Exemple #1
2
class DragPlotWidget(QFrame):
    ''' draggable widget plotting data and
    a combo box to choose channel
    '''
    
    def __init__(self, parent=None):
        super(DragPlotWidget, self).__init__(parent)
        
        # transparent fill color and a frame with size 400x250 
        self.setStyleSheet("QFrame {  border: 2px solid black; background-image: url(); }")
        self.setGeometry(1,1,400,250)
        
        # arrange elements in a gridLayout
        l = QGridLayout()
        self.setLayout(l)
        
        self.p = pq.PlotWidget(self)
        self.p.setYRange(-0.0002, 0.0002)
        self.pl1 = self.p.plot(np.linspace(0,3.4, 1000))  # initial plot
        
        self.box = QComboBox(self)
        self.box.addItems(["EMG " + str(x+1) for x in range(16)])
        self.box.currentIndexChanged.connect(self.changeChannel)
        
        l.addWidget(self.p)
        l.addWidget(self.box)
        
        self.dragPos = QPoint(0,0)
        
    def mousePressEvent(self, e):
        ''' enter drag mode by left click and save position '''
        if e.buttons() != Qt.LeftButton:
            return
        self.dragPos = e.pos()
        
    def mouseMoveEvent(self, e):
        ''' move by holding left mouse button and update position
        - removing offset by subtracting saved dragPos
        '''
        if e.buttons() != Qt.LeftButton:
            return
        position = e.pos() + self.pos() - self.dragPos
        self.move(position)
        self.update()
        self.parent().update()
    
    def mouseReleaseEvent(self, e):
        ''' release left mouse button and exit drag mode '''
        if e.buttons() != Qt.LeftButton:
            return
        position = e.pos() + self.pos() - self.dragPos
        self.move(position)
    
    def changeChannel(self, index):
        ''' change channel to index and clear plot '''
        self.p.plot([0], clear=True)
    
    def updatePlot(self, data):
        ''' plot new data '''
        self.p.plot(data[self.box.currentIndex()], clear=True)
Exemple #2
1
    def setup_toolbar(self):
        color_widget = ColorWidget()
        color_widget.color_changed.connect(self.fourier.on_color_change)
        self.toolBar.addWidget(QLabel("Color:"))
        self.toolBar.addWidget(color_widget)

        self.toolBar.addWidget(QLabel("Shape:"))
        size_spin = QSpinBox(self.toolBar)
        size_spin.setValue(20)
        size_spin.valueChanged[int].connect(self.fourier.on_size_change)

        shape_combo = QComboBox(self.toolBar)
        shape_combo.activated[str].connect(self.fourier.on_shape_change)
        shape_combo.addItems(brush_shapes)

        self.toolBar.addWidget(shape_combo)
        self.toolBar.addWidget(size_spin)

        self.toolBar.addWidget(QLabel("Symmetry:"))
        x_sym = QCheckBox(self.toolBar)
        x_sym.toggled.connect(self.fourier.on_x_toggle)

        opp_sym = QCheckBox(self.toolBar)
        opp_sym.toggled.connect(self.fourier.on_opp_toggle)
        self.toolBar.addWidget(QLabel("X"))
        self.toolBar.addWidget(x_sym)

        y_sym = QCheckBox(self.toolBar)
        y_sym.toggled.connect(self.fourier.on_y_toggle)
        self.toolBar.addWidget(QLabel("Y"))
        self.toolBar.addWidget(y_sym)
        self.toolBar.addWidget(QLabel("Center"))
        self.toolBar.addWidget(opp_sym)
Exemple #3
0
class aLabeledPopup(QWidget):
    def __init__(self, var, text, item_list, pos = "side", max_size = 200):
        QWidget.__init__(self)
        self.setContentsMargins(1, 1, 1, 1)
        if pos == "side":
            self.layout1=QHBoxLayout()
        else:
            self.layout1 = QVBoxLayout()
        self.layout1.setContentsMargins(1, 1, 1, 1)
        self.layout1.setSpacing(1)
        self.setLayout(self.layout1)
        
        self.item_combo = QComboBox()
        self.item_combo.addItems(item_list)
        self.item_combo.setFont(QFont('SansSerif', 12))
        self.label = QLabel(text)
        # self.label.setAlignment(Qt.AlignLeft)
        self.label.setFont(QFont('SansSerif', 12))
        self.layout1.addWidget(self.label)
        self.layout1.addWidget(self.item_combo)
        self.var = var
        self.item_combo.textChanged.connect(self.when_modified)
        self.item_combo.currentIndexChanged.connect(self.when_modified)
        self.when_modified()
        
    def when_modified(self):
        self.var.set(self.item_combo.currentText())
        
    def hide(self):
        QWidget.hide(self)
Exemple #4
0
    def setup_toolbar(self):
        color_widget = ColorWidget()
        color_widget.color_changed.connect(self.fourier.on_color_change)
        self.toolBar.addWidget(QLabel("Color:"))
        self.toolBar.addWidget(color_widget)

        self.toolBar.addWidget(QLabel("Shape:"))
        size_spin = QSpinBox(self.toolBar)
        size_spin.setValue(20)
        size_spin.valueChanged[int].connect(self.fourier.on_size_change)

        shape_combo = QComboBox(self.toolBar)
        shape_combo.activated[str].connect(self.fourier.on_shape_change)
        shape_combo.addItems(brush_shapes)

        self.toolBar.addWidget(shape_combo)
        self.toolBar.addWidget(size_spin)

        self.toolBar.addWidget(QLabel("Symmetry:"))
        x_sym = QCheckBox(self.toolBar)
        x_sym.toggled.connect(self.fourier.on_x_toggle)

        opp_sym = QCheckBox(self.toolBar)
        opp_sym.toggled.connect(self.fourier.on_opp_toggle)
        self.toolBar.addWidget(QLabel("X"))
        self.toolBar.addWidget(x_sym)

        y_sym = QCheckBox(self.toolBar)
        y_sym.toggled.connect(self.fourier.on_y_toggle)
        self.toolBar.addWidget(QLabel("Y"))
        self.toolBar.addWidget(y_sym)
        self.toolBar.addWidget(QLabel("Center"))
        self.toolBar.addWidget(opp_sym)
Exemple #5
0
class AddScenarioDlg(QDialog):

	def __init__(self, root_node, parent=None):
		super(AddScenarioDlg, self).__init__(parent)
		self.setWindowTitle("Add Scenario")
		
		type_label = QLabel("&Scenario Type:")
		self.type_combobox = QComboBox()
		type_label.setBuddy(self.type_combobox)
		self.type_combobox.addItems(["External Fire", "Liquid Overfill", "Regulator Failure"])
		device_label = QLabel("&Associated Relief Device:")
		self.device_combobox = QComboBox()
		device_label.setBuddy(self.device_combobox)
		for area in root_node.children:
			for device in area.children:
				self.device_combobox.addItem(device.name, device)
		button_box = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
			
		layout = QGridLayout()
		layout.addWidget(type_label, 0, 0)
		layout.addWidget(self.type_combobox, 0, 1)
		layout.addWidget(device_label, 1, 0)
		layout.addWidget(self.device_combobox, 1, 1)
		layout.addWidget(button_box, 2, 1)
		self.setLayout(layout)
		
		button_box.accepted.connect(self.accept)
		button_box.rejected.connect(self.reject)
		
	def returnVals(self):
		return (self.type_combobox.currentText(), self.device_combobox.itemData(self.device_combobox.currentIndex()))
class ChooseMarkerDialog(QDialog):
	def __init__(self,markers):
		super(ChooseMarkerDialog, self).__init__()
		self.setWindowTitle('Select final marker...')
		markerLabel			= QLabel('Marker:')
		self.marker			= QComboBox()
		self.marker.addItems(markers)
		self.marker.setCurrentIndex(-1)
		layout				= QGridLayout()
		layout.addWidget(markerLabel,0,0)
		layout.addWidget(self.marker,0,1)
		self.buttons		= QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)	
		self.buttons.accepted.connect(self.accept)
		self.buttons.rejected.connect(self.reject)
		layout.addWidget(self.buttons,100,0,1,2)
		self.setLayout(layout)
	def getMarker(self):
		return self.marker.currentText()
 
	@staticmethod
	def run(markers,parent = None):
		dialog				= ChooseMarkerDialog(markers)
		result				= dialog.exec_()
		marker				= dialog.getMarker()
		return (marker,result == QDialog.Accepted)
Exemple #7
0
class AddFilterDlg(QDialog):
	
	def __init__(self, parent=None):
		super(AddFilterDlg, self).__init__(parent)
		self.setWindowTitle("Advanced Filtering Options")
		
		note_label = QLabel("NOTE: These filtering options apply exclusively to relief devices, not to the relief device area they belong to or to their scenarios.")
		pressure_label = QLabel("Filter where <b>Set Pressure</b> is")
		self.pressure_combobox = QComboBox()
		self.pressure_combobox.addItems(["Greater Than", "Less Than", "Equal To", "Not Equal To"])
		self.pressure_value = QDoubleSpinBox()
		pressure_layout = QHBoxLayout()
		pressure_layout.addWidget(pressure_label)
		pressure_layout.addWidget(self.pressure_combobox)
		pressure_layout.addWidget(self.pressure_value)
		button_box = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
		
		layout = QGridLayout()
		layout.addWidget(note_label, 0, 0)
		layout.addLayout(pressure_layout, 1, 0)
		layout.addWidget(button_box, 2, 0)
		self.setLayout(layout)
		
		button_box.accepted.connect(self.accept)
		button_box.rejected.connect(self.reject)
		
	def returnVals(self):
		return (self.pressure_combobox.currentText(), self.pressure_value.value())
Exemple #8
0
	def newCombo(self):
		taskList  = [u'--請選擇--', u'值班', u'救護勤務', u'備勤', u'待命服勤', u'水源查察', u'消防查察', u'宣導勤務', u'訓(演)練', u'專案勤務', u'南山救護站']
		nComboBox = QComboBox()
		nComboBox.addItems(taskList)
		for i in xrange(len(taskList)):
			if i == 0:
				nComboBox.setItemData(i, QColor('#550000'), Qt.BackgroundColorRole)
			nComboBox.setItemData(i, Qt.AlignCenter, Qt.TextAlignmentRole)
		nComboBox.setStyleSheet("text-align: right; font: bold 13px;")		
		return nComboBox
 def addFilter(self):
     """ Add Filter Label and Combo Box to the UI """
     label = QLabel("Filter: ", self.toolbar)
     self.toolbar.addWidget(label)
     comboBox = QComboBox(self.toolbar)
     comboBox.addItems(__filter_order__)
     comboBox.activated.connect(self.setTransactionFilter)
     index = [__transaction_filters__[filterText] for filterText in __filter_order__].index(self.table_view.filters)
     comboBox.setCurrentIndex(index)
     self.toolbar.addWidget(comboBox)
 def createEditor(self, parent, option, index):
     current_column = GridManagerColumns.Columns[index.column()]
     # Using a combobox to the planes.
     if( current_column == GridManagerColumns.Plane ):
         combo_plane = QComboBox( parent )
         combo_plane.addItems( GridPlanes.Planes )
         return combo_plane
     else:
         # The rest of the controls are fine with the standard control
         return super(VoxelGridDelegate,self).createEditor(parent, option, index)
class DateToolbarSection:
    """ Represents the Date Toolbar Section """
    
    def __init__(self, toolbar, panel):
        """ Initialize the Date Toolbar Section """
        self.toolbar = toolbar
        self.panel = panel
        
    def addDateSection(self):
        """ Add Date Section """
        self.dateLabel = QLabel("Month: ", self.toolbar)
        self.toolbar.addWidget(self.dateLabel)
        self.setupMonthComboBox()
        self.setupYearComboBox()
        
    def setupMonthComboBox(self):
        """ Setup the month combo box """
        self.monthComboBox = QComboBox(self.toolbar)
        self.monthComboBox.addItems(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"])
        self.monthComboBox.activated.connect(self.setMonth)
        self.monthComboBox.setCurrentIndex(self.getCategoryStatistics().month-1)
        self.toolbar.addWidget(self.monthComboBox)
        
    def setupYearComboBox(self):
        """ Setup the year combo box """
        self.yearComboBox = QComboBox(self.toolbar)
        self.getTransactionYears()
        self.yearComboBox.addItems([str(year) for year in self.transactionYears])
        self.yearComboBox.activated.connect(self.setYear)
        self.yearComboBox.setCurrentIndex(self.transactionYears.index(self.getCategoryStatistics().year))
        self.toolbar.addWidget(self.yearComboBox)
    
    def getTransactionYears(self):
        """ Get the possible transacttion years """
        self.transactionYearsSet = Transactions.getAllYears()
        self.transactionYearsSet.add(self.getCategoryStatistics().year)
        self.transactionYears = list(self.transactionYearsSet)
        self.transactionYears.sort()
    
    def setMonth(self, index):
        """ Set the month """
        categoryStatistics = self.getCategoryStatistics()
        categoryStatistics.month = index+1
        self.panel.updatePanel()
    
    def setYear(self, index):
        """ Set the year """
        categoryStatistics = self.getCategoryStatistics()
        categoryStatistics.year = int(self.yearComboBox.currentText())
        self.panel.updatePanel()
        
    def getCategoryStatistics(self):
        """ Returns the Category Statistics """
        return self.panel.categoryStatistics
class SearchFile(QWidget):
    def __init__(self):
        '''
            Creates GUI
        '''
        QWidget.__init__(self)
        self.setWindowTitle("Search window")
        self.fn1 = ""
        self.fn2 = ""
        L1 = []
        L2 = []
        st = os.getcwd()
        L = os.listdir(st)
        for filenames in L:
            if (".txt" in filenames):
                L1.append(filenames)
            if (".csv" in filenames):
                L2.append(filenames)
        self.files1 = QComboBox()
        self.files2 = QComboBox()
        #self.files1.setText("SatelliteDataFile")
        #print(self.files1)
        #print(self.files2)
        self.files1.addItems(L1)
        self.files1.setCurrentIndex(-1)
        self.files2 = QComboBox()
        self.files2.addItems(L2)
        self.files2.setCurrentIndex(-1)
        self.files1.currentIndexChanged.connect(
            lambda: self.returnString(self.files1))

        self.files2.currentIndexChanged.connect(
            lambda: self.returnString(self.files2))
        self.setUpUI()

    def setUpUI(self):
        layout = QVBoxLayout()
        form = QFormLayout()
        form.addRow(QLabel("text file"), self.files1)
        form.addRow(QLabel(".csv file"), self.files2)
        layout.addLayout(form)
        self.setLayout(layout)

    def returnString(self, files):
        #print(files)
        if (files == self.files1):
            self.fn1 = str(self.files1.currentText())
        else:
            self.fn2 = str(self.files2.currentText())
class CreateSamplesRow():
	def __init__(self):
		self.plate			= QLineEdit()
		self.parents		= QSpinBox()
		self.samples		= QSpinBox()
		self.loadedBy		= QComboBox()
		self.parents.setMaximum(8)
		self.parents.setValue(2)
		self.samples.setMaximum(96)
		self.samples.setValue(94)
		self.loadedBy.addItems(['Column','Row'])
	def getPlate(self):			return self.plate.text()
	def getParents(self):		return self.parents.value()
	def getSamples(self):		return self.samples.value()
	def getLoadedBy(self):		return self.loadedBy.currentText()
Exemple #14
0
class ScenarioPage(QWidget):

	def __init__(self, parent=None):
		super(ScenarioPage, self).__init__(parent)
		
		reqflow_label = QLabel("Required Flow:")
		self.reqflow_spinbox = QSpinBox()
		maxflow_label = QLabel("Maximum Flow:")
		self.maxflow_spinbox = QSpinBox()
		type_label = QLabel("Vapor or Liquid?:")
		self.type_combobox = QComboBox()
		self.type_combobox.addItems(["Vapor", "Liquid"])
		pdropinlet_label = QLabel("% Pressure Drop (Inlet)")
		self.pdropinlet_spinbox = QSpinBox()
		pdropoutlet_label = QLabel("% Pressure Drop (Outlet)")
		self.pdropoutlet_spinbox = QSpinBox()
		
		layout = QGridLayout()
		layout.addWidget(reqflow_label, 0, 0)
		layout.addWidget(self.reqflow_spinbox, 0, 1)
		layout.addWidget(maxflow_label, 1, 0)
		layout.addWidget(self.maxflow_spinbox, 1, 1)
		layout.addWidget(type_label, 2, 0)
		layout.addWidget(self.type_combobox, 2, 1)
		layout.addWidget(pdropinlet_label, 3, 0)
		layout.addWidget(self.pdropinlet_spinbox, 3, 1)
		layout.addWidget(pdropoutlet_label, 4, 0)
		layout.addWidget(self.pdropoutlet_spinbox, 4, 1)
		self.setLayout(layout)
		
		self.mapper = QDataWidgetMapper()
		
	def setModel(self, proxy_model):
		self.proxy_model = proxy_model
		self.mapper.setModel(self.proxy_model.sourceModel())
		self.mapper.addMapping(self.reqflow_spinbox, 2)
		self.mapper.addMapping(self.maxflow_spinbox, 3)
		self.mapper.addMapping(self.type_combobox, 4, "currentIndex")
		self.mapper.addMapping(self.pdropinlet_spinbox, 5)
		self.mapper.addMapping(self.pdropoutlet_spinbox, 6)
		
	def setSelection(self, current):
		current = self.proxy_model.mapToSource(current)
		parent = current.parent()
		self.mapper.setRootIndex(parent)
		self.mapper.setCurrentModelIndex(current)
Exemple #15
0
    def _fill_table(self):
        colors = ["yellow", "orange", "green", "red"]

        dimensions = self._parser_result.get_dimensions()
        row = 0
        for dimension in dimensions:
            dimension_name = QLabel(dimension[0])
            dimension_name.setStyleSheet("background: %s" % colors[row % len(colors)])
            self.table_widget.setCellWidget(row, 0, dimension_name)
            choices_widget = QComboBox()
            choices = dimension[1]
            choices.insert(0, "No choice")
            choices_widget.addItems(choices)
            choices_widget.setStyleSheet("background: white")
            choices_widget.setStyleSheet("border: none")
            choices_widget.currentIndexChanged.connect(self.on_choice_change)
            self.table_widget.setCellWidget(row, 1, choices_widget)
            row += 1
Exemple #16
0
class DevicePage(QWidget):

	def __init__(self, node, parent=None):
		super(DevicePage, self).__init__(parent)
		
		name_label = QLabel("Name:")
		self.name_lineedit = QLineEdit()
		setpressure_label = QLabel("Set Pressure:")
		#self.setpressure_spinbox = QDoubleSpinBox()
		self.setpressure_spinbox = CustomDoubleSpinBox(node, parent, setpressure_label.text())
		modelnum_label = QLabel("Model Number:")
		#self.modelnum_lineedit = QLineEdit()
		self.modelnum_lineedit = CustomLineEdit(node, parent, modelnum_label.text())
		orient_label = QLabel("Orientation:")
		self.orient_combobox = QComboBox()
		self.orient_combobox.addItems(["Horizontal", "Vertical"])
		
		layout = QGridLayout()
		layout.addWidget(name_label, 0, 0)
		layout.addWidget(self.name_lineedit, 0, 1)
		layout.addWidget(setpressure_label, 1, 0)
		layout.addWidget(self.setpressure_spinbox, 1, 1)
		layout.addWidget(modelnum_label, 2, 0)
		layout.addWidget(self.modelnum_lineedit, 2, 1)
		layout.addWidget(orient_label, 3, 0)
		layout.addWidget(self.orient_combobox, 3, 1)
		self.setLayout(layout)
		
		self.mapper = QDataWidgetMapper()
		
	def setModel(self, proxy_model):
		self.proxy_model = proxy_model
		self.mapper.setModel(self.proxy_model.sourceModel())
		self.mapper.addMapping(self.name_lineedit, 0)
		self.mapper.addMapping(self.setpressure_spinbox, 2)
		self.mapper.addMapping(self.modelnum_lineedit, 3)
		self.mapper.addMapping(self.orient_combobox, 4, "currentIndex")
		
	def setSelection(self, current):
		current = self.proxy_model.mapToSource(current)
		parent = current.parent()
		self.mapper.setRootIndex(parent)
		self.mapper.setCurrentModelIndex(current)
class SimpleComboboxOption(SimpleOption):
    def __init__(self, settingsName, labelText, defaultValue, checkable=False, *options):
        self.options = options
        super(SimpleComboboxOption,self).__init__(settingsName, labelText, defaultValue, checkable)
    def editor(self, defaultValue):
        #options = ('Uniform','Exponential','Normal','Log Normal')
        options = self.options
        self.combo = QComboBox()
        self.combo.addItems(options)
        self.combo.setCurrentIndex(int(QSettings().value(self.settingsName, defaultValue)))
        self.combo.setToolTip('Default value: %s' % defaultValue)
        #self.combo.setAlignment(Qt.AlignLeft|Qt.AlignTop)
        self.layout().addWidget(self.combo)
    def setEnabled(self, e):
        self.combo.setEnabled(e)
    def getValue(self):
        return self.combo.currentIndex()
    def getName(self):
        return self.combo.currentText()
Exemple #18
0
class LCRow():
	def __init__(self,fileName,experimentName,guess):
		self.fileName		= QLabel(fileName)
		self.plateID		= QLineEdit()
		self.experiment		= QLineEdit()
		self.guess			= QLabel(guess[0] + ', ' + guess[1])
		self.robot			= QComboBox()
		self.platePosition	= QComboBox()
		
		self.plateID.setText(path.splitext(path.basename(fileName))[0])
		self.experiment.setText(experimentName)
		self.robot.addItems(['2000','FX','96'])
		self.robot.setCurrentIndex(self.robot.findText(guess[0]))
		self.platePosition.addItems(['Plate 0','Plate 1','Plate 2','Plate 3','Plate 4'])
		self.platePosition.setCurrentIndex(self.platePosition.findText(guess[1]))
	def getFileName(self):		return self.fileName.text()
	def getPlateID(self):		return self.plateID.text()
	def getExperiment(self):	return self.experiment.text()
	def getRobot(self):			return self.robot.currentText()
	def getPlatePosition(self):	return self.platePosition.currentIndex()
class AnalysisSelector(QWidget):
    def __init__(self, my_parent, max_size = 200):
        QWidget.__init__(self)
        myframe = QHBoxLayout()
        self.setLayout(myframe)
        self.popup = QComboBox()
        self.popup.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        myframe.addWidget(self.popup)
        myframe.addStretch()
        self.my_parent = my_parent
        self.popup.addItems(self.my_parent._lcvsa_dict.keys())
        self.popup.setFont(QFont('SansSerif', 12))
        self.popup.currentIndexChanged.connect(self.when_modified)
        self.when_modified()
        
    def when_modified(self):
        self.my_parent._lcvsa  = self.my_parent._lcvsa_dict[self.popup.currentText()]
        self.my_parent.gprint("Working with analysis %s" % self.popup.currentText(), "h2")
        
    def hide(self):
        QWidget.hide(self)
Exemple #20
0
class ChoiceField(BaseInputField):
    def __init__(self, choices, initial="", label=""):
        super(ChoiceField, self).__init__(initial, label)
        self._choices = choices

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

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

    def get_value_from(self, widget):
        return widget.currentText()
Exemple #21
0
class ChoiceField(BaseInputField):
    def __init__(self, choices, initial="", label=""):
        super(ChoiceField, self).__init__(initial, label)
        self._choices = choices

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

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

    def get_value_from(self, widget):
        return widget.currentText()
Exemple #22
0
class ImportMovementFilter(QtGui.QWidget):
    def __init__(self, parent):
        super(self.__class__, self).__init__()
        self.parent = parent
        self.layout = QtGui.QGridLayout(self)
        #btnfileFinder
        self.btnfileFinder = QtGui.QPushButton("File")
        self.layout.addWidget(self.btnfileFinder, 1, 0)
        #txtFile
        self.txtFile = QLineEdit(self)
        self.layout.addWidget(self.txtFile, 1, 1)
        #lblAssetName
        self.lblAssetName = QLabel("Asset Name")
        self.layout.addWidget(self.lblAssetName, 2, 0)
        #cmdAssetName
        self.cmdAssetName = QComboBox(self)
        self.cmdAssetName.addItems(DaoReportMovement.getAssetNames())
        self.cmdAssetName.setCurrentIndex(self.cmdAssetName.findText("ALL"))
        self.layout.addWidget(self.cmdAssetName, 2, 1)
        #btnSubmit
        self.btnSubmit = QPushButton("Submit", self)
        self.btnSubmit.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.layout.addWidget(self.btnSubmit)
        self.setFixedSize(190, 150)
        self.initListener()

    def initListener(self):
        self.btnSubmit.clicked.connect(self.doSubmit)
        self.btnfileFinder.clicked.connect(self.doFile)
        self.btnfileFinder.show()

    def doSubmit(self):
        assetName = self.cmdAssetName.currentText()
        self.parent.doSubmit(self.txtFile.text(), assetName)

    def doFile(self):
        filePath = QtGui.QFileDialog.getOpenFileName()
        self.txtFile.setText(filePath[0])
Exemple #23
0
class Server(QGroupBox):
    def __init__(self, parent=None, opc=None, tag_selection=None):
        super(Server, self).__init__()

        self.opc = opc
        self.tag_selection = tag_selection

        self.setTitle('OPC Server Selection')

        self.layout = QHBoxLayout(self)

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

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

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

        self.setLayout(self.layout)

        self._refresh()

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

    def _connect(self):
        server = self.combobox_server.currentText()
        connected = opcda.connect(self.opc, server)
        if connected:
            if self.tag_selection:
                self.tag_selection._refresh()
class AnimMungeDialog(QDialog):
    types = ['FirstPerson/Soldier',
            'Prop/Vehicle']
    types2 = {'FirstPerson/Soldier': '/comp_debug 0 /debug',
                'Prop/Vehicle': '/specialquathack'}

    def __init__(self, files, main, parent=None):
        super(AnimMungeDialog, self).__init__(parent)
        self.outd = os.getcwd() + '\\munge\\output'
        self.ind = os.getcwd() + '\\munge\\input'
        self.files = files
        self.clear_input_files()
        self.clear_output_files()
        for filename in self.files:
            shutil.copy(filename, self.ind)
        self.initUI()

    def munge(self):
        self.statlabel.setText('<b>AnimMunging</b>')
        params = self.types2[self.type_box.currentText()]
        add_params = ''
        if self.add_params.text() != 'Additional Params':
            add_params = ' {0}'.format(self.add_params.text())
        if self.bf1mode.isChecked():
            os.system(os.getcwd() + '\\zenasset1.exe /multimsh /src {0}{1} /keepframe0 {2} /dest {3}\\{4}.zaf'.format(self.ind, add_params, params, self.outd, self.animname.text()))
            os.system(os.getcwd() + '\\binmunge1.exe -inputfile munge\\output\\*.zaa -chunkid zaa_ -ext zaabin -outputdir {1}\\'.format(self.outd, self.outd))
            os.system(os.getcwd() + '\\binmunge1.exe -inputfile munge\\output\\*.zaf -chunkid zaf_ -ext zafbin -outputdir {1}\\'.format(self.outd, self.outd))
        else:
            os.system(os.getcwd() + '\\zenasset.exe /multimsh /writefiles /src {0}{1} /keepframe0 {2} /dest {3}\\{4}.zaf'.format(self.ind, add_params, params, self.outd, self.animname.text()))
            os.system(os.getcwd() + '\\binmunge.exe -inputfile munge\\output\\*.zaa -chunkid zaa_ -ext zaabin -outputdir {1}'.format(self.outd, self.outd))
            os.system(os.getcwd() + '\\binmunge.exe -inputfile munge\\output\\*.zaf -chunkid zaf_ -ext zafbin -outputdir {1}'.format(self.outd, self.outd))
        self.clear_byproduct()
        files = []
        for filename in os.listdir(self.outd):
            files.append(filename)
        self.outfiles.addItems(files)
        self.statlabel.setText('<b>AnimMunged</b>')

    def initUI(self):
        grp = QGroupBox('Anim Munge')
        grplay = QGridLayout()
        self.bf1mode = QCheckBox()
        grplay.addWidget(QLabel('<b>SWBF1</b>'), 0, 1)
        grplay.addWidget(self.bf1mode, 0, 2)
        grplay.addWidget(QLabel('<b>Input</b>'), 1, 1)
        grplay.addWidget(QLabel('<b>Output</b>'), 1, 3)
        self.infiles = QListWidget()
        self.infiles.setMinimumWidth(150)
        self.infiles.addItems([os.path.basename(item) for item in self.files])
        grplay.addWidget(self.infiles, 2, 1, 1, 2)
        self.outfiles = QListWidget()
        self.outfiles.setMinimumWidth(150)
        grplay.addWidget(self.outfiles, 2, 3, 1, 2)
        self.add_params = QLineEdit()
        self.add_params.setText('Additional Params')
        self.add_params.setToolTip('<b>Additional Munge Parameters.</b> Like scale 1.5')
        grplay.addWidget(self.add_params, 0, 3, 1, 2)

        self.statlabel = QLabel('<b>AnimMunger</b>')
        grplay.addWidget(self.statlabel, 4, 1, 1, 1)
        self.animname = QLineEdit()
        self.animname.setText('AnimName')
        self.animname.setToolTip('<b>Animation Name.</b> Name of the final animation files. IE: name.zafbin, name.zaabin, name.anims.')
        grplay.addWidget(self.animname, 3, 1)
        self.type_box = QComboBox()
        self.type_box.addItems(self.types)
        self.type_box.setToolTip('<b>Munge Mode.</b> This switches munge parameters.')
        grplay.addWidget(QLabel('<b>Munge Mode:</b>'), 3, 2)
        grplay.addWidget(self.type_box, 3, 3, 1, 2)
        munge_btn = QPushButton('Munge')
        munge_btn.clicked.connect(self.munge)
        munge_btn.setToolTip('<b>Munge.</b> Munges the input files with the selected mode.')
        grplay.addWidget(munge_btn, 4, 2)
        save_out = QPushButton('Save')
        save_out.clicked.connect(self.save)
        save_out.setToolTip('<b>Save.</b> Saves the output files.')
        grplay.addWidget(save_out, 4, 3)
        cancel_btn = QPushButton('Cancel')
        cancel_btn.clicked.connect(self.cancel)
        cancel_btn.setToolTip('<b>Cancel.</b> Closes the dialog and removes all temporary files.')
        grplay.addWidget(cancel_btn, 4, 4)

        grp.setLayout(grplay)

        mainlay = QVBoxLayout()
        mainlay.addWidget(grp)

        self.setLayout(mainlay)
        self.setGeometry(340, 340, 320, 300)
        self.setWindowTitle('MSH Suite - Animation Munge')
        self.show()

    def save(self):
        filepath = QFileDialog.getExistingDirectory(self, 'Select .MSH', os.getcwd())
        for filename in os.listdir(self.outd):
            shutil.copy(os.path.join(self.outd, filename), filepath)
        self.cancel()

    def cancel(self):
        self.statlabel.setText('<b>AnimSeeYa</b>')
        self.clear_input_files()
        self.clear_output_files()
        self.close()

    def clear_byproduct(self):
        for filename in os.listdir(self.outd):
            if filename.split('.')[-1] in ('zaa', 'zaf'):
                os.unlink(os.path.join(self.outd, filename))

    def clear_output_files(self):
        for filename in os.listdir(self.outd):
            filepath = os.path.join(self.outd, filename)
            try:
                if os.path.isfile(filepath):
                    os.unlink(filepath)
            except Exception, e:
                print e
class MovementEditor(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setGeometry(QRect(100, 100, 400, 200))
        self.layout = QtGui.QGridLayout(self)
        #lblAssetType
        self.lblAssetType = QLabel("Asset Type")
        self.layout.addWidget(self.lblAssetType, 0, 0)
        #cmdAssetType
        self.cmdAssetType = QComboBox(self)
        self.cmdAssetType.addItems(DaoAsset().getAssetTypes())
        self.layout.addWidget(self.cmdAssetType, 0, 1)
        #lblAssetName
        self.lblAssetName = QLabel("Asset Name")
        self.layout.addWidget(self.lblAssetName, 1, 0)
        #cmdAssetName
        self.cmdAssetName = QComboBox(self)
        self.layout.addWidget(self.cmdAssetName, 1, 1)
        #lblCustody
        self.lblCustody = QLabel("Custody")
        self.layout.addWidget(self.lblCustody, 2, 0)
        #cmbCustody
        self.cmbCustody = QComboBox(self)
        custodyList = DaoCustody().getCustodyList()
        for (row) in custodyList:
            self.cmbCustody.addItem(row[1], row[0])
        self.layout.addWidget(self.cmbCustody, 2, 1)
        #lblBuySell
        self.lblBuySell = QLabel("Buy Sell")
        self.layout.addWidget(self.lblBuySell, 3, 0)
        #cmdBuySell
        self.cmdBuySell = QComboBox(self)
        self.cmdBuySell.addItem("BUY")
        self.cmdBuySell.addItem("SELL")
        self.layout.addWidget(self.cmdBuySell, 3, 1)
        #lblByAmount
        self.lblByAmount = QLabel("By Amount")
        self.layout.addWidget(self.lblByAmount, 4, 0)
        #chkByAmount
        self.chkByAmount = QCheckBox(self)
        self.layout.addWidget(self.chkByAmount, 4, 1)
        #lblGrossAmount
        self.lblGrossAmount = QLabel("Gross Amount")
        self.layout.addWidget(self.lblGrossAmount, 5, 0)
        #txtGrossAmount
        self.txtGrossAmount = QLineEdit(self)
        self.txtGrossAmount.setValidator(QDoubleValidator(
            0, 99999999, 6, self))
        self.layout.addWidget(self.txtGrossAmount, 5, 1)
        #lblAcquisitionDate
        self.lblAcquisitionDate = QLabel("Acquisition Date")
        self.layout.addWidget(self.lblAcquisitionDate, 6, 0)
        #cmdAcquisitionDate
        self.dateAcquisitionDate = QDateEdit(self)
        self.dateAcquisitionDate.setDisplayFormat("dd-MM-yyyy")
        self.dateAcquisitionDate.setDate(datetime.datetime.now())
        self.layout.addWidget(self.dateAcquisitionDate, 6, 1)
        #lblQuantity
        self.lblQuantity = QLabel("Quantity")
        self.layout.addWidget(self.lblQuantity, 7, 0)
        #txtQuantity
        self.txtQuantity = QLineEdit(self)
        self.txtQuantity.setValidator(QIntValidator(0, 1000000000, self))
        self.layout.addWidget(self.txtQuantity, 7, 1)
        #lblPrice
        self.lblPrice = QLabel("Price")
        self.layout.addWidget(self.lblPrice, 8, 0)
        #txtPrice
        self.txtPrice = QLineEdit(self)
        self.txtPrice.setValidator(QDoubleValidator(0, 99999999, 6, self))
        self.layout.addWidget(self.txtPrice, 8, 1)
        #lblRate
        self.lblRate = QLabel("Rate")
        self.layout.addWidget(self.lblRate, 9, 0)
        #txtRate
        self.txtRate = QLineEdit(self)
        self.txtRate.setValidator(QDoubleValidator(0, 99999999, 4, self))
        self.txtRate.setEnabled(0)
        self.layout.addWidget(self.txtRate, 9, 1)
        #lblNetAmount
        self.lblNetAmount = QLabel("Net Amount")
        self.layout.addWidget(self.lblNetAmount, 10, 0)
        #txtNetAmount
        self.txtNetAmount = QLineEdit(self)
        self.txtNetAmount.setEnabled(0)
        self.txtNetAmount.setValidator(QDoubleValidator(0, 99999999, 6, self))
        self.layout.addWidget(self.txtNetAmount, 10, 1)
        #lblCommissionPercentage
        self.lblCommissionPercentage = QLabel("Commission Percentage")
        self.layout.addWidget(self.lblCommissionPercentage, 11, 0)
        #txtCommissionPercentage
        self.txtCommissionPercentage = QLineEdit(self)
        self.txtCommissionPercentage.setValidator(
            QDoubleValidator(0, 9999999, 6, self))
        self.layout.addWidget(self.txtCommissionPercentage, 11, 1)
        #lblCommissionAmount
        self.lblCommissionAmount = QLabel("Commission Amount")
        self.layout.addWidget(self.lblCommissionAmount, 12, 0)
        #txtCommissionAmmount
        self.txtCommissionAmount = QLineEdit(self)
        self.txtCommissionAmount.setEnabled(0)
        self.txtCommissionAmount.setValidator(
            QDoubleValidator(0, 9999999, 6, self))
        self.layout.addWidget(self.txtCommissionAmount, 12, 1)
        #lblCommissionAmount
        self.lblCommissionVATAmount = QLabel("Commission VAT Amount")
        self.layout.addWidget(self.lblCommissionVATAmount, 13, 0)
        #txtCommissionAmmount
        self.txtCommissionVATAmount = QLineEdit(self)
        self.txtCommissionVATAmount.setEnabled(0)
        self.txtCommissionVATAmount.setValidator(
            QDoubleValidator(0, 9999999, 6, self))
        self.layout.addWidget(self.txtCommissionVATAmount, 13, 1)
        #lblTenor
        self.lblTenor = QLabel("Tenor")
        self.layout.addWidget(self.lblTenor, 14, 0)
        #txtTenor
        self.txtTenor = QLineEdit(self)
        self.txtTenor.setEnabled(0)
        self.txtTenor.setValidator(QDoubleValidator(0, 9999999, 0, self))
        self.layout.addWidget(self.txtTenor, 14, 1)
        #btnAdd
        self.btnAdd = QPushButton("Add", self)
        self.layout.addWidget(self.btnAdd)
        #btnClear
        self.btnClear = QPushButton("Clear", self)
        self.layout.addWidget(self.btnClear)
        #clearEditor
        self.clearEditor()
        self.initListener()

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

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

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

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

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

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

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

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

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

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

    def calculateGrossAmount(self):
        quantity = self.txtQuantity.text()
        price = self.txtPrice.text()
        if (not self.chkByAmount.isChecked()) and (
                quantity is not u"" or None) and (price is not u"" or None):
            self.txtGrossAmount.setText(
                str('{0:.6f}'.format(float(quantity) * float(price))))
        self.calculateCommission()
Exemple #26
0
class ColorMapWidget(QWidget):
    """Interface for changing ColorMap information. It shows the current
       color map selection, a selector for other colormaps, and the option
       to cycle the color map by any number of ordinal values.

       This widget was designed for use with the tab dialog. It can be used by
       itself or it can be used as part of a bigger color tab.

       Changes to this widget are emitted via a changeSignal as a ColorMap
       object and this widget's tag.
    """

    changeSignal = Signal(ColorMap, str)

    def __init__(self, parent, initial_map, tag):
        """Creates a ColorMap widget.

           parent
               The Qt parent of this widget.

           initial_map
               The colormap set on creation.

           tag
               A name for this widget, will be emitted on change.
        """
        super(ColorMapWidget, self).__init__(parent)
        self.color_map = initial_map.color_map
        self.color_map_name = initial_map.color_map_name
        self.color_step = initial_map.color_step
        self.step_size = initial_map.step_size
        self.tag = tag

        self.color_map_label = "Color Map"
        self.color_step_label = "Cycle Color Map"
        self.number_steps_label = "Colors"

        self.color_step_tooltip = "Use the given number of evenly spaced " \
            + " colors from the map and assign to discrete values in cycled " \
            + " sequence."

        layout = QVBoxLayout()

        layout.addWidget(self.buildColorBarControl())
        layout.addItem(QSpacerItem(5,5))
        layout.addWidget(self.buildColorStepsControl())

        self.setLayout(layout)

    def buildColorBarControl(self):
        """Builds the portion of this widget for color map selection."""
        widget = QWidget()
        layout = QHBoxLayout()

        label = QLabel(self.color_map_label)
        self.colorbar = QLabel(self)
        self.colorbar.setPixmap(QPixmap.fromImage(ColorBarImage(
            self.color_map, 180, 15)))

        self.mapCombo = QComboBox(self)
        self.mapCombo.addItems(map_names)
        self.mapCombo.setCurrentIndex(map_names.index(self.color_map_name))
        self.mapCombo.currentIndexChanged.connect(self.colorbarChange)

        layout.addWidget(label)
        layout.addItem(QSpacerItem(5,5))
        layout.addWidget(self.mapCombo)
        layout.addItem(QSpacerItem(5,5))
        layout.addWidget(self.colorbar)

        widget.setLayout(layout)
        return widget

    @Slot(int)
    def colorbarChange(self, ind):
        """Handles a selection of a different colormap."""
        indx = self.mapCombo.currentIndex()
        self.color_map_name = map_names[indx]
        self.color_map = getMap(self.color_map_name)
        self.colorbar.setPixmap(QPixmap.fromImage(ColorBarImage(
            self.color_map, 180, 12)))
        self.changeSignal.emit(ColorMap(self.color_map_name, self.color_step,
            self.step_size), self.tag)

    def buildColorStepsControl(self):
        """Builds the portion of this widget for color cycling options."""
        widget = QWidget()
        layout = QHBoxLayout()

        self.stepBox = QCheckBox(self.color_step_label)
        self.stepBox.stateChanged.connect(self.colorstepsChange)

        self.stepEdit = QLineEdit("8", self)
        # Setting max to sys.maxint in the validator causes an overflow! D:
        self.stepEdit.setValidator(QIntValidator(1, 65536, self.stepEdit))
        self.stepEdit.setEnabled(False)
        self.stepEdit.editingFinished.connect(self.colorstepsChange)

        if self.color_step > 0:
            self.stepBox.setCheckState(Qt.Checked)
            self.stepEdit.setEnabled(True)

        layout.addWidget(self.stepBox)
        layout.addItem(QSpacerItem(5,5))
        layout.addWidget(QLabel("with"))
        layout.addItem(QSpacerItem(5,5))
        layout.addWidget(self.stepEdit)
        layout.addItem(QSpacerItem(5,5))
        layout.addWidget(QLabel(self.number_steps_label))

        widget.setLayout(layout)
        return widget


    def colorstepsChange(self):
        """Handles a change in the state of the color cycling for this
           colormap.
        """
        if self.stepBox.checkState() == Qt.Checked:
            self.stepEdit.setEnabled(True)
            self.color_step = int(self.stepEdit.text())
            self.changeSignal.emit(ColorMap(self.color_map_name,
                self.color_step, self.step_size), self.tag)
        else:
            self.stepEdit.setEnabled(False)
            self.color_step = 0
            self.changeSignal.emit(ColorMap(self.color_map_name,
                self.color_step, self.step_size), self.tag)
Exemple #27
0
class Form(QDialog):

    def __init__(self, state, parent=None):
        super().__init__(parent)
        Lib.prepareModalDialog(self)
        self.state = state
        self.setWindowTitle("Forget Spelling Words — {}".format(
                            QApplication.applicationName()))
        words = sorted(
            self.state.entryPanel.spellHighlighter.wordsToIgnore |
            set(self.state.model.spellWords()), key=str.casefold)
        if words:
            self.initialize(words)
        else:
            self.nowords()
        settings = QSettings()
        self.updateToolTips(bool(int(settings.value(
            Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips))))


    def nowords(self):
        label = QLabel("<p>No ignored or index dictionary words to "
                       "remove")
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.helpButton.clicked.connect(self.help)
        self.tooltips.append((self.helpButton,
                              "Help on the Forget Spelling Words dialog"))
        closeButton = QPushButton(QIcon(":/dialog-close.svg"),
                                  "&Close")
        self.tooltips.append((closeButton, """<p><b>Close</b></p>
<p>Close the dialog.</p>"""))
        buttonBox = QDialogButtonBox()
        buttonBox.addButton(closeButton, QDialogButtonBox.RejectRole)
        buttonBox.rejected.connect(self.reject)
        buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole)
        layout = QVBoxLayout()
        layout.addWidget(label)
        layout.addWidget(buttonBox)
        self.setLayout(layout)


    def initialize(self, words):
        self.removeComboBox = QComboBox()
        self.removeComboBox.addItems(words)
        self.tooltips.append((self.removeComboBox, """\
<p><b>Spelling Words combobox</b></p>
<p>This index's list of words that have been remembered as correctly
spelled or to be ignored even though they aren't in the dictionary for
the index's language.</p>"""))
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.tooltips.append((self.helpButton,
                              "Help on the Forget Spelling Words dialog"))
        self.removeButton = QPushButton(QIcon(":/spelling-remove.svg"),
                                        "&Forget")
        self.tooltips.append((self.removeButton, """\
<p><b>Forget</b></p>
<p>Permanently forget the selected word from the index's spelling words
list. Afterwards, if this word appears in any entry, it will be
highlighted as misspelled.</p>"""))
        closeButton = QPushButton(QIcon(":/dialog-close.svg"),
                                  "&Close")
        self.tooltips.append((closeButton, """<p><b>Close</b></p>
<p>Close the dialog.</p>"""))
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.addButton(closeButton, QDialogButtonBox.RejectRole)
        self.buttonBox.addButton(
            self.removeButton, QDialogButtonBox.ApplyRole)
        self.buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole)
        layout = QFormLayout()
        layout.addRow("F&orget", self.removeComboBox)
        layout.addRow(self.buttonBox)
        self.setLayout(layout)
        self.helpButton.clicked.connect(self.help)
        self.removeButton.clicked.connect(self.remove)
        self.buttonBox.rejected.connect(self.reject)


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


    def remove(self):
        word = self.removeComboBox.currentText()
        if word:
            i = self.removeComboBox.currentIndex()
            self.removeComboBox.removeItem(i)
            self.state.entryPanel.spellHighlighter.wordsToIgnore.discard(
                word)
            self.state.model.removeSpellWord(word)
            Spell.remove(word, self.state.language.value)
            self.state.entryPanel.spellHighlighter.rehighlight()
            if not self.removeComboBox.count():
                self.accept()
Exemple #28
0
class UsbResetter(QWidget):
    def __init__(self):
        super(UsbResetter, self).__init__()
        self.P = UR_thread()
        self.thr_counter = 0
        self.Looping = None
        self.Hidden = None
        self.Fhidden = None
        self.s_error = "QStatusBar{color:red;font-weight:1000;}"
        self.s_loop = "QStatusBar{color:black;font-weight:1000;}"
        self.s_norm = "QStatusBar{color:blue;font-style:italic;"
        self.s_norm += "font-weight:500;}"
        favicon = r_path("images/favicon.png")
        logo = r_path("images/logo.png")
        if name == 'nt':
            favicon = r_path("images\\favicon.png")
            logo = r_path("images\\logo.png")
        self.favicon = QIcon(favicon)
        self.plogo = logo
        self.logo = QIcon(logo)
        self.setStyle()
        mlayout = QVBoxLayout()
        self.setAbout(mlayout)
        self.setUlist(mlayout)
        self.setCboxs(mlayout)
        self.setReset(mlayout)
        self.setLoop(mlayout)
        self.setSb(mlayout)
        # functionalities
        self.set_list()
        self.rootWarn()
        # initiation
        self.activateWindow()
        self.setLayout(mlayout)
        self.show()

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

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

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

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

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

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

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

    # Functionalities

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

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

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

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

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

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

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

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

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

    @Slot(object)
    def handleStatusMessage(self, message):
        self.statusbar.setStyleSheet(self.s_loop)
        if message[:7] == '# Error':
            self.in_loop()
            self.statusbar.setStyleSheet(self.s_error)
        self.statusbar.showMessage(message)
Exemple #29
0
class RobocompDslGui(QMainWindow):
    def __init__(self, parent=None):
        super(RobocompDslGui, self).__init__(parent)
        self.setWindowTitle("Create new component")
        # self._idsl_paths = []
        self._communications = {
            "implements": [],
            "requires": [],
            "subscribesTo": [],
            "publishes": []
        }
        self._interfaces = {}
        self._cdsl_doc = CDSLDocument()
        self._command_process = QProcess()

        self._main_widget = QWidget()
        self._main_layout = QVBoxLayout()
        self.setCentralWidget(self._main_widget)

        self._name_layout = QHBoxLayout()
        self._name_line_edit = QLineEdit()
        self._name_line_edit.textEdited.connect(self.update_component_name)
        self._name_line_edit.setPlaceholderText("New component name")
        self._name_layout.addWidget(self._name_line_edit)
        self._name_layout.addStretch()

        # DIRECTORY SELECTION
        self._dir_line_edit = QLineEdit()
        # self._dir_line_edit.textEdited.connect(self.update_completer)
        self._dir_completer = QCompleter()
        self._dir_completer_model = QFileSystemModel()
        if os.path.isdir(ROBOCOMP_COMP_DIR):
            self._dir_line_edit.setText(ROBOCOMP_COMP_DIR)
            self._dir_completer_model.setRootPath(ROBOCOMP_COMP_DIR)
        self._dir_completer.setModel(self._dir_completer_model)
        self._dir_line_edit.setCompleter(self._dir_completer)

        self._dir_button = QPushButton("Select directory")
        self._dir_button.clicked.connect(self.set_output_directory)
        self._dir_layout = QHBoxLayout()
        self._dir_layout.addWidget(self._dir_line_edit)
        self._dir_layout.addWidget(self._dir_button)

        # LIST OF ROBOCOMP INTERFACES
        self._interface_list = QListWidget()
        self._interface_list.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        self._interface_list.itemSelectionChanged.connect(
            self.set_comunication)

        # LIST OF CONNECTION TyPES
        self._type_combo_box = QComboBox()
        self._type_combo_box.addItems(
            ["publishes", "implements", "subscribesTo", "requires"])
        self._type_combo_box.currentIndexChanged.connect(
            self.reselect_existing)

        # BUTTON TO ADD A NEW CONNECTION
        # self._add_connection_button = QPushButton("Add")
        # self._add_connection_button.clicked.connect(self.add_new_comunication)
        self._add_connection_layout = QHBoxLayout()
        # self._add_connection_layout.addWidget(self._add_connection_button)
        self._language_combo_box = QComboBox()
        self._language_combo_box.addItems(["Python", "Cpp", "Cpp11"])
        self._language_combo_box.currentIndexChanged.connect(
            self.update_language)
        self._add_connection_layout.addWidget(self._language_combo_box)
        self._add_connection_layout.addStretch()
        self._gui_check_box = QCheckBox()
        self._gui_check_box.stateChanged.connect(self.update_gui_selection)
        self._gui_label = QLabel("Use Qt GUI")
        self._add_connection_layout.addWidget(self._gui_label)
        self._add_connection_layout.addWidget(self._gui_check_box)

        # WIDGET CONTAINING INTERFACES AND TYPES
        self._selection_layout = QVBoxLayout()
        self._selection_layout.addWidget(self._type_combo_box)
        self._selection_layout.addWidget(self._interface_list)
        self._selection_layout.addLayout(self._add_connection_layout)
        self._selection_widget = QWidget()
        self._selection_widget.setLayout(self._selection_layout)

        # TEXT EDITOR WITH THE RESULTING CDSL CODE
        self._editor = QTextEdit(self)
        self._editor.setHtml("")

        self._document = self._editor.document()
        self._component_directory = None

        # SPLITTER WITH THE SELECTION AND THE CODE
        self._body_splitter = QSplitter(Qt.Horizontal)
        self._body_splitter.addWidget(self._selection_widget)
        self._body_splitter.addWidget(self._editor)
        self._body_splitter.setStretchFactor(0, 2)
        self._body_splitter.setStretchFactor(1, 9)

        # CREATION BUTTONS
        self._create_button = QPushButton("Create .cdsl")
        self._create_button.clicked.connect(self.write_cdsl_file)
        self._creation_layout = QHBoxLayout()
        self._creation_layout.addStretch()
        self._creation_layout.addWidget(self._create_button)

        self._console = QConsole()
        self._command_process.readyReadStandardOutput.connect(
            self._console.standard_output)
        self._command_process.readyReadStandardError.connect(
            self._console.error_output)

        # ADDING WIDGETS TO MAIN LAYOUT
        self._main_widget.setLayout(self._main_layout)
        self._main_layout.addLayout(self._name_layout)
        self._main_layout.addLayout(self._dir_layout)
        self._main_layout.addWidget(self._body_splitter)
        self._main_layout.addLayout(self._creation_layout)
        self._main_layout.addWidget(self._console)
        self.setMinimumSize(800, 500)
        self._editor.setText(self._cdsl_doc.generate_doc())

    # self.editor->show();

    # def update_completer(self, path):
    # 	print "update_completer %s"%path
    # 	info = QFileInfo(path)
    # 	if info.exists() and info.isDir():
    # 			if not path.endswith(os.path.pathsep):
    # 				new_path = os.path.join(path, os.sep)
    # 				# self._dir_line_edit.setText(new_path)
    # 			all_dirs_output = [dI for dI in os.listdir(path) if os.path.isdir(os.path.join(path, dI))]
    # 			print all_dirs_output
    # 			self._dir_completer.complete()

    def load_idsl_files(self, fullpath=None):
        if fullpath is None:
            fullpath = ROBOCOMP_INTERFACES
        idsls_dir = os.path.join(ROBOCOMP_INTERFACES, "IDSLs")
        if os.path.isdir(idsls_dir):
            for full_filename in os.listdir(idsls_dir):
                file_name, file_extension = os.path.splitext(full_filename)
                if "idsl" in file_extension.lower():
                    full_idsl_path = os.path.join(idsls_dir, full_filename)
                    # self._idsl_paths.append(os.path.join(idsls_dir,full_filename))
                    self.parse_idsl_file(full_idsl_path)
        self._interface_list.addItems(self._interfaces.keys())

    def parse_idsl_file(self, fullpath):

        with open(fullpath, 'r') as fin:
            interface_name = None
            for line in fin:
                result = re.findall(r'^\s*interface\s+(\w+)\s*\{?\s*$',
                                    line,
                                    flags=re.MULTILINE)
                if len(result) > 0:
                    interface_name = result[0]
            print("%s for idsl %s" % (interface_name, fullpath))
            if interface_name is not None:
                self._interfaces[interface_name] = fullpath

    def add_new_comunication(self):
        interface_names = self._interface_list.selectedItems()
        com_type = str(self._type_combo_box.currentText())
        for iface_name_item in interface_names:
            iface_name = str(iface_name_item.text())
            self._communications[com_type].append(iface_name)
            idsl_full_path = self._interfaces[iface_name]
            idsl_full_filename = os.path.basename(idsl_full_path)
            self._cdsl_doc.add_comunication(com_type, iface_name)
            self._cdsl_doc.add_import(idsl_full_filename)
        self.update_editor()

    def set_comunication(self):
        interface_names = self._interface_list.selectedItems()
        com_type = str(self._type_combo_box.currentText())
        self._communications[com_type] = []
        self._cdsl_doc.clear_comunication(com_type)
        for iface_name_item in interface_names:
            iface_name = str(iface_name_item.text())
            self._communications[com_type].append(iface_name)
            self._cdsl_doc.add_comunication(com_type, iface_name)
        self.update_imports()
        self.update_editor()

    def update_imports(self):
        self._cdsl_doc.clear_imports()
        for com_type in self._communications:
            for iface_name in self._communications[com_type]:
                idsl_full_path = self._interfaces[iface_name]
                idsl_full_filename = os.path.basename(idsl_full_path)
                self._cdsl_doc.add_import(idsl_full_filename)

    def update_language(self):
        language = self._language_combo_box.currentText()
        self._cdsl_doc.set_language(str(language))
        self.update_editor()

    def update_gui_selection(self):
        checked = self._gui_check_box.isChecked()
        if checked:
            self._cdsl_doc.set_qui(True)
        else:
            self._cdsl_doc.set_qui(False)
        self.update_editor()

    def update_component_name(self, name):
        self._cdsl_doc.set_name(name)
        self.update_editor()

    def update_editor(self):
        self._editor.setText(self._cdsl_doc.generate_doc())

    def set_output_directory(self):
        dir_set = False
        while not dir_set:
            dir = QFileDialog.getExistingDirectory(
                self, "Select Directory", ROBOCOMP_COMP_DIR,
                QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks)
            if self.check_dir_is_empty(str(dir)):
                self._dir_line_edit.setText(dir)
                dir_set = True

    def write_cdsl_file(self):
        component_dir = str(self._dir_line_edit.text())
        text = self._cdsl_doc.generate_doc()
        if not self._name_line_edit.text():
            component_name, ok = QInputDialog.getText(self,
                                                      'No component name set',
                                                      'Enter component name:')
            if ok:
                self.update_component_name(component_name)
                self._name_line_edit.setText(component_name)
            else:
                return False

        if not os.path.exists(component_dir):
            if QMessageBox.Yes == QMessageBox.question(
                    self, "Directory doesn't exist.",
                    "Do you want create the directory %s?" % component_dir,
                    QMessageBox.Yes | QMessageBox.No):
                os.makedirs(component_dir)
            else:
                QMessageBox.question(
                    self, "Directory not exist",
                    "Can't create a component witout a valid directory")
                return False

        file_path = os.path.join(component_dir,
                                 str(self._name_line_edit.text()) + ".cdsl")
        if os.path.exists(file_path):
            if QMessageBox.No == QMessageBox.question(
                    self, "File already exists", "Do you want to overwrite?",
                    QMessageBox.Yes | QMessageBox.No):
                return False

        with open(file_path, 'w') as the_file:
            the_file.write(text)
        self.execute_robocomp_cdsl()
        return True

    def execute_robocomp_cdsl(self):
        cdsl_file_path = os.path.join(
            str(self._dir_line_edit.text()),
            str(self._name_line_edit.text()) + ".cdsl")
        command = "python -u %s/robocompdsl.py %s %s" % (
            ROBOCOMPDSL_DIR, cdsl_file_path,
            os.path.join(str(self._dir_line_edit.text())))
        self._console.append_custom_text("%s\n" % command)
        self._command_process.start(command,
                                    QProcess.Unbuffered | QProcess.ReadWrite)

    def reselect_existing(self):
        com_type = self._type_combo_box.currentText()
        selected = self._communications[com_type]
        self._interface_list.clearSelection()
        for iface in selected:
            items = self._interface_list.findItems(iface,
                                                   Qt.MatchFlag.MatchExactly)
            if len(items) > 0:
                item = items[0]
                item.setSelected(True)

    def check_dir_is_empty(self, dir_path):
        if len(os.listdir(dir_path)) > 0:
            msgBox = QMessageBox()
            msgBox.setWindowTitle("Directory not empty")
            msgBox.setText(
                "The selected directory is not empty.\n"
                "For a new Component you usually want a new directory.\n"
                "Do you want to use this directory anyway?")
            msgBox.setStandardButtons(QMessageBox.Yes)
            msgBox.addButton(QMessageBox.No)
            msgBox.setDefaultButton(QMessageBox.No)
            if msgBox.exec_() == QMessageBox.Yes:
                return True
            else:
                return False
        else:
            return True
class LoginDialog(QDialog):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        super(LoginDialog, self).__init__()
        formLayout = QFormLayout()
        
        self.input1 = QLineEdit()
        self.input2 = QLineEdit()
        self.input2.setEchoMode(QLineEdit.EchoMode.Password)

        self.input3 = QLineEdit()
        self.input3.setEchoMode(QLineEdit.EchoMode.Password)    
        
        self.cb = QComboBox()
        self.cb.addItems(["Sef stanice", "Radnik u centrali", "Radnik na naplatnom mestu", "Admin"])
        
        palete = QPalette()
        palete.setColor(self.backgroundRole(), Qt.black)
        self.setPalette(palete)
        self.setWindowTitle("Login")
        self.resize(370, 100)
        
        label2 = QLabel("<font color='White'>Username</font>")
        label3 = QLabel("<font color='White'>Password</font>")
        label4 = QLabel("<font color='White'>Registration key</font>")
        label5 = QLabel("<font color='White'>Role</font>")
        
        formLayout.addRow(label2, self.input1)
        formLayout.addRow(label3, self.input2)
    
        
        btnOK = QPushButton("Login")
        btnOK.clicked.connect(self.loginAction)
        btnCancel = QPushButton("Cancel")
        btnCancel.clicked.connect(self.reject)
        btnRegister = QPushButton("Register")
        btnRegister.clicked.connect(self.registerAction)
        
        
        group = QDialogButtonBox()
        group.addButton(btnOK, QDialogButtonBox.AcceptRole)
        group.addButton(btnCancel, QDialogButtonBox.RejectRole)
        
        
        formLayout.addRow(group)
        formLayout.addRow(label4, self.input3)
        formLayout.addRow(label5, self.cb)
        formLayout.addWidget(btnRegister)
        
        self.result = None
        self.setLayout(formLayout)
        
    def loginAction(self):
        self.result = [self.input1.text(), self.input2.text()]
        users = []
        infile = open(".\\users.cfg", "rb")
        while True:
            try:
                user = pickle.load(infile)
                users.append(user)
            except (EOFError, UnpicklingError):
                break
        infile.close()
        for user in users:
            if user.username == self.result[0] and user.password == self.result[1]:
                self.setUser(user)
                self.accept()
                return
        message = QMessageBox()
        message.setText("Username or password is incorrect")
        message.exec_()
        
        
    def registerAction(self):
        '''
        Dodaje korisnika sa unetim imenom i lozinkom u listu postojecih korisnika.
        '''
        self.result = [self.input1.text(), self.input2.text()]
        if "" in self.result:
            message3 = QMessageBox()
            message3.setText("Incorrect input")
            message3.exec_()
        else:
            users = []
            infile = open(".\\users.cfg", "rb")
            while True:
                try:
                    user = pickle.load(infile)
                    users.append(user)
                except (EOFError, UnpicklingError):
                    break
            infile.close()
            indicator = False
            for user in users:
                if user.username == self.result[0]:
                    indicator = True;
            if indicator:
                message1 = QMessageBox()
                message1.setText("Username already exists")
                message1.exec_()
            else:
                if self.input3.text() == "admin":
                    user1 = User(self.result[0], self.result[1], self.cb.currentText())
                    users.append(user1)
                    message2 = QMessageBox()
                    message2.setText("The user was successfully created")
                    message2.exec_()
                else:
                    message3 = QMessageBox()
                    message3.setText("Registration code is incorrect")
                    message3.exec_()
            out = open(".\\users.cfg", "wb")
            for user in users:
                pickle.dump(user, out)
            out.close()
            
    def result(self):
        return self.result
    
    def setUser(self, user):
        self.user = user
        
    def getUser(self):
        return self.user
    
    
        
class MTTFilterFileDialog(QDialog):
    def __init__(self, define_path='', define_type=None):
        super(MTTFilterFileDialog, self).__init__(get_maya_window())

        self.supported_node_type = sorted([
            node_type for (node_type, nice, attr) in MTTSettings.SUPPORTED_TYPE
        ])

        self.defined_path = (define_path if os.path.isdir(define_path)
                             or define_path == SOURCEIMAGES_TAG else None)

        self.defined_type = (define_type if define_type
                             in self.supported_node_type else None)

        self.path_edit = None
        self.filter_reset_btn = None
        self.filter_line = None
        self.parent_folder_btn = None
        self.files_model = None
        self.files_list = None
        self.bookmark_list = None
        self.bookmark_list_sel_model = None
        self.types = None

        # move window to cursor position
        win_geo = MTTSettings.value('FilterFileDialog/windowGeometry',
                                    QRect(0, 0, 400, 300))
        self.setGeometry(win_geo)
        mouse_pos = QCursor.pos()
        mouse_pos.setX(mouse_pos.x() - (win_geo.width() * 0.5))
        self.move(mouse_pos)

        self.__create_ui()

        self.filter_line.setFocus()
        self.on_change_root_path(self.defined_path or SOURCEIMAGES_TAG)

    def __create_ui(self):
        """ Create main UI """
        self.setWindowTitle(CREATE_NODE_TITLE)

        # remove window decoration if path and type is set
        if self.defined_path and self.defined_type:
            self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)

        main_layout = QVBoxLayout(self)
        main_layout.setSpacing(1)
        main_layout.setContentsMargins(2, 2, 2, 2)

        # content layout
        content_layout = QVBoxLayout()
        self.files_model = QFileSystemModel()
        self.files_model.setNameFilterDisables(False)
        self.files_list = MTTFileList()
        self.files_list.setAlternatingRowColors(True)
        self.files_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.files_list.selectionValidated.connect(self.do_validate_selection)
        self.files_list.goToParentDirectory.connect(self.on_go_up_parent)
        self.files_list.doubleClicked.connect(self.on_double_click)
        self.files_list.setModel(self.files_model)

        buttons_layout = QHBoxLayout()

        content_layout.addLayout(self.__create_filter_ui())
        content_layout.addWidget(self.files_list)
        content_layout.addLayout(buttons_layout)
        self.files_list.filter_line = self.filter_line

        if not self.defined_path:
            # path line
            path_layout = QHBoxLayout()
            # bookmark button
            bookmark_btn = QPushButton('')
            bookmark_btn.setFlat(True)
            bookmark_btn.setIcon(QIcon(':/addBookmark.png'))
            bookmark_btn.setToolTip('Bookmark this Folder')
            bookmark_btn.setStatusTip('Bookmark this Folder')
            bookmark_btn.clicked.connect(self.on_add_bookmark)
            # path line edit
            self.path_edit = QLineEdit()
            self.path_edit.editingFinished.connect(self.on_enter_path)
            # parent folder button
            self.parent_folder_btn = QPushButton('')
            self.parent_folder_btn.setFlat(True)
            self.parent_folder_btn.setIcon(
                QIcon(':/SP_FileDialogToParent.png'))
            self.parent_folder_btn.setToolTip('Parent Directory')
            self.parent_folder_btn.setStatusTip('Parent Directory')
            self.parent_folder_btn.clicked.connect(self.on_go_up_parent)
            # browse button
            browse_btn = QPushButton('')
            browse_btn.setFlat(True)
            browse_btn.setIcon(QIcon(':/navButtonBrowse.png'))
            browse_btn.setToolTip('Browse Directory')
            browse_btn.setStatusTip('Browse Directory')
            browse_btn.clicked.connect(self.on_browse)
            # parent widget and layout
            path_layout.addWidget(bookmark_btn)
            path_layout.addWidget(self.path_edit)
            path_layout.addWidget(self.parent_folder_btn)
            path_layout.addWidget(browse_btn)
            main_layout.addLayout(path_layout)

            # bookmark list
            bookmark_parent_layout = QHBoxLayout()
            bookmark_frame = QFrame()
            bookmark_frame.setFixedWidth(120)
            bookmark_layout = QVBoxLayout()
            bookmark_layout.setSpacing(1)
            bookmark_layout.setContentsMargins(2, 2, 2, 2)
            bookmark_frame.setLayout(bookmark_layout)
            bookmark_frame.setFrameStyle(QFrame.Sunken)
            bookmark_frame.setFrameShape(QFrame.StyledPanel)
            self.bookmark_list = MTTBookmarkList()
            self.bookmark_list.bookmarkDeleted.connect(self.do_delete_bookmark)
            self.bookmark_list.setAlternatingRowColors(True)
            self.bookmark_list.dragEnabled()
            self.bookmark_list.setAcceptDrops(True)
            self.bookmark_list.setDropIndicatorShown(True)
            self.bookmark_list.setDragDropMode(QListView.InternalMove)
            self.bookmark_list_sel_model = self.bookmark_list.selectionModel()
            self.bookmark_list_sel_model.selectionChanged.connect(
                self.on_select_bookmark)

            bookmark_layout.addWidget(self.bookmark_list)
            bookmark_parent_layout.addWidget(bookmark_frame)
            bookmark_parent_layout.addLayout(content_layout)
            main_layout.addLayout(bookmark_parent_layout)

            self.do_populate_bookmarks()

        else:
            main_layout.addLayout(content_layout)

        if not self.defined_type:
            # type layout
            self.types = QComboBox()
            self.types.addItems(self.supported_node_type)
            self.types.currentIndexChanged.connect(self.on_node_type_changed)
            if cmds.optionVar(exists='MTT_lastNodeType'):
                last = cmds.optionVar(query='MTT_lastNodeType')
                if last in self.supported_node_type:
                    self.types.setCurrentIndex(
                        self.supported_node_type.index(last))
            buttons_layout.addWidget(self.types)

        if not self.defined_path or not self.defined_type:
            create_btn = QPushButton('C&reate')
            create_btn.clicked.connect(self.accept)
            cancel_btn = QPushButton('&Cancel')
            cancel_btn.clicked.connect(self.reject)

            buttons_layout.addStretch()
            buttons_layout.addWidget(create_btn)
            buttons_layout.addWidget(cancel_btn)

    def __create_filter_ui(self):
        """ Create filter widgets """
        filter_layout = QHBoxLayout()
        filter_layout.setSpacing(1)
        filter_layout.setContentsMargins(0, 0, 0, 0)

        self.filter_reset_btn = QPushButton()
        icon = QIcon(':/filtersOff.png')
        self.filter_reset_btn.setIcon(icon)
        self.filter_reset_btn.setIconSize(QSize(22, 22))
        self.filter_reset_btn.setFixedSize(24, 24)
        self.filter_reset_btn.setToolTip('Reset filter')
        self.filter_reset_btn.setFlat(True)
        self.filter_reset_btn.clicked.connect(
            partial(self.on_filter_set_text, ''))

        self.filter_line = QLineEdit()
        self.filter_line.setPlaceholderText('Enter filter string here')
        self.filter_line.textChanged.connect(self.on_filter_change_text)

        completer = QCompleter(self)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        completer.setModel(QStringListModel([], self))
        self.filter_line.setCompleter(completer)

        filter_layout.addWidget(self.filter_reset_btn)
        filter_layout.addWidget(self.filter_line)

        return filter_layout

    def on_filter_set_text(self, text=''):
        """ Set text in filter field """
        self.filter_line.setText(text)

    def on_filter_change_text(self, text):
        """ Apply filter string """
        if len(text):
            icon = QIcon(':/filtersOn.png')
            self.filter_reset_btn.setIcon(icon)
        else:
            icon = QIcon(':/filtersOff.png')
            self.filter_reset_btn.setIcon(icon)

        self.files_model.setNameFilters([
            '*%s*' % item.strip() for item in text.split(',') if item.strip()
        ])

    def on_node_type_changed(self, index):
        cmds.optionVar(
            sv=['MTT_lastNodeType', self.supported_node_type[index]])

    def on_double_click(self, index):
        current_item = self.files_model.filePath(index)
        if os.path.isdir(current_item):
            self.on_change_root_path(current_item)
        elif os.path.isfile(current_item):
            self.accept()

    def on_change_root_path(self, current_path):
        if current_path == SOURCEIMAGES_TAG:
            current_path = os.path.join(
                cmds.workspace(query=True, rootDirectory=True),
                cmds.workspace(fileRuleEntry='sourceImages'))

        self.files_model.setRootPath(current_path)
        self.files_list.setRootIndex(self.files_model.index(current_path))
        if self.path_edit:
            self.path_edit.setText(current_path)

        if self.parent_folder_btn:
            current_dir = QDir(current_path)
            self.parent_folder_btn.setEnabled(current_dir.cdUp())

    def on_go_up_parent(self):
        current_path = QDir(self.files_model.rootPath())
        current_path.cdUp()
        self.on_change_root_path(current_path.absolutePath())

    def on_enter_path(self):
        new_path = self.path_edit.text()
        if os.path.isdir(new_path):
            self.on_change_root_path(new_path)
        else:
            self.path_edit.setText(self.files_model.rootPath())

    def on_browse(self):
        current_path = self.files_model.rootPath()
        file_dialog = QFileDialog(self, 'Select a Folder', current_path)
        file_dialog.setFileMode(QFileDialog.Directory)
        file_dialog.setOption(QFileDialog.ShowDirsOnly)

        if file_dialog.exec_():
            self.on_change_root_path(file_dialog.selectedFiles()[0])

    def on_select_bookmark(self, selected, deselected):
        current_item = selected.indexes()
        if current_item:
            self.on_change_root_path(
                self.bookmark_list.selectedItems()[0].root_path)

    def on_add_bookmark(self):
        current_path = self.files_model.rootPath()
        self.on_add_bookmark_item(
            '%s|%s' % (os.path.basename(current_path), current_path))

    def on_add_bookmark_item(self, item):
        if item == '':
            return

        current_item = MTTBookmarkItem()
        current_item.add_raw_data(item)
        current_item.setSizeHint(QSize(40, 25))
        current_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable
                              | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)

        self.bookmark_list.addItem(current_item)

    def do_delete_bookmark(self):
        current_item = self.bookmark_list.selectedItems()
        if current_item:
            item_row = self.bookmark_list.row(current_item[0])
            self.bookmark_list.takeItem(item_row)
            del current_item[0]

    def do_save_bookmark(self):
        if not self.bookmark_list:
            return

        row_count = self.bookmark_list.count()
        ordered_list = list()

        for i in range(row_count):
            item = self.bookmark_list.item(i)
            name = item.text().replace(',', '_').replace('|', '_')
            path = item.root_path
            if name != 'sourceimages':
                ordered_list.append('%s|%s' % (name, path))

        MTTSettings.set_value('FilterFileDialog/bookmarks',
                              ','.join(ordered_list))

    def do_populate_bookmarks(self):
        bookmarks = ['sourceimages|%s' % SOURCEIMAGES_TAG]
        bookmarks.extend(
            MTTSettings.value('FilterFileDialog/bookmarks').split(','))

        for bm in bookmarks:
            self.on_add_bookmark_item(bm)

    def do_validate_selection(self):
        selection = self.files_list.selectedIndexes()
        if len(selection) == 1:
            current_path = self.files_model.filePath(selection[0])
            if os.path.isdir(current_path):
                self.on_change_root_path(current_path)
                return
        self.accept()

    def get_selected_files(self):
        selected_items = list()
        for item_index in self.files_list.selectedIndexes():
            current_path = self.files_model.filePath(item_index)
            if os.path.isfile(current_path):
                selected_items.append(current_path)
        return selected_items

    def get_node_type(self):
        return self.types.currentText() if self.types else self.defined_type

    def closeEvent(self, event):
        MTTSettings.set_value('FilterFileDialog/windowGeometry',
                              self.geometry())
        self.do_save_bookmark()

        self.deleteLater()
        event.accept()
Exemple #32
0
class Airport_project_UI(QWidget):

    airports = [
        'KRK',
        'LA',
        'LIS'
    ]

    elitism_possibly_values = ['true', 'false']

    max_flights_list = ['1', '2', '3', '4', '5']

    def __init__(self):
        QWidget.__init__(self)
        self.params = {}

       # self.setMinimumSize(600, 250)
        #self.setWindowTitle("Medody Optymalizacji - Projekt")
       # self.setIcon()

        self.start_airport_label = QLabel("Start airport:", self)
        self.start_airport_label.move(5, 10)
        self.start_airport = QLineEdit(self)
        self.start_airport.setText('1')
        #self.start_airport.addItems(self.airports)
        self.start_airport.setMinimumHeight(20)
        self.start_airport.setMaximumHeight(20)
        self.start_airport.setMinimumWidth(60)
        self.start_airport.setMaximumWidth(60)
        self.start_airport.move(150, 5)

#TODO function to convert names of airport to indexes

        self.destination_airport_label = QLabel("Destination airport:", self)
        self.destination_airport_label.move(5, 40)
        self.destination_airport = QLineEdit(self)
        self.destination_airport.setText('2')
       # self.destination_airport.addItems(self.airports)
        self.destination_airport.setMinimumHeight(20)
        self.destination_airport.setMaximumHeight(20)
        self.destination_airport.setMaximumWidth(60)
        self.destination_airport.setMinimumWidth(60)
        self.destination_airport.move(150, 35)

        self.max_flights_label = QLabel("max number of flights:", self)
        self.max_flights_label.move(5, 70)
        self.max_flights = QLineEdit(self)
        self.max_flights.setText("3")
        #self.max_flights.addItems(self.max_flights_list)
        self.max_flights.setMaximumHeight(20)
        self.max_flights.setMinimumHeight(20)
        self.max_flights.setMaximumWidth(60)
        self.max_flights.setMinimumWidth(60)
        #self.max_flights.setMinimumWidth(60)
        self.max_flights.move(150, 65)

        self.cost_weight_label = QLabel("max cost weights:", self)
        self.cost_weight_label.move(5, 100)
        self.cost_weight = QLineEdit(self)
        self.cost_weight.setText("4")
        self.cost_weight.setMinimumWidth(60)
        self.cost_weight.setMaximumWidth(60)
        self.cost_weight.setMinimumHeight(20)
        self.cost_weight.setMaximumHeight(20)
        self.cost_weight.move(150, 95)


        self.time_weight_label = QLabel("time weight:", self)
        self.time_weight_label.move(5, 130)
        self.time_weight = QLineEdit(self)
        self.time_weight.setText("5")
        self.time_weight.setMinimumWidth(60)
        self.time_weight.setMaximumWidth(60)
        self.time_weight.setMinimumHeight(20)
        self.time_weight.setMaximumHeight(20)
        self.time_weight.move(150, 125)

        self.pop_size_label = QLabel("pop size:", self)
        self.pop_size_label.move(5, 160)  # +30

        self.pop_size = QLineEdit(self)
        self.pop_size.setText("6")
        self.pop_size.setMinimumWidth(60)
        self.pop_size.setMaximumWidth(60)
        self.pop_size.setMinimumHeight(20)
        self.pop_size.setMaximumHeight(20)
        self.pop_size.move(150, 155) # +30

        self.generation_label = QLabel("generations:", self)
        self.generation_label.move(5, 190)  # +30

        self.generation = QLineEdit(self)
        self.generation.setText("7")
        self.generation.setMinimumWidth(60)
        self.generation.setMaximumWidth(60)
        self.generation.setMinimumHeight(20)
        self.generation.setMaximumHeight(20)
        self.generation.move(150, 185) # +30

        self.mutation_rate_label = QLabel("mutation rate:", self)
        self.mutation_rate_label.move(5, 210)  # +30

        self.mutation_rate = QLineEdit(self)
        self.mutation_rate.setText("8")
        self.mutation_rate.setMinimumWidth(60)
        self.mutation_rate.setMaximumWidth(60)
        self.mutation_rate.setMinimumHeight(20)
        self.mutation_rate.setMaximumHeight(20)
        self.mutation_rate.move(150, 215) # +30


        self.tournament_size_label = QLabel("tournament size:", self)
        self.tournament_size_label.move(5, 240)  # +30

        self.tournament_size = QLineEdit(self)
        self.tournament_size.setText("9")
        self.tournament_size.setMinimumWidth(60)
        self.tournament_size.setMaximumWidth(60)
        self.tournament_size.setMinimumHeight(20)
        self.tournament_size.setMaximumHeight(20)
        self.tournament_size.move(150, 245) # +30

        self.elitism_label = QLabel("elitism:", self)
        self.elitism_label.move(5, 270)  # +30

        self.elitism = QComboBox(self)
        self.elitism.addItems(self.elitism_possibly_values)
        self.elitism.setMinimumWidth(60)
        self.elitism.setMaximumWidth(60)
        self.elitism.setMinimumHeight(20)
        self.elitism.setMaximumHeight(20)
        self.elitism.move(150, 275) # +30

        self.destination_min_label = QLabel("dest min:", self)
        self.destination_min_label.move(5, 300)  # +30

        self.dest_min = QLineEdit(self)
        self.dest_min.setText("4")
        self.dest_min.setMinimumWidth(60)
        self.dest_min.setMaximumWidth(60)
        self.dest_min.setMinimumHeight(20)
        self.dest_min.setMaximumHeight(20)
        self.dest_min.move(150, 305) # +30

        self.destination_max_label = QLabel("dest max:", self)
        self.destination_max_label.move(5, 330)  # +30

        self.dest_max = QLineEdit(self)
        self.dest_max.setText("10")
        self.dest_max.setMinimumWidth(60)
        self.dest_max.setMaximumWidth(60)
        self.dest_max.setMinimumHeight(20)
        self.dest_max.setMaximumHeight(20)
        self.dest_max.move(150, 335) # +30

        self.generate_graph_button = QPushButton("Generate graph!", self)
        self.generate_graph_button.setMinimumWidth(170)
        self.generate_graph_button.move(25, 365)

        self.start_evolution_button = QPushButton("Start evolution!", self)
        self.start_evolution_button.setMinimumWidth(170)
        self.start_evolution_button.move(25, 395)

        self.start_evolution_button.clicked.connect(self.start_evolution)
        self.generate_graph_button.clicked.connect(self.generate_graph)
        #self.get_list_of_possibly_airports() #TODO to have full list of airports in QComboBox

    def generate_graph(self):
        self.params = {
            'graph'           : None,
            'start_idx'       : int(self.start_airport.text()),
            'end_idx'         : int(self.destination_airport.text()),
            'max_flights'     : int(self.max_flights.text()),
            'cost_weight'     : int(self.cost_weight.text()),
            'time_weight'     : int(self.time_weight.text()),
            'pop_size'        : int(self.pop_size.text()),
            'generations'     : int(self.generation.text()),
            'mutation_rate'   : float(self.mutation_rate.text()),
            'tournament_size' : int(self.tournament_size.text()),
            'elitism'         : bool(self.elitism.currentText()),
            'dest_min'        : int(self.dest_min.text()),
            'dest_max'        : int(self.dest_max.text()),
            'max_flights'     : 4,
        }
        data = DataGenerator()
        DataGenerator.DESTINATIONS_MIN = self.params['dest_min']
        DataGenerator.DESTINATIONS_MAX = self.params['dest_max']

        # if input_graph_file is not None:
        #     data.load_saved_graph(input_graph_file)
        #
        # else:
        #TODO ilosc lotnisk
        data.load_new_data(10)
        data.create_graph()

        # if graph_save_file is not None:
        #     data.save_graph(graph_save_file)

        testsuite_airports = data.get_airports()
        testsuite_graph = data.get_graph()

        self.graph = GraphManager(self.params['max_flights'])
        self.graph.set_graph(testsuite_graph, testsuite_airports)

        airports_parser = Testsuite_airports_parser(testsuite_airports)


    def start_evolution(self):
        import pprint
        self.params = {
        'graph'           : self.graph,
        'start_idx'       : int(self.start_airport.text()),
        'end_idx'         : int(self.destination_airport.text()),
        'max_flights'     : int(self.max_flights.text()),
        'cost_weight'     : int(self.cost_weight.text()),
        'time_weight'     : int(self.time_weight.text()),
        'pop_size'        : int(self.pop_size.text()),
        'generations'     : int(self.generation.text()),
        'mutation_rate'   : float(self.mutation_rate.text()),
        'tournament_size' : int(self.tournament_size.text()),
        'elitism'         : bool(self.elitism.currentText()),
        'dest_min'        : int(self.dest_min.text()),
        'dest_max'        : int(self.dest_max.text()),
        }
        # pprint.pprint(params)
        self.output_of_algorithm = sys.__stdout__
        GA.run_with_params(self.params)
        self.newwindow()

    def newwindow(self):
        import pprint
        print("##############")
        pprint.pprint(self.output_of_algorithm)
        print("##############")
        self.wid = QWidget()
        self.wid.resize(250, 150)
        self.wid.setWindowTitle('NewWindow')
        self.result = QTextEdit(self.wid)
        self.result.setText(str(self.output_of_algorithm))
        #self.start_airport.addItems(self.airports)
        self.result.setMinimumHeight(200)
        self.result.setMaximumHeight(200)
        self.result.setMinimumWidth(600)
        self.start_airport.setMaximumWidth(600)
        # self.start_airport.move(150, 5)
        self.output_of_algorithm = None
        self.wid.show()
class EditEmployeeWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.__parent = parent

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

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

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

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

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

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

        self.setupUI()

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

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

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

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

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

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

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

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

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

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

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

    def setupUI(self):

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

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

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

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

        layout.addLayout(bttnLayout)
        self.setLayout(layout)
class Form(QDialog):
    def __init__(self,parent=None):
        super(Form,self).__init__(parent)

        date = self.get_data()
        rates = sorted(self.rates.keys())

        dateLabel = QLabel(date)

        self.fromComboBox = QComboBox()
        self.toComboBox = QComboBox()

        self.fromComboBox.addItems(rates)
        self.toComboBox.addItems(rates)

        self.fromSpinBox = QDoubleSpinBox()
        self.fromSpinBox.setRange(0.01,1000)
        self.fromSpinBox.setValue(1.00)

        self.toLabel = QLabel("1.00")

        layout = QGridLayout();
        layout.addWidget(dateLabel,5,0)
        layout.addWidget(self.fromComboBox, 1,0)
        layout.addWidget(self.toComboBox,2,0)
        layout.addWidget(self.fromSpinBox,1,1)
        layout.addWidget(self.toLabel,2,1)

        self.setLayout(layout)

        #Connect Signal
        self.fromComboBox.currentIndexChanged.connect(self.update_ui)
        self.toComboBox.currentIndexChanged.connect(self.update_ui)
        self.fromSpinBox.valueChanged.connect(self.update_ui)

    def get_data(self):
        self.rates = {}

        try:
            date = "Unknown"
            # Thanks Mr Mark Summerfield
            fh = urllib.urlopen("http://www.bankofcanada.ca/valet/observations/group/FX_RATES_DAILY/csv?start_date=2017-01-03")

            for line in fh:
                line = line.rstrip()
                if not line or line.startswith(("#", "Closing")):
                    continue

                fields = line.split(",")
                if line.startswith("Date "):
                    date = fields[-1]

                else:
                    try:
                        value = float(fields[-1])
                        self.rates[fields[0]] = value
                    except ValueError:
                        pass

            return "Exchange rates date: " + date
        except Exception, e:
            return "Failued to download:\n%s" % e
Exemple #35
0
class CalculateSalaryWidget(QWidget):
    """A PySide widget which provides GUI for selecting employee and calculating salary for a month & year

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

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

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

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

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

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

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

        self.__desig = None
        self.__emp = None

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

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

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

        self.id = QComboBox()

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

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

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

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

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

        self.setupUI()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        layout.addLayout(table)

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

        layout.addLayout(bttnLayout)

        paneLayout.addLayout(layout)
        self.setLayout(paneLayout)
Exemple #36
0
class App(QWidget):
    def __init__(self):
        super(App, self).__init__()
        self.title = 'Hydraulic labcar'
        self.left = 100
        self.top = 100
        self.width = 600
        self.height = 400
        self.initUI()

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

        self.createLayout()
        windowLayout = QVBoxLayout()
        windowLayout.addWidget(self.GridGroupBox)
        self.setLayout(windowLayout)

        self.show()

    def createLayout(self):
        self.GridGroupBox = QGroupBox("ESD tranisent control")
        l1 = QLabel("HOST PORT")

        h1 = QHBoxLayout()

        a3host = QLineEdit('127.0.0.1')
        a3col = QLabel(':')
        a3port = QLineEdit('22222')
        h1.addWidget(a3host)
        h1.addWidget(a3col)
        h1.addWidget(a3port)

        l3 = QLabel("COM port")

        hbb = QHBoxLayout()
        comport = QComboBox()
        #comport.addItem('COM1')
        comport.addItems(['COM1', 'COM2', 'COM3', 'COM4', 'COM5'])
        l4 = QLabel("Baue rate")
        comBaud = QComboBox()
        comBaud.addItems(['9600'])
        hbb.addWidget(comport)
        hbb.addWidget(l4)
        hbb.addWidget(comBaud)

        l4 = QLabel("Profile CSV")
        self.prof = QLineEdit()
        hb = QHBoxLayout()
        btnSel = QPushButton("Select")
        btnSel.clicked.connect(self.openFileNameDialog)
        hb.addWidget(self.prof)
        hb.addWidget(btnSel)

        l5 = QLabel("INCA Label")
        self.label = QLineEdit("PhyMod_trq2qBas_MAP")
        self.labelType = QComboBox()
        l6 = QLabel("Type")
        self.labelType.addItems([r'MAP/CURVE', 'Single'])
        h2 = QHBoxLayout()
        h2.addWidget(self.label)
        h2.addWidget(l6)
        h2.addWidget(self.labelType)

        fbox = QFormLayout()
        fbox.addRow(l1, h1)
        fbox.addRow(l3, hbb)
        fbox.addRow(l4, hb)
        fbox.addRow(l5, h2)
        hbox = QHBoxLayout()

        init = QPushButton("Init")
        HeatBeat = QPushButton("Heart beat")
        run = QPushButton("Run")
        stop = QPushButton("Stop")
        hbox.addWidget(init)
        hbox.addWidget(stop)
        hbox.addWidget(run)
        hbox.addWidget(HeatBeat)
        fbox.addRow(QLabel("control"), hbox)

        self.GridGroupBox.setLayout(fbox)

    def doParser(self):
        s = self.txt.text()
        if (s == ""):
            QMessageBox.warning(self, 'Warning',
                                'Please select the source file.')
        elif (self.ratio.text() == ""):
            QMessageBox.warning(self, 'Warning',
                                'Please enter the gear ratio.')
        else:
            self.parseMDF(s)

    def openFileNameDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "CSV Files (*.csv)",
            options=options)
        if fileName:
            self.prof.setText(fileName)

    def parseMDF(self, filename):
        if (os.path.exists(filename)):
            mdf = mdfreader.mdf(filename,
                                channelList=['Epm_nEng', 'InjCtl_qSetUnBal'])
            mdf.convertToPandas(0.1)
            df = mdf['master_group']
            try:
                r = float(Fraction(self.ratio.text()))
                df['Epm_nEng'] = df['Epm_nEng'].apply(lambda x: round(x / r))
                df.columns = ['Speed', 'q']
                df.to_csv(filename + ".csv", index=False)
                QMessageBox.information(self, 'Finished.', 'OK.')
            except PermissionError:
                QMessageBox.warning(
                    self, 'Warning',
                    'The file is opened, please close it and try again.')
        else:
            QMessageBox.warning(self, 'Warning',
                                'Cannot file the file you specified!')

    def openFileNamesDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        files, _ = QFileDialog.getOpenFileNames(
            self,
            "QFileDialog.getOpenFileNames()",
            "",
            "All Files (*);;Python Files (*.py)",
            options=options)
        if files:
            print(files)

    def saveFileDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getSaveFileName(
            self,
            "QFileDialog.getSaveFileName()",
            "",
            "All Files (*);;Text Files (*.txt)",
            options=options)
        if fileName:
            parseMDF(self.txt.text)

    def spdinit(self):
        mSerial = SpdCtl.SpdCtl()
Exemple #37
0
class MainWindow(QMainWindow):  # Sets up the main window
    def resize_window(self):  # Function for resizing the window
        self.resize(self.minimumSizeHint())

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        # Set window Icon
        self.setWindowTitle(__appname__)
        iconImage = QImage(iconByteArray)
        iconPixmap = QPixmap(iconImage)
        self.setWindowIcon(QIcon(iconPixmap))

        # Set up private key format widgets
        privateKeyFormatLayout = QHBoxLayout()
        privateKeyFormatLabel = QLabel('Select Key Format: ')
        self.privateKeyTypeCombobox = QComboBox()
        self.privateKeyTypeCombobox.addItems(privateKeyFormats)
        self.privateKeyLengthLabel = QLabel('0')
        privateKeyFormatLayout.addWidget(privateKeyFormatLabel)
        privateKeyFormatLayout.addWidget(self.privateKeyTypeCombobox)
        privateKeyFormatLayout.addWidget(self.privateKeyLengthLabel)

        # Set up private key text widgets
        privateKeyLayout = QVBoxLayout()
        privateKeyButtonsLayout = QHBoxLayout()
        generatePrivateKeyButton = QPushButton('Generate Key')
        generatePrivateKeyButton.clicked.connect(self.get_private_key)
        self.copyPrivateKeyButton = QPushButton('Copy Key')
        self.copyPrivateKeyButton.setDisabled(True)
        self.copyPrivateKeyButton.clicked.connect(self.copy_private_key)
        privateKeyButtonsLayout.addWidget(generatePrivateKeyButton)
        privateKeyButtonsLayout.addWidget(self.copyPrivateKeyButton)
        self.privateKeyEdit = GrowingTextEdit()
        self.privateKeyEdit.setFont(QFont('Courier'))
        self.privateKeyEdit.textChanged.connect(
            self.private_key_or_code_changed)
        privateKeyLayout.addLayout(privateKeyButtonsLayout)
        privateKeyLayout.addWidget(self.privateKeyEdit)

        # Set up cypher code widgets
        codeLayout = QHBoxLayout()
        codeLabel = QLabel('Select Cypher Code: ')
        self.codeSelect = QSpinBox()
        self.codeSelect.setValue(10)
        self.codeSelect.setMinimum(2)
        self.codeSelect.setDisabled(True)
        self.codeSelect.valueChanged.connect(self.private_key_or_code_changed)
        codeLayout.addWidget(codeLabel)
        codeLayout.addWidget(self.codeSelect)

        # Set up cypher text widgets
        cypherLayout = QVBoxLayout()
        cypherButtonsLayout = QHBoxLayout()
        cardButtonsLayout = QHBoxLayout()
        self.generateCypherButton = QPushButton('Generate Cypher')
        self.generateCypherButton.clicked.connect(self.get_cypher)
        self.generateCypherButton.setDisabled(True)
        self.copyCypherButton = QPushButton('Copy Cypher')
        self.copyCypherButton.setDisabled(True)
        self.copyCypherButton.clicked.connect(self.copy_cypher)
        cypherButtonsLayout.addWidget(self.generateCypherButton)
        cypherButtonsLayout.addWidget(self.copyCypherButton)
        self.cypherEdit = GrowingTextEdit()
        self.cypherEdit.setFont(QFont('Courier'))
        self.cypherEdit.setReadOnly(True)
        self.cypherEdit.setVisible(False)
        self.cypherEdit.textChanged.connect(self.resize_window)
        self.cypherPreviewLabel = QLabel('-CYPHER PREVIEW-')
        self.cypherPreviewLabel.setAlignment(Qt.AlignCenter)
        self.cypherPreviewLabel.setVisible(False)
        self.cypherPreview = GrowingTextEdit()
        self.cypherPreview.setFont(QFont('Courier'))
        self.cypherPreview.setAlignment(Qt.AlignHCenter)
        self.cypherPreview.setWordWrapMode(QTextOption.NoWrap)
        self.cypherPreview.setReadOnly(True)
        self.cypherPreview.setVisible(False)
        self.cypherCardsPrintButton = QPushButton('Print Cypher Cards')
        self.cypherCardsPrintButton.setVisible(False)
        self.cypherCardsPrintButton.clicked.connect(partial(self.cards, True))
        self.cypherCardsCopyButton = QPushButton('Copy Cypher Cards')
        self.cypherCardsCopyButton.setVisible(False)
        self.cypherCardsCopyButton.clicked.connect(partial(self.cards, False))
        cardButtonsLayout.addWidget(self.cypherCardsPrintButton)
        cardButtonsLayout.addWidget(self.cypherCardsCopyButton)
        cypherLayout.addLayout(cypherButtonsLayout)
        cypherLayout.addWidget(self.cypherEdit)
        cypherLayout.addWidget(self.cypherPreviewLabel)
        cypherLayout.addWidget(self.cypherPreview)
        cypherLayout.addLayout(cardButtonsLayout)

        # Set up donation widgets
        donationsLayout = QVBoxLayout()
        separater = QFrame()
        separater.setFrameShape(QFrame.HLine)
        self.donationButton = QPushButton('Donate')
        self.donationButton.setVisible(False)
        self.donationButton.clicked.connect(self.donate)
        self.copyEthAddressButton = QPushButton('ETH: Copy Address')
        self.copyEthAddressButton.clicked.connect(
            self.copy_eth_donation_address)
        self.copyEthAddressButton.setVisible(False)
        self.copyBtcAddressButton = QPushButton('BTC: Copy Address')
        self.copyBtcAddressButton.clicked.connect(
            self.copy_btc_donation_address)
        self.copyBtcAddressButton.setVisible(False)
        donationsLayout.addWidget(separater)
        donationsLayout.addWidget(self.donationButton)
        donationsLayout.addWidget(self.copyEthAddressButton)
        donationsLayout.addWidget(self.copyBtcAddressButton)

        # Add all widgets and sub-layouts to the master layout
        self.master_layout = QVBoxLayout()
        self.master_layout.addLayout(privateKeyFormatLayout)
        self.master_layout.addLayout(privateKeyLayout)
        self.master_layout.addLayout(codeLayout)
        self.master_layout.addLayout(cypherLayout)
        self.master_layout.addLayout(donationsLayout)
        self.master_widget = QWidget()
        self.master_widget.setLayout(self.master_layout)
        self.setCentralWidget(self.master_widget)

        # Start and connect the window resizing thread
        self.worker = Worker()
        self.worker.updateWindowSize.connect(self.resize_window)

    def copy_private_key(
            self):  # Copies the private key text to the system clipboard
        clip.setText(self.privateKeyEdit.toPlainText())
        self.copyPrivateKeyButton.setText('Key Copied')
        app.processEvents()
        sleep(2)
        self.copyPrivateKeyButton.setText('Copy Key')

    def copy_cypher(self):  # Copies the cypher text to the system clipboard
        clip.setText(self.cypherEdit.toPlainText())
        self.copyCypherButton.setText('Cypher Copied')
        app.processEvents()
        sleep(2)
        self.copyCypherButton.setText('Copy Cypher')

    def copy_eth_donation_address(
            self):  # Copies the ETH donation address to the system clipboard
        clip.setText(ethDonationAddress)
        self.copyEthAddressButton.setText('ETH: Address Copied\nThanks!')
        app.processEvents()
        sleep(2)
        self.copyEthAddressButton.setText('ETH: Copy Address')

    def copy_btc_donation_address(
            self):  # Copies the BTC donation address to the system clipboard
        clip.setText(btcDonationAddress)
        self.copyBtcAddressButton.setText('BTC: Address Copied\nThanks!')
        app.processEvents()
        sleep(2)
        self.copyBtcAddressButton.setText('BTC: Copy Address')

    def get_private_key(
        self
    ):  # Generates a key of the desired format using two instances of the SystemRandom function
        privateKey = generate_private_key.start(
            self.privateKeyTypeCombobox.currentText())
        self.privateKeyEdit.setText(privateKey)
        self.private_key_or_code_changed()
        self.copyPrivateKeyButton.setDisabled(False)

    def private_key_or_code_changed(
        self
    ):  # Changes visibility and ability of some widgets based on user input
        self.privateKeyLengthLabel.setText(
            str(len(self.privateKeyEdit.toPlainText())))
        self.copyCypherButton.setDisabled(True)
        self.cypherEdit.setText('')
        self.cypherPreview.setText('')
        self.cypherEdit.setVisible(False)
        self.cypherPreviewLabel.setVisible(False)
        self.cypherPreview.setVisible(False)
        if len(self.privateKeyEdit.toPlainText()) <= 2:
            self.copyPrivateKeyButton.setDisabled(True)
            self.generateCypherButton.setDisabled(True)
            self.codeSelect.setDisabled(True)
        else:
            self.codeSelect.setMaximum(
                len(self.privateKeyEdit.toPlainText()) - 1)
            self.copyPrivateKeyButton.setDisabled(False)
            self.generateCypherButton.setDisabled(False)
            self.codeSelect.setDisabled(False)
        self.cypherCardsPrintButton.setDisabled(True)
        self.cypherCardsPrintButton.setVisible(False)
        self.cypherCardsCopyButton.setDisabled(True)
        self.cypherCardsCopyButton.setVisible(False)
        self.worker.start()

    def get_cypher(
        self
    ):  # Converts the raw key into a cypher based on the codeSelect value
        if not 1 >= len(self.privateKeyEdit.toPlainText()) >= int(
                self.privateKeyLengthLabel.text()):
            self.generateCypherButton.setDisabled(False)
            cypherRows, cypherSeed = create_cypher.start(
                self.privateKeyEdit.toPlainText(), self.codeSelect.value())
            self.copyCypherButton.setDisabled(False)
            self.cypherEdit.setVisible(True)
            self.cypherEdit.setText(cypherSeed)
            self.cypherPreviewLabel.setVisible(True)
            self.cypherPreview.setVisible(True)
            previewText = ''
            for i in cypherRows:
                previewText += i + '\n'
            self.cypherPreview.setText(previewText)
            self.worker.start()
            self.cypherCardsPrintButton.setDisabled(False)
            self.cypherCardsPrintButton.setVisible(True)
            self.cypherCardsCopyButton.setDisabled(False)
            self.cypherCardsCopyButton.setVisible(True)
            self.donationButton.setVisible(True)
        else:
            self.generateCypherButton.setDisabled(True)

    def cards(self, print):  # Creates and prints the output.txt file
        cardList = split_cypher_into_pairs.start(self.cypherEdit.toPlainText())
        printString = format_cards.start(cardList)
        if print:
            self.cypherCardsPrintButton.setText('Printing')
            app.processEvents()
            cards_output.start(printString)
            self.cypherCardsPrintButton.setText('Print Cypher Cards')
        else:
            clip.setText(printString)
            self.cypherCardsCopyButton.setText('Cards Copied')
            app.processEvents()
            sleep(2)
            self.cypherCardsCopyButton.setText('Copy Cypher Cards')

    def donate(self):  # Adjusts the visibility of the donation buttons
        if self.donationButton.text() == 'Donate':
            self.copyEthAddressButton.setVisible(True)
            self.copyBtcAddressButton.setVisible(True)
            self.donationButton.setText('Hide')
        elif self.donationButton.text() == 'Hide':
            self.copyEthAddressButton.setVisible(False)
            self.copyBtcAddressButton.setVisible(False)
            self.donationButton.setText('Donate')
        self.worker.start()

    def cleanup(self):  # Clears the clipboard of any copied text
        clip.setText('')
Exemple #38
0
class NotificationTab():
    """ui class for new notification tab"""
    global logger

    def __init__(self):
        #####
        logger.info('Inside PurchaseSchedule')
        self.notificationTab_tab_4 = QWidget()
        self.notificationTab_tab_4.setObjectName("notificationTab_tab_4")
        self.gridLayout_19 = QGridLayout(self.notificationTab_tab_4)
        self.gridLayout_19.setObjectName("gridLayout_19")
        ##
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.title_label = QLabel(self.notificationTab_tab_4)
        self.title_label.setObjectName("title_label")
        self.horizontalLayout.addWidget(self.title_label)
        self.gridLayout_19.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        ##
        self.horizontalLayout_6 = QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.id_label = QLabel(self.notificationTab_tab_4)
        self.id_label.setObjectName("id_label")
        self.horizontalLayout_6.addWidget(self.id_label)
        self.id_line = QLineEdit(self.notificationTab_tab_4)
        self.id_line.setObjectName("id_line")
        self.horizontalLayout_6.addWidget(self.id_line)
        self.notification_schedule_fromdate_label = QLabel(
            self.notificationTab_tab_4)
        self.notification_schedule_fromdate_label.setObjectName(
            "notification_schedule_fromdate_label")
        self.horizontalLayout_6.addWidget(
            self.notification_schedule_fromdate_label)
        self.notification_schedule_fromdate_dateedit = QDateEdit(
            self.notificationTab_tab_4)
        self.notification_schedule_fromdate_dateedit.setMaximumDate(
            QDate.currentDate())
        self.notification_schedule_fromdate_dateedit.setDate(
            QDate.currentDate())
        self.notification_schedule_fromdate_dateedit.setCalendarPopup(True)
        self.notification_schedule_fromdate_dateedit.setObjectName(
            "notification_schedule_fromdate_dateedit")
        self.horizontalLayout_6.addWidget(
            self.notification_schedule_fromdate_dateedit)
        self.notification_schedule_todate_label = QLabel(
            self.notificationTab_tab_4)
        self.notification_schedule_todate_label.setObjectName(
            "notification_schedule_todate_label")
        self.horizontalLayout_6.addWidget(
            self.notification_schedule_todate_label)
        self.notification_schedule_todate_dateedit = QDateEdit(
            self.notificationTab_tab_4)
        self.notification_schedule_todate_dateedit.setMaximumDate(
            QDate.currentDate())
        self.notification_schedule_todate_dateedit.setDate(QDate.currentDate())
        self.notification_schedule_todate_dateedit.setCalendarPopup(True)
        self.notification_schedule_todate_dateedit.setObjectName(
            "notification_schedule_todate_dateedit")
        self.horizontalLayout_6.addWidget(
            self.notification_schedule_todate_dateedit)
        self.type_label = QLabel(self.notificationTab_tab_4)
        self.type_label.setObjectName("type_label")
        self.horizontalLayout_6.addWidget(self.type_label)
        self.notification_states = QComboBox(self.notificationTab_tab_4)
        self.notification_states.setObjectName("notification_states")
        self.horizontalLayout_6.addWidget(self.notification_states)
        self.batch_label = QLabel(self.notificationTab_tab_4)
        self.batch_label.setObjectName("batch_label")
        self.horizontalLayout_6.addWidget(self.batch_label)
        self.notification_results = QComboBox(self.notificationTab_tab_4)
        self.notification_results.setObjectName("notification_results")
        self.horizontalLayout_6.addWidget(self.notification_results)
        self.gridLayout_19.addLayout(self.horizontalLayout_6, 1, 0, 1, 1)
        self.gridLayout_8 = QGridLayout()
        self.gridLayout_8.setObjectName("gridLayout_8")
        self.notification_schedule_table = QTableWidget(
            self.notificationTab_tab_4)
        self.notification_schedule_table.setObjectName(
            "notification_schedule_table")
        self.notification_schedule_table.setColumnCount(5)
        self.notification_schedule_table.setRowCount(0)
        self.notification_schedule_table.setWordWrap(True)
        item = QTableWidgetItem()
        self.notification_schedule_table.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem()
        self.notification_schedule_table.setHorizontalHeaderItem(1, item)
        item = QTableWidgetItem()
        self.notification_schedule_table.setHorizontalHeaderItem(2, item)
        item = QTableWidgetItem()
        self.notification_schedule_table.setHorizontalHeaderItem(3, item)
        item = QTableWidgetItem()
        self.notification_schedule_table.setHorizontalHeaderItem(4, item)
        self.notification_schedule_table.horizontalHeader(
        ).setCascadingSectionResizes(True)
        self.notification_schedule_table.horizontalHeader(
        ).setStretchLastSection(True)
        self.notification_schedule_table.verticalHeader().setVisible(False)
        self.notification_schedule_table.verticalHeader(
        ).setCascadingSectionResizes(True)
        self.notification_schedule_table.verticalHeader(
        ).setStretchLastSection(False)
        self.gridLayout_8.addWidget(self.notification_schedule_table, 0, 0, 1,
                                    5)
        self.notification_search_button = QPushButton(
            self.notificationTab_tab_4)
        self.notification_search_button.setObjectName(
            "notification_search_button")
        self.gridLayout_8.addWidget(self.notification_search_button, 1, 0, 1,
                                    1)
        spacerItem10 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.gridLayout_8.addItem(spacerItem10, 1, 2, 1, 1)
        self.notification_reset_button = QPushButton(
            self.notificationTab_tab_4)
        self.notification_reset_button.setObjectName(
            "notification_reset_button")
        self.gridLayout_8.addWidget(self.notification_reset_button, 1, 3, 1, 1)
        self.notification_load_more_button = QPushButton(
            self.notificationTab_tab_4)
        self.notification_load_more_button.setObjectName(
            "notification_load_more_button")
        self.gridLayout_8.addWidget(self.notification_load_more_button, 1, 4,
                                    1, 1)
        self.gridLayout_19.addLayout(self.gridLayout_8, 2, 0, 1, 1)
        ###retranslate
        self.title_label.setText(
            QApplication.translate(
                "MainWindow", "<html><head/><body><p align=\"center\">"
                "<span style=\" font-weight:600;font-size:20px\">"
                "<u>All Notifications</u></span></p></body></html>", None,
                QApplication.UnicodeUTF8))
        self.id_label.setText(
            QApplication.translate("MainWindow", "Message Id", None,
                                   QApplication.UnicodeUTF8))
        self.notification_schedule_fromdate_label.setText(
            QApplication.translate("MainWindow", "From Date", None,
                                   QApplication.UnicodeUTF8))
        self.notification_schedule_fromdate_dateedit.setDisplayFormat(
            QApplication.translate("MainWindow", "dd/MM/yyyy", None,
                                   QApplication.UnicodeUTF8))
        self.notification_schedule_todate_label.setText(
            QApplication.translate("MainWindow", "To Date", None,
                                   QApplication.UnicodeUTF8))
        self.notification_schedule_todate_dateedit.setDisplayFormat(
            QApplication.translate("MainWindow", "dd/MM/yyyy", None,
                                   QApplication.UnicodeUTF8))
        self.type_label.setText(
            QApplication.translate("MainWindow", "Type", None,
                                   QApplication.UnicodeUTF8))
        self.batch_label.setText(
            QApplication.translate("MainWindow", "Number of Notifications",
                                   None, QApplication.UnicodeUTF8))
        self.notification_schedule_table.horizontalHeaderItem(0).setText(
            QApplication.translate("MainWindow", "Message Id", None,
                                   QApplication.UnicodeUTF8))
        self.notification_schedule_table.horizontalHeaderItem(1).setText(
            QApplication.translate("MainWindow", "Date", None,
                                   QApplication.UnicodeUTF8))
        self.notification_schedule_table.horizontalHeaderItem(2).setText(
            QApplication.translate("MainWindow", "From", None,
                                   QApplication.UnicodeUTF8))
        self.notification_schedule_table.horizontalHeaderItem(3).setText(
            QApplication.translate("MainWindow", "Message", None,
                                   QApplication.UnicodeUTF8))
        self.notification_schedule_table.horizontalHeaderItem(4).setText(
            QApplication.translate("MainWindow", "State", None,
                                   QApplication.UnicodeUTF8))
        self.notification_search_button.setText(
            QApplication.translate("MainWindow", "Search", None,
                                   QApplication.UnicodeUTF8))
        self.notification_reset_button.setText(
            QApplication.translate("MainWindow", "Reset All", None,
                                   QApplication.UnicodeUTF8))
        self.notification_load_more_button.setText(
            QApplication.translate("MainWindow", "Load More", None,
                                   QApplication.UnicodeUTF8))
        ##signals and slotts && other stuffs
        self.scheduletable_count = 0
        self.addtable_count = 0
        # self.mainwindow = Ui_MainWindow  # just for the ease of finding the attributes in pycharm
        self.notification_schedule_table.setEditTriggers(
            QAbstractItemView.NoEditTriggers)
        self.batch_number = None
        self.notification_results.addItems([str(i) for i in range(1, 50, 5)])
        self.notification_states.addItems(['All', 'New', 'To Do', 'Done'])
        self.message = Messaging()
        self.notification_load_more_button.clicked.connect(self.load_more)
        self.notification_search_button.clicked.connect(self.search_messages)
        self.notification_reset_button.clicked.connect(self.reset_all)
        self.notificationTab_tab_4.setFocusPolicy(Qt.StrongFocus)
        self.notificationTab_tab_4.focusInEvent = self.load_rows
        # self.assign_shortcuts()

        # def assign_shortcuts(self):
        # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_search']),
        # self.notificationTab_tab_4, self.search_messages)
        # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_additem']),
        # self.notificationTab_tab_4, self.add_new_blank_rows)
        # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_print']),
        # self.notificationTab_tab_4, self.commit_and_print)
        # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_today']),
        # self.notificationTab_tab_4, lambda: self.load_messages('today'))
        # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_tommorow']),
        # self.notificationTab_tab_4, lambda: self.load_messages('tomorrow'))
        # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_thismonth']),
        # self.notificationTab_tab_4, lambda: self.load_messages('month'))
        # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_thisweek']),
        # self.notificationTab_tab_4, lambda: self.load_messages('week'))
        # QShortcut(QKeySequence(settings.custom_shortcut['key_tabcon_inventorynotification_clear']),
        # self.notificationTab_tab_4, self.clear_table)

    def add_messages(self, *args):
        """
        Populates the Schedules when we load the tab
        """
        table = self.notification_schedule_table
        if args:
            if args[0] != 'new':
                table.clearContents()
                table.setRowCount(0)
                table.setRowCount(len(args))
                for i, j in enumerate(args):
                    item = QTableWidgetItem(j['msg_id'])
                    table.setItem(i, 0, item)
                    item = QTableWidgetItem(j['date'])
                    table.setItem(i, 1, item)
                    item = QTableWidgetItem(
                        'Name:{}\nDesignation:{}\nAddress:{}'.format(
                            j['name'], j['designation'], j['address']))
                    table.setItem(i, 2, item)
                    item = QTableWidgetItem(
                        'Message Type:{}\nMessage:{}'.format(
                            j['msg_type'].title(), j['msg_body']))
                    table.setItem(i, 3, item)
                    states = QComboBox()
                    self.populate_states(states, j['msg_state'].title())
                    states.currentIndexChanged.connect(
                        lambda index, row=i: self.changed_state(row, index))
                    table.setCellWidget(i, 4, states)
            elif args[0] == 'new':
                initial = table.rowCount()
                row = table.rowCount() + len(args[1])
                table.setRowCount(row)
                forward_range = range(initial, row)
                for i, j in zip(forward_range, args[1]):
                    item = QTableWidgetItem(j['msg_id'])
                    table.setItem(i, 0, item)
                    item = QTableWidgetItem(j['date'])
                    table.setItem(i, 1, item)
                    item = QTableWidgetItem(
                        'Name:{}\nDesignation:{}\nAddress:{}'.format(
                            j['name'], j['designation'], j['address']))
                    table.setItem(i, 2, item)
                    item = QTableWidgetItem(
                        'Message Type:{}\nMessage:{}'.format(
                            j['msg_type'].title(), j['msg_body']))
                    table.setItem(i, 3, item)
                    states = QComboBox()
                    self.populate_states(states, j['msg_state'].title())
                    states.currentIndexChanged.connect(
                        lambda index, row=i: self.changed_state(row, index))
                    table.setCellWidget(i, 4, states)
        table.setColumnWidth(0, (table.width() * 0.5) / 5)
        table.setColumnWidth(1, (table.width() * 0.5) / 5)
        table.setColumnWidth(2, table.width() / 5)
        table.setColumnWidth(3, (table.width() * 2) / 5)
        self.notification_schedule_table.resizeRowsToContents()

    def populate_states(self, combo, state):
        """
        fills the supplier list for each item line
        :param combo: the combo box of suppliers
        :return:none
        """
        combo.setStyleSheet("QAbstractItemView{" "background: #4B77BE;" "}")
        combo.addItems(['New', 'To Do', 'Done'])
        index = combo.findText(state)
        combo.setCurrentIndex(index)

    def changed_state(self, row, index):
        """
        fill the item combo box
        :param combo: the combobox object
        :return: none
        """
        table = self.notification_schedule_table
        data = {}
        data['message_id'] = table.item(row, 0).text()
        data['msg_state'] = table.cellWidget(row, 4).currentText()
        msg = QMessageBox.information(
            QMessageBox(), 'Alert!!',
            'Do you want to change the status of the Message??',
            QMessageBox.Yes | QMessageBox.No)
        if msg == QMessageBox.Yes:
            report = self.message.update_message(data)
            if report:
                _ = QMessageBox.information(QMessageBox(), 'Success!!',
                                            'The Message was updated',
                                            QMessageBox.Yes | QMessageBox.No)
            else:
                _ = QMessageBox.critical(QMessageBox(), 'Error!!',
                                         'The Message was not updated',
                                         QMessageBox.Yes | QMessageBox.No)

    def search_messages(self):
        """
        Searches for messages when search button is pressed
        """
        logger.info('Notifications searching messages initiated')
        from_date = self.notification_schedule_fromdate_dateedit.text()
        to_date = self.notification_schedule_todate_dateedit.text()
        limit = self.notification_results.currentText()
        msg_id = self.id_line.text()
        msg_state = self.notification_states.currentText()
        dataobj = self.message.load_message(limit=limit,
                                            from_date=from_date,
                                            to_date=to_date,
                                            msg_id=msg_id,
                                            msg_state=msg_state)
        if dataobj:
            self.add_messages(*dataobj)
        else:
            self.notification_schedule_table.clearContents()
            self.notification_schedule_table.setRowCount(0)

    def load_more(self):
        """
        Searches for messages when search button is pressed
        """
        logger.info('Notifications searching messages initiated')
        from_date = self.notification_schedule_fromdate_dateedit.text()
        to_date = self.notification_schedule_todate_dateedit.text()
        limit = self.notification_results.currentText()
        msg_id = self.id_line.text()
        msg_state = self.notification_states.currentText()
        offset = self.notification_schedule_table.rowCount()
        dataobj = self.message.load_message(limit=limit,
                                            from_date=from_date,
                                            to_date=to_date,
                                            msg_id=msg_id,
                                            msg_state=msg_state,
                                            offset=offset)
        if dataobj:
            self.add_messages('new', dataobj)
        else:
            self.notification_schedule_table.clearContents()
            self.notification_schedule_table.setRowCount(0)

    def load_single_message(self, msg_id):  # api
        """method to load a single message"""
        self.reset_all()
        dataobj = self.message.load_message(msg_id=msg_id)
        if dataobj:
            self.add_messages('new', dataobj)
            self.id_line.setText(str(msg_id))
        else:
            self.notification_schedule_table.clearContents()
            self.notification_schedule_table.setRowCount(0)

    def load_rows(self, event):
        """
        :return:loads the rows
        """
        self.add_messages()

    def reset_all(self):
        """
        :return: resets the the data in the search text
        """
        try:
            self.id_line.clear()
            self.notification_schedule_table.clearContents()
            self.notification_schedule_table.setRowCount(0)
        except Exception as _:
            if settings.level == 10:
                logger.exception('raised exception')
            return False
Exemple #39
0
class Dialog(QWidget):

    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setupUI()
        self.setupConnection()
        self.threadPool = []
        self.totalUids = 0
        self.finishedThreadNum = 0
        self.realThreadNum = 0
        self.excel = Excel()
        #self.initSearchDb()

    def setupUI(self):

        self.pushButton = QPushButton(u"Search", self)
        #self.testButton = QPushButton(u"Test", self)
        self.lineEdit = QLineEdit(self)
        self.textEdit = QTextEdit(self)
        self.comboBox = QComboBox(self)
        self.label = QLabel(u"DB:", self)
        self.progressBar = QProgressBar(self)
        self.progressBar.setRange(0,1)
        
        self.textEdit.setReadOnly(True)

        self.layout = QVBoxLayout()
        self.topLayout = QHBoxLayout()
        
        self.topLayout.addWidget(self.label)
        self.topLayout.addWidget(self.comboBox)
        self.topLayout.addWidget(self.lineEdit)
        self.topLayout.addWidget(self.pushButton)
        #self.topLayout.addWidget(self.testButton)

        #self.testButton.clicked.connect(self.onTestButtonClicked)

        self.layout.addLayout(self.topLayout)
        self.layout.addWidget(self.textEdit)
        self.layout.addWidget(self.progressBar)

        self.setLayout(self.layout)

        self.resize(600, 700)
        self.setWindowTitle(u"Search Data for NCBI")

    def setupConnection(self):
        self.pushButton.clicked.connect(self.onButtonClicked)

    def onButtonClicked(self):
        if not self.lineEdit.text() or not self.comboBox.count():
            QtGui.QMessageBox.information(self, u"Warning", u"Please Set the Search Field")
            return
        # disable button
        self.pushButton.setDisabled(True)
        dbName = self.comboBox.currentText()
        fieldName = self.lineEdit.text()
        self.log("Start searching db: %s and field: %s" % (dbName, fieldName))
        # add use history to add all uids to the history server
        handle = self.entrez.esearch(db=dbName, term=fieldName, usehistory='y')
        record = self.entrez.read(handle)
        self.log("All result count %s" % record['Count'])
        self.totalUids = int(record['Count'])
        # to get onnly data less than the MAX_COUNT
        if self.totalUids > MAX_COUNT:
            ret = QtGui.QMessageBox.question(
                    self,
                    u'Warning',
                    u'result count %s is too large, will only get the %s result \
                            continue?' % (self.totalUids, MAX_COUNT),
                            QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel
                            )
            if ret == QtGui.QMessageBox.Ok:
                self.totalUids = MAX_COUNT
            else:
                return
        #handle = self.entrez.efetch(db=dbName, id=record['IdList'], rettype='gb')
        self.finishedThreadNum = 0
        WebEnv = record['WebEnv']
        QueryKey = record['QueryKey']
        global FINISHED_COUNT
        FINISHED_COUNT = 0
        self.progressBar.setValue(0)
        self.progressBar.setMaximum(self.totalUids)
        if self.totalUids / RET_MAX_SUMMARY >= MAX_THREAD:
            self.realThreadNum = MAX_THREAD
            each_count = self.totalUids/MAX_THREAD
            startIndex = 0
            for i in range(MAX_THREAD - 1):
                thread = MyThread(startIndex, each_count, dbName, fieldName, WebEnv, QueryKey)
                thread.finished.connect(self.onThreadFinished)
                thread.finishedCountChanged.connect(self.onFinishedCountChange)
                thread.start()
                self.threadPool.append(thread)
                startIndex = startIndex + each_count
            thread = MyThread(startIndex, (self.totalUids-startIndex+1), dbName, fieldName, WebEnv, QueryKey)
            thread.finished.connect(self.onThreadFinished)
            thread.finishedCountChanged.connect(self.onFinishedCountChange)
            self.threadPool.append(thread)
            thread.start()
        else:
            if self.totalUids == RET_MAX_SUMMARY:
                self.realThreadNum = 1
            else:
                self.realThreadNum = self.totalUids/RET_MAX_SUMMARY + 1
            startIndex = 0
            for i in range(self.realThreadNum):
                thread = MyThread(startIndex, RET_MAX_SUMMARY, dbName, fieldName, WebEnv, QueryKey)
                thread.finished.connect(self.onThreadFinished)
                thread.finishedCountChanged.connect(self.onFinishedCountChange)
                self.threadPool.append(thread)
                thread.start()
                startIndex = startIndex + RET_MAX_SUMMARY
        self.log("thread num: %s" % self.realThreadNum)
        self.log('reading data')
        self.filename = '%s_%s_output.xls' % (dbName, fieldName)
        self.excel.setFilename(self.filename)

    def log(self, context):
        self.textEdit.append(context)

    def initSearchDb(self):
        self.entrez = Entrez 
        self.entrez.email = email
        self.log("Connect to NCBI")
        try:
            handle = self.entrez.einfo()
        except:
            QtGui.QMessageBox.warning(self, u"Error", u"Error Connect the WebSite")
            self.close()
        record = self.entrez.read(handle)
        self.log("Get NCBI DataBases:")
        for name in record['DbList']:
            self.log('DBName:\t%s' % name)
        self.comboBox.addItems(record['DbList'])

    def onThreadFinished(self):
        self.finishedThreadNum = self.finishedThreadNum + 1
        self.log('finished thread %s ' % self.finishedThreadNum)
        if(self.finishedThreadNum == self.realThreadNum):
            global all_output
            heads = all_output[0][0].keys()
            self.excel.setHead(heads)
            for values in all_output:
                for value in values:
                    self.excel.addValues(value)
            self.excel.save()
            self.progressBar.setValue(int(self.totalUids))
            # clear all thread
            self.threadPool = []
            all_output = []
            self.excel.clearValues()
            self.pushButton.setDisabled(False)
            self.log("output to file: %s" % self.filename)

    def onFinishedCountChange(self, num):
        self.progressBar.setValue(num)

    def onTestButtonClicked(self):
        self.finishedThreadNum = 0
        self.realThreadNum = 1
        self.thread = MyThread(0, 10,"abd","123")
        self.thread.finished.connect(self.onThreadFinished)
        self.thread.startIndex()
Exemple #40
0
class MainWindow(QWidget):
    def __init__(self, fixtures_folder, parent=None):
        QWidget.__init__(self, parent)
        self.current_fixture = None
        self.fixtures_folder = fixtures_folder
        self.setWindowTitle("Frangitron DMX program editor")

        self.text = QPlainTextEdit()
        font = QFont("Monospace")
        font.setStyleHint(QFont.TypeWriter)
        font.setPixelSize(16)
        self.text.setFont(font)
        self.text.setStyleSheet(
            "color: white; background-color: rgb(30, 30, 30)")

        self.combo_fixture = QComboBox()

        self.frame_programs = QWidget()
        self.checkboxes_programs = list()
        self.layout_programs = QGridLayout(self.frame_programs)

        self.spinner_offset = QSpinBox()
        self.spinner_offset.setMinimum(1)
        self.spinner_offset.setMaximum(512)
        self.spinner_offset.setValue(1)
        self.spinner_offset.valueChanged.connect(self.address_changed)

        self.doc = QPlainTextEdit()
        self.doc.setReadOnly(True)
        self.doc.setFont(font)

        self.status = QLabel()

        layout = QGridLayout(self)
        layout.addWidget(self.combo_fixture, 0, 1)
        layout.addWidget(self.spinner_offset, 0, 2)
        layout.addWidget(self.frame_programs, 1, 1)
        layout.addWidget(self.text, 0, 0, 3, 1)
        layout.addWidget(self.doc, 2, 1, 1, 2)
        layout.addWidget(self.status, 3, 0, 1, 3)
        layout.setColumnStretch(0, 60)
        layout.setColumnStretch(1, 40)

        self.resize(1280, 800)

        self.streamer = Streamer(self.fixtures_folder)

        self.combo_fixture.addItems(sorted(self.streamer.fixtures))
        self.combo_fixture.currentIndexChanged.connect(self.fixture_changed)

        self.timer = QTimer()
        self.timer.timeout.connect(self.tick)
        self.timer.start(500.0 / FRAMERATE)
        self.should_reload = True

        self.fixture_changed()

    def selected_programs(self):
        return [
            chk.text() for chk in self.checkboxes_programs if chk.isChecked()
        ]

    def update_programs(self):
        selected_programs = self.selected_programs()

        for checkbox_program in self.checkboxes_programs:
            self.layout_programs.removeWidget(checkbox_program)
            checkbox_program.deleteLater()
        self.checkboxes_programs = list()

        for i, program_name in enumerate(
                sorted(self.current_fixture.programs.keys())):
            column = i // 4
            row = i % 4

            new_checkbox = QCheckBox(program_name)
            new_checkbox.setChecked(program_name in selected_programs)

            self.layout_programs.addWidget(new_checkbox, row, column)
            self.checkboxes_programs.append(new_checkbox)

    def address_changed(self):
        self.current_fixture.address = self.spinner_offset.value()
        self.doc.setPlainText(self.current_fixture.doc())
        self.update_programs()

    def fixture_changed(self):
        self.current_fixture = self.streamer.fixtures[
            self.combo_fixture.currentText()]
        self.address_changed()
        self.streamer.reset_expressions()
        with open(self.current_fixture.programs_filepath, 'r') as f_programs:
            self.text.setPlainText(f_programs.read())

    def tick(self):
        if self.should_reload:
            self.current_fixture.reload_programs()
            self.update_programs()
            self.streamer.reset_state()
            program = PROGRAM.replace('__fixture__', self.current_fixture.name)
            program = program.replace('__address__',
                                      str(self.current_fixture.address))
            program = program.replace(
                '__programs__', ", ".join([
                    '"{}"'.format(prog) for prog in self.selected_programs()
                ]))
            self.streamer.load(programs_source=program)
            self.streamer.program_clicked("1")

        else:
            state = self.streamer.state

            if state:
                self.status.setStyleSheet(
                    "background-color: green; color: white; padding: 5px")
                self.status.setText(state.context)
            else:
                self.status.setStyleSheet(
                    "background-color: red; color: white; padding: 5px")
                self.status.setText("{} : {}".format(state.context,
                                                     state.exception))

            if self.current_fixture is None: return

            with open(self.current_fixture.programs_filepath,
                      'w') as f_programs:
                f_programs.write(self.text.toPlainText())

        self.should_reload = not self.should_reload

    def closeEvent(self, event):
        self.timer.stop()
        self.streamer.load(programs_source="")
        self.streamer.program_clicked("1")
        sleep(2.0 / float(FRAMERATE))
        self.streamer.stop()
        event.accept()
Exemple #41
0
class WindowMain(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self._comm = Comm()
        self._isRecording = False
        self._settings = Settings()

        self.customWidgets = {'WidgetLcd': WidgetLcd, 'WidgetPlot': WidgetPlot}
        loadUi(self, 'mainwindow.ui')

        self.__setupToolbar()
        self.__setupStatusbar()

        self._settings.setComboPort(self._comboSerial)

        self.adjustSize()

    def __setupToolbar(self):
        widgetSpacer = QWidget()
        widgetSpacer.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred))

        self._comboSerial = QComboBox()
        self._comboSerial.addItems(self._comm.getPorts())
        self._comboSerial.setToolTip('Serial port')

        self.toolbar.addWidget(widgetSpacer)
        self.toolbar.addWidget(self._comboSerial)

        icon = QIcon(getResource('record.png'))
        self.actionRecord.setIcon(icon)
        icon = QIcon(getResource('clear.png'))
        self.actionClear.setIcon(icon)

    def __setupStatusbar(self):
        self._ledData = WidgetLed(self, '#2a426b')
        self._ledData.setToolTip('Data received')
        self._ledBatt = WidgetLed(self, '#ea5b00')
        self._ledBatt.setToolTip('Low battery')
        self.statusbar.addPermanentWidget(self._ledData)
        self.statusbar.addPermanentWidget(self._ledBatt)
        self.statusbar.showMessage('Ready')

    @Slot()
    def on_actionRecord_triggered(self):
        if self.actionRecord.isChecked():
            self.__start()
        else:
            self.__stop()

    @Slot()
    def on_actionClear_triggered(self):
        self._widgetLcd.clear()
        self._widgetPlot.clearPlot()
        self.actionClear.setDisabled(True)

    def __onData(self, meter):
        self.statusbar.showMessage('Recording')
        if self._isRecording:
            self._widgetLcd.set(meter)
            self._widgetPlot.set(meter)
            self.actionClear.setEnabled(True)
            self._ledData.flash()
            if meter.batt:
                self._ledBatt.light(True)

    def __onWarning(self, warning):
        self._widgetLcd.clear()
        self.statusbar.showMessage(warning)

    def __onError(self, error):
        self.__stop()
        QMessageBox.critical(self, 'Error', error, QMessageBox.Ok)

    def closeEvent(self, _event):
        self.__stop()
        self._settings.getComboPort(self._comboSerial)

    def __start(self):
        self._isRecording = True
        self._comboSerial.setDisabled(True)
        port = self._comboSerial.currentText()
        self._comm.start(port, self.__onData, self.__onWarning, self.__onError)
        self.statusbar.showMessage('Started')
        self._widgetPlot.enableAutoRange()

    def __stop(self):
        self.actionRecord.setChecked(False)
        self._comboSerial.setEnabled(True)
        self._comm.stop()
        self.statusbar.showMessage('Stopped')
        self._widgetLcd.clear()
        self._ledBatt.light(False)
        self.__onData(Meter(time.time()))
        self._isRecording = False
Exemple #42
0
class qHotField(QWidget):
    def __init__(self, name, mytype, initial_value, value_list = None, pos = "left", help_text = None, help_instance = None, min_size = 0, max_size = None, handler = None, multiline=False):
        QWidget.__init__(self)
        if max_size == None:
            max_size = 300
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) # Let it expand horizontally but not vertically
        self.name = name
        self.mytype = mytype
        self.multiline = multiline
        self.setContentsMargins(1, 1, 1, 1)
        self.is_popup = (value_list != None)
        if self.is_popup:
            self.value_list = [str(v) for v in value_list] # It's possible the values won't be strings.
        if pos == "top":
            self.layout1 = QVBoxLayout()
        else:
            self.layout1=QHBoxLayout()
        self.layout1.setContentsMargins(1, 1, 1, 1)
        self.layout1.setSpacing(1)
        self.setLayout(self.layout1)
        if mytype == bool:
            self.cb = QCheckBox(name)
            self.cb.setFont(regular_small_font)
            self.layout1.addWidget(self.cb)
            self.cb.setChecked(initial_value)
            if handler != None:
                self.cb.toggled.connect(handler)
        else:
            if not self.is_popup:
                if multiline:
                    self.efield=QPlainTextEdit("")
                    self.efield.appendPlainText(str(initial_value))
                else:
                    self.efield = QLineEdit("Default Text")
                    self.efield.setText(str(initial_value))
                if handler != None:
                    self.efield.textChanged.connect(handler)
            else:
                self.efield = QComboBox()
                self.efield.addItems(value_list)
                if len(value_list) != 0:
                    self.efield.setCurrentIndex(value_list.index(initial_value))
                self.efield.setSizeAdjustPolicy(QComboBox.AdjustToContents)
                if handler != None:
                    self.efield.currentIndexChanged.connect(handler)
                self.layout1.setContentsMargins(5, 5, 5, 5) # Popups need a little more space
                self.layout1.setSpacing(2)
            self.efield.setFont(regular_small_font)
            self.label = QLabel(name)
            self.label.setFont(regular_small_font)
            if pos == "right":
                self.layout1.addWidget(self.efield)
                self.layout1.addWidget(self.label)
            else:
                self.layout1.addWidget(self.label)
                self.layout1.addWidget(self.efield)
            
            self.efield.setMaximumWidth(max_size)
            if min_size != 0:
                self.efield.setMinimumWidth(min_size)
        self.layout1.addStretch()
        if help_text != None:
            if (help_instance == None):
                print "No help instance specified."
            else:
                help_button_widget = help_instance.create_button(name, help_text)
                self.layout1.addWidget(help_button_widget)
                    
    def repopulate_list(self, initial_value, value_list):
        if not self.is_popup:
            print "This qHotField is not a popup list. So it can't be repopulated"
            return
        self.value_list = [str(v) for v in value_list] # It's possible the values won't be strings
        self.efield.clear()
        self.efield.addItems(value_list)
        self.efield.setCurrentIndex(value_list.index(initial_value))
        return
        
    def get_myvalue(self):
        if self.mytype == bool:
            return self.cb.isChecked()
        else:
            if self.is_popup:
                the_txt = self.efield.currentText()
            else:
                if self.multiline:
                    the_txt = self.efield.toPlainText()
                else:
                    the_txt = self.efield.text()
            if (self.mytype == str) or (self.mytype == unicode):
                return (self.mytype)(the_txt)
            else: # if we have a numerical type, the user might have entered a list separated by spaces. Handle that specially
                the_val = re.findall(r"\S+", the_txt) # We might have a list of values separated by spaces if this is a numerical variable
                if len(the_val) == 1:  # it's just a single value
                    result = (self.mytype)(the_txt)
                else: # it's a list. We want to convert treat this as a monte sequence
                    res = []
                    for v in the_val:
                        res.append((self.mytype)(v))
                    result = MonteSequence(res)
                return result
        
    def set_myvalue(self, val):
        if self.mytype == bool:
            self.cb.setChecked(val)
        elif self.is_popup:
            self.efield.setCurrentIndex(self.value_list.index(val))
        else:
            if type(val) == list:
                result = ""
                for x in val:
                    result = result + str(x) + " "
                self.efield.setText(result)
            else:
                if self.multiline:
                    self.efield.clear()
                    self.efield.appendPlainText(str(val))
                else:
                    self.efield.setText(str(val))
    value = property(get_myvalue, set_myvalue)
Exemple #43
0
    def __init__(self):
        '''
        Constructor
        '''
        super(MyWidget1, self).__init__()
        gridlayout = QGridLayout()

        label1 = QLabel("KATEGORIJA")
        label2 = QLabel("DEONICA")
        label3 = QLabel("VALUTA")

        kategorija = QGroupBox()
        hbox = QHBoxLayout()

        iakat = QRadioButton("Ia")
        iakat.setChecked(True)
        #lakat.setIcon(QIcon("lakat.png"))
        ikat = QRadioButton("I")
        iikat = QRadioButton("II")
        iiikat = QRadioButton("III")
        ivkat = QRadioButton("IV")
        hbox.addWidget(iakat)
        hbox.addWidget(ikat)
        hbox.addWidget(iikat)
        hbox.addWidget(iiikat)
        hbox.addWidget(ivkat)
        kategorija.setLayout(hbox)

        deonica = QComboBox()
        deonica.setEditable(False)

        deonica.addItems(Deonice().listaDeonica)

        valuta = QGroupBox()
        hbox1 = QHBoxLayout()
        eur = QRadioButton("EUR")
        rsd = QRadioButton("RSD")
        rsd.setChecked(True)
        cenaRsd = QLineEdit()
        cenaRsd.setReadOnly(True)
        cenaEur = QLineEdit()
        cenaEur.setReadOnly(True)
        hbox1.addWidget(rsd)
        hbox1.addWidget(cenaRsd)
        hbox1.addWidget(eur)
        hbox1.addWidget(cenaEur)
        valuta.setLayout(hbox1)

        btnNaplati = QPushButton("\nNAPLATI\n")
        btnNaplati.clicked.connect(self.naplatiAction)

        btnPodigni = QPushButton("\nPODIGNI RAMPU\n")
        btnPodigni.clicked.connect(self.podigniAction)

        btnSpusti = QPushButton("\nSPUSTI RAMPU\n")
        btnSpusti.clicked.connect(self.spustiAction)

        gridlayout.addWidget(label1, 0, 0, 2, 3, int(Qt.AlignCenter))
        gridlayout.addWidget(label2, 2, 0, 2, 3, int(Qt.AlignCenter))
        gridlayout.addWidget(label3, 4, 0, 2, 3, int(Qt.AlignCenter))

        gridlayout.addWidget(kategorija, 0, 3, 2, 6)

        gridlayout.addWidget(deonica, 2, 3, 2, 6)

        gridlayout.addWidget(valuta, 4, 3, 2, 6)

        gridlayout.addWidget(btnNaplati, 6, 0, 2, 10)

        gridlayout.addWidget(btnPodigni, 8, 0, 2, 5)
        gridlayout.addWidget(btnSpusti, 8, 5, 2, 5)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def translate(self, ar=True):
        if ar:
            self.Arabic = "arabic"
            self.labutton.setEnabled(False)
            self.labutton.setText(u"العربية")
            self.labutton.setToolTip(u"تغير اللغة إلى العربية")
            self.lebutton.setText(u"الإنجليزية")
            self.lebutton.setToolTip(u"تغير اللغة إلى الإنجليزية")
            self.lebutton.setEnabled(True)
            self.Amsgb = u"عن النظام"
            self.abutton.setToolTip(u"عن النظام")
            self.mbutton.setText(u"تشغــيل")
            self.mbutton.setToolTip(u"تشغيل الخدمة")
            self.mbutton2.setText(u"إيــقاف")
            self.mbutton2.setToolTip(u"إيقاف الخدمة")
            self.sl.setToolTip(u"إختار عنوان IP ليتم بث الخدمة عليه")
            self.sl2.setToolTip(u"إختار منفذ ليتم بث الخدمة من خلاله")
            self.t.setToolTip(u"حالة الخدمة ")
            self.l.setToolTip(u"حالة الخدمة ")
            if self.Runningo:
                pp = self.slchange()
                addr = u"الخدمة <u>مشغــلة</u> و تبث على : <br>"
                addr += u"<a href='http://"
                addr += pp[1].split(',')[1] + u":" + pp[0]
                addr += u"'> http://" + pp[1].split(',')[1] + u":" + pp[0]
                addr += u"</a>"
                self.t.setText(addr)
            else:
                self.t.setText(u"الــخـدمة <u>متــوقفــة</u><br>")
        else:
            self.Arabic = None
            self.lebutton.setEnabled(False)
            self.lebutton.setText("English")
            self.lebutton.setToolTip('Change language to English')
            self.labutton.setEnabled(True)
            self.labutton.setText("Arabic")
            self.labutton.setToolTip('Change language to Arabic')
            self.Amsgb = "About FQM"
            self.abutton.setToolTip('About FQM')
            self.mbutton.setText("Start")
            self.mbutton.setToolTip("Start the server")
            self.mbutton2.setText("Stop")
            self.mbutton2.setToolTip("Stop the server")
            self.sl.setToolTip(
                'Select network interface with ip, so the server runs on it')
            self.sl2.setToolTip('Select a port, so server runs through it')
            self.t.setToolTip('Status of the server')
            self.l.setToolTip('Status of the server')
            if self.Runningo:
                pp = self.slchange()
                addr = "Server is <u>Running</u> <br>"
                addr += " On : <a href='http://"
                addr += pp[1].split(',')[1] + ":" + pp[0]
                addr += "'> http://" + pp[1].split(',')[1] + ":" + pp[0]
                addr += "</a>"
                self.t.setText(addr)
            else:
                self.t.setText("Server is <u> Not running </u> <br>")
class Form(QDialog):
    def __init__(self, parent=None):

        self.rates = {}
        super(Form, self).__init__(parent)

        date = self.get_data()
        rates = sorted(self.rates.keys())

        # Create UI Elements -------------------------------------------------------------------------------------------
        dateLabel = QLabel(date)
        self.fromComboBox = QComboBox()
        self.toComboBox = QComboBox()

        self.fromComboBox.addItems(rates)
        self.toComboBox.addItems(rates)

        self.fromSpinBox = QDoubleSpinBox()

        # Saturation of minimum and maximum values
        self.fromSpinBox.setRange(0.01, 1000)
        # Set initial value
        self.fromSpinBox.setValue(1.00)

        self.toLabel = QLabel('1.00')

        # Layout -------------------------------------------------------------------------------------------------------
        layout = QGridLayout()
        # addWidget (Widget, row, column)
        layout.addWidget(dateLabel, 0, 0)
        layout.addWidget(self.fromComboBox, 1, 0)
        layout.addWidget(self.toComboBox, 2, 0)
        layout.addWidget(self.fromSpinBox, 1, 1)
        layout.addWidget(self.toLabel, 2, 1)
        self.setLayout(layout)

        # Signals ------------------------------------------------------------------------------------------------------
        self.fromComboBox.currentIndexChanged.connect(self.update_ui)
        self.toComboBox.currentIndexChanged.connect(self.update_ui)

        self.fromSpinBox.valueChanged.connect(self.update_ui)


        # Force window to stay on top when start
        self.setWindowFlags(Qt.WindowStaysOnTopHint)

    def get_data(self):
        date = 'Unknown'

        url = "http://www.bankofcanada.ca/en/markets/csv/exchange_eng.csv"
        try:
            date = None
            fh = urllib2.urlopen(url)
            for line in fh:
                line = line.rstrip()
                if not line or line.startswith(("#", "Closing ")):
                    continue
                fields = line.split(",")
                if line.startswith("Date "):
                    date = fields[-1]
                else:
                    try:
                        value = float(fields[-1])
                        self.rates[unicode(fields[0])] = value
                    except ValueError:
                        pass
            return "Exchange Rates Date: " + date
        except Exception, e:
            return "Failed to download: \n%s" % e
class _SummaryOptionsToolItem(_ResultsToolItem):

    def _initUI(self):
        # Variables
        self._parameter_getters = {}

        def _program_getter(options):
            programs = list(options.programs)
            if len(programs) == 1:
                return programs[0]
            else:
                return list(programs)
        self._parameter_getters['program'] = _program_getter

        options = self.options()
        for name, getter in iter_getters(options):
            values = np.array(getter(options), ndmin=1)
            if len(values) < 2:
                continue
            self._parameter_getters[name] = getter

        # Actions
        act_add_series = QAction(getIcon("list-add"), "Add series", self)
        act_remove_series = QAction(getIcon("list-remove"), "Remove series", self)
        act_clear_series = QAction(getIcon("edit-clear"), "Clear", self)

        # Widgets
        self._cb_result_key = QComboBox()

        self._cb_x_parameter = QComboBox()
        self._cb_x_parameter.addItems(list(self._parameter_getters.keys()))

        self._lst_series = QListView()
        self._lst_series.setModel(_SeriesModel())

        tlb_series = QToolBar()
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        tlb_series.addWidget(spacer)
        tlb_series.addAction(act_add_series)
        tlb_series.addAction(act_remove_series)
        tlb_series.addAction(act_clear_series)

        self._chk_normalize = QCheckBox('Normalize series')

        # Layouts
        layout = _ResultsToolItem._initUI(self)
        layout.addRow("Result", self._cb_result_key)
        layout.addRow("X parameter", self._cb_x_parameter)
        layout.addRow("Series", self._lst_series)
        layout.addRow(tlb_series)
        layout.addRow(self._chk_normalize)

        # Signals
        act_add_series.triggered.connect(self._onAddSeries)
        act_remove_series.triggered.connect(self._onRemoveSeries)
        act_clear_series.triggered.connect(self._onClearSeries)
        self._lst_series.doubleClicked.connect(self._onSeriesDoubleClicked)
        self._cb_result_key.currentIndexChanged.connect(self._onResultKeyChanged)
        self._chk_normalize.stateChanged.connect(self.stateChanged)

        # Defaults
        keys = set()
        for container in self.results():
            for key, result in container.items():
                if not isinstance(result, _SummarizableResult):
                    continue
                keys.add(key)
        self._cb_result_key.addItems(sorted(keys))

        return layout

    def _onResultKeyChanged(self):
        ndim = self._getResultDimensions()
        self._cb_x_parameter.setEnabled(ndim == 1)

    def _onAddSeries(self):
        # Dialog
        result_key = self._cb_result_key.currentText()

        if self._getResultDimensions() > 1:
            x_parameter_name = None
        else:
            x_parameter_name = self._cb_x_parameter.currentText()

        dialog = _SeriesDialog(self.results(), result_key,
                               self._parameter_getters, x_parameter_name)
        if not dialog.exec_():
            return

        # Create series
        series_name = dialog.name()
        parameter_value = dialog.parameterValue()
        summary_key = dialog.summaryKey()

        conditions = []
        for name, value in parameter_value.items():
            conditions.append((name, self._parameter_getters[name], value))

        model = self._lst_series.model()
        model.addSeries(_Series(series_name, conditions, summary_key))

        # Update widgets
        self._cb_result_key.setEnabled(False)
        self._cb_x_parameter.setEnabled(False)

        self.stateChanged.emit()

    def _onRemoveSeries(self):
        selection = self._lst_series.selectionModel().selection().indexes()
        if len(selection) == 0:
            QMessageBox.warning(self, "Series", "Select a row")
            return

        model = self._lst_series.model()
        for row in sorted(map(methodcaller('row'), selection), reverse=True):
            model.removeSeries(row)

        enabled = model.rowCount() == 0
        self._cb_result_key.setEnabled(enabled)
        self._cb_x_parameter.setEnabled(enabled)

        self.stateChanged.emit()

    def _onClearSeries(self):
        model = self._lst_series.model()
        model.clearSeries()

        self._cb_result_key.setEnabled(True)
        self._cb_x_parameter.setEnabled(True)

        self.stateChanged.emit()

    def _onSeriesDoubleClicked(self, index):
        series = self._lst_series.model().series(index.row())

        # Dialog
        result_key = self._cb_result_key.currentText()

        if self._getResultDimensions() > 1:
            x_parameter_name = None
        else:
            x_parameter_name = self._cb_x_parameter.currentText()

        dialog = _SeriesDialog(self.results(), result_key,
                               self._parameter_getters, x_parameter_name,
                               series)
        if not dialog.exec_():
            return

        # Create series
        series_name = dialog.name()
        parameter_value = dialog.parameterValue()
        summary_key = dialog.summaryKey()

        conditions = []
        for name, value in parameter_value.items():
            conditions.append((name, self._parameter_getters[name], value))

        model = self._lst_series.model()
        model.updateSeries(index.row(),
                           _Series(series_name, conditions, summary_key))

        self.stateChanged.emit()

    def _getResultDimensions(self):
        result_key = self._cb_result_key.currentText()

        for container in self.results():
            try:
                result = container[result_key]
            except KeyError:
                continue
            ndim = result.get_dimensions()

        return ndim

    def resultKey(self):
        return self._cb_result_key.currentText() or None

    def xParameterName(self):
        if self._getResultDimensions() > 1:
            return None
        return self._cb_x_parameter.currentText() or None

    def xParameterGetter(self):
        if self._getResultDimensions() > 1:
            return None
        text = self._cb_x_parameter.currentText()
        return self._parameter_getters.get(text)

    def listSeries(self):
        return self._lst_series.model().listSeries()

    def isNormalize(self):
        return self._chk_normalize.isChecked()
class CalculateSalaryWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.__parent = parent
        self.setWindowTitle("Calculate Salary")

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

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

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

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

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

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

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

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

        self.setupUI()

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

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

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

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

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

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

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

    def setupUI(self):

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

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

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

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

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

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

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

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

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

        layout.addLayout(table)

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

        layout.addLayout(bttnLayout)
        self.setLayout(layout)
Exemple #48
0
class Airport_project_UI(QWidget):

    airports = ['KRK', 'LA', 'LIS']

    elitism_possibly_values = ['true', 'false']

    max_flights_list = ['1', '2', '3', '4', '5']

    def __init__(self):
        QWidget.__init__(self)
        self.params = {}

        # self.setMinimumSize(600, 250)
        #self.setWindowTitle("Medody Optymalizacji - Projekt")
        # self.setIcon()

        self.start_airport_label = QLabel("Start airport:", self)
        self.start_airport_label.move(5, 10)
        self.start_airport = QLineEdit(self)
        self.start_airport.setText('1')
        #self.start_airport.addItems(self.airports)
        self.start_airport.setMinimumHeight(20)
        self.start_airport.setMaximumHeight(20)
        self.start_airport.setMinimumWidth(60)
        self.start_airport.setMaximumWidth(60)
        self.start_airport.move(150, 5)

        #TODO function to convert names of airport to indexes

        self.destination_airport_label = QLabel("Destination airport:", self)
        self.destination_airport_label.move(5, 40)
        self.destination_airport = QLineEdit(self)
        self.destination_airport.setText('2')
        # self.destination_airport.addItems(self.airports)
        self.destination_airport.setMinimumHeight(20)
        self.destination_airport.setMaximumHeight(20)
        self.destination_airport.setMaximumWidth(60)
        self.destination_airport.setMinimumWidth(60)
        self.destination_airport.move(150, 35)

        self.max_flights_label = QLabel("max number of flights:", self)
        self.max_flights_label.move(5, 70)
        self.max_flights = QLineEdit(self)
        self.max_flights.setText("3")
        #self.max_flights.addItems(self.max_flights_list)
        self.max_flights.setMaximumHeight(20)
        self.max_flights.setMinimumHeight(20)
        self.max_flights.setMaximumWidth(60)
        self.max_flights.setMinimumWidth(60)
        #self.max_flights.setMinimumWidth(60)
        self.max_flights.move(150, 65)

        self.cost_weight_label = QLabel("max cost weights:", self)
        self.cost_weight_label.move(5, 100)
        self.cost_weight = QLineEdit(self)
        self.cost_weight.setText("4")
        self.cost_weight.setMinimumWidth(60)
        self.cost_weight.setMaximumWidth(60)
        self.cost_weight.setMinimumHeight(20)
        self.cost_weight.setMaximumHeight(20)
        self.cost_weight.move(150, 95)

        self.time_weight_label = QLabel("time weight:", self)
        self.time_weight_label.move(5, 130)
        self.time_weight = QLineEdit(self)
        self.time_weight.setText("5")
        self.time_weight.setMinimumWidth(60)
        self.time_weight.setMaximumWidth(60)
        self.time_weight.setMinimumHeight(20)
        self.time_weight.setMaximumHeight(20)
        self.time_weight.move(150, 125)

        self.pop_size_label = QLabel("pop size:", self)
        self.pop_size_label.move(5, 160)  # +30

        self.pop_size = QLineEdit(self)
        self.pop_size.setText("6")
        self.pop_size.setMinimumWidth(60)
        self.pop_size.setMaximumWidth(60)
        self.pop_size.setMinimumHeight(20)
        self.pop_size.setMaximumHeight(20)
        self.pop_size.move(150, 155)  # +30

        self.generation_label = QLabel("generations:", self)
        self.generation_label.move(5, 190)  # +30

        self.generation = QLineEdit(self)
        self.generation.setText("7")
        self.generation.setMinimumWidth(60)
        self.generation.setMaximumWidth(60)
        self.generation.setMinimumHeight(20)
        self.generation.setMaximumHeight(20)
        self.generation.move(150, 185)  # +30

        self.mutation_rate_label = QLabel("mutation rate:", self)
        self.mutation_rate_label.move(5, 210)  # +30

        self.mutation_rate = QLineEdit(self)
        self.mutation_rate.setText("8")
        self.mutation_rate.setMinimumWidth(60)
        self.mutation_rate.setMaximumWidth(60)
        self.mutation_rate.setMinimumHeight(20)
        self.mutation_rate.setMaximumHeight(20)
        self.mutation_rate.move(150, 215)  # +30

        self.tournament_size_label = QLabel("tournament size:", self)
        self.tournament_size_label.move(5, 240)  # +30

        self.tournament_size = QLineEdit(self)
        self.tournament_size.setText("9")
        self.tournament_size.setMinimumWidth(60)
        self.tournament_size.setMaximumWidth(60)
        self.tournament_size.setMinimumHeight(20)
        self.tournament_size.setMaximumHeight(20)
        self.tournament_size.move(150, 245)  # +30

        self.elitism_label = QLabel("elitism:", self)
        self.elitism_label.move(5, 270)  # +30

        self.elitism = QComboBox(self)
        self.elitism.addItems(self.elitism_possibly_values)
        self.elitism.setMinimumWidth(60)
        self.elitism.setMaximumWidth(60)
        self.elitism.setMinimumHeight(20)
        self.elitism.setMaximumHeight(20)
        self.elitism.move(150, 275)  # +30

        self.destination_min_label = QLabel("dest min:", self)
        self.destination_min_label.move(5, 300)  # +30

        self.dest_min = QLineEdit(self)
        self.dest_min.setText("4")
        self.dest_min.setMinimumWidth(60)
        self.dest_min.setMaximumWidth(60)
        self.dest_min.setMinimumHeight(20)
        self.dest_min.setMaximumHeight(20)
        self.dest_min.move(150, 305)  # +30

        self.destination_max_label = QLabel("dest max:", self)
        self.destination_max_label.move(5, 330)  # +30

        self.dest_max = QLineEdit(self)
        self.dest_max.setText("10")
        self.dest_max.setMinimumWidth(60)
        self.dest_max.setMaximumWidth(60)
        self.dest_max.setMinimumHeight(20)
        self.dest_max.setMaximumHeight(20)
        self.dest_max.move(150, 335)  # +30

        self.generate_graph_button = QPushButton("Generate graph!", self)
        self.generate_graph_button.setMinimumWidth(170)
        self.generate_graph_button.move(25, 365)

        self.start_evolution_button = QPushButton("Start evolution!", self)
        self.start_evolution_button.setMinimumWidth(170)
        self.start_evolution_button.move(25, 395)

        self.start_evolution_button.clicked.connect(self.start_evolution)
        self.generate_graph_button.clicked.connect(self.generate_graph)
        #self.get_list_of_possibly_airports() #TODO to have full list of airports in QComboBox

    def generate_graph(self):
        self.params = {
            'graph': None,
            'start_idx': int(self.start_airport.text()),
            'end_idx': int(self.destination_airport.text()),
            'max_flights': int(self.max_flights.text()),
            'cost_weight': int(self.cost_weight.text()),
            'time_weight': int(self.time_weight.text()),
            'pop_size': int(self.pop_size.text()),
            'generations': int(self.generation.text()),
            'mutation_rate': float(self.mutation_rate.text()),
            'tournament_size': int(self.tournament_size.text()),
            'elitism': bool(self.elitism.currentText()),
            'dest_min': int(self.dest_min.text()),
            'dest_max': int(self.dest_max.text()),
            'max_flights': 4,
        }
        data = DataGenerator()
        DataGenerator.DESTINATIONS_MIN = self.params['dest_min']
        DataGenerator.DESTINATIONS_MAX = self.params['dest_max']

        # if input_graph_file is not None:
        #     data.load_saved_graph(input_graph_file)
        #
        # else:
        #TODO ilosc lotnisk
        data.load_new_data(10)
        data.create_graph()

        # if graph_save_file is not None:
        #     data.save_graph(graph_save_file)

        testsuite_airports = data.get_airports()
        testsuite_graph = data.get_graph()

        self.graph = GraphManager(self.params['max_flights'])
        self.graph.set_graph(testsuite_graph, testsuite_airports)

        airports_parser = Testsuite_airports_parser(testsuite_airports)

    def start_evolution(self):
        import pprint
        self.params = {
            'graph': self.graph,
            'start_idx': int(self.start_airport.text()),
            'end_idx': int(self.destination_airport.text()),
            'max_flights': int(self.max_flights.text()),
            'cost_weight': int(self.cost_weight.text()),
            'time_weight': int(self.time_weight.text()),
            'pop_size': int(self.pop_size.text()),
            'generations': int(self.generation.text()),
            'mutation_rate': float(self.mutation_rate.text()),
            'tournament_size': int(self.tournament_size.text()),
            'elitism': bool(self.elitism.currentText()),
            'dest_min': int(self.dest_min.text()),
            'dest_max': int(self.dest_max.text()),
        }
        # pprint.pprint(params)
        self.output_of_algorithm = sys.__stdout__
        GA.run_with_params(self.params)
        self.newwindow()

    def newwindow(self):
        import pprint
        print("##############")
        pprint.pprint(self.output_of_algorithm)
        print("##############")
        self.wid = QWidget()
        self.wid.resize(250, 150)
        self.wid.setWindowTitle('NewWindow')
        self.result = QTextEdit(self.wid)
        self.result.setText(str(self.output_of_algorithm))
        #self.start_airport.addItems(self.airports)
        self.result.setMinimumHeight(200)
        self.result.setMaximumHeight(200)
        self.result.setMinimumWidth(600)
        self.start_airport.setMaximumWidth(600)
        # self.start_airport.move(150, 5)
        self.output_of_algorithm = None
        self.wid.show()
Exemple #49
0
class ControlLayout(QWidget):
    """Widget that stores the controls"""
    def __init__(self):
        QWidget.__init__(self)

        self.layout = QVBoxLayout()

        self.form_layout = QFormLayout()

        # The products that we want to make available
        self.products = ['Producto A']

        # Create and fill the combo box to choose the product
        self.product = QComboBox(self)
        self.product.addItems(self.products)

        # Add it to the form layout with a label
        self.form_layout.addRow('Producto:', self.product)

        # Add policies label and combobox
        self.policies = ['Qs', 'Ss', 'RS', 'RSs']
        self.policy = QComboBox(self)
        self.policy.addItems(self.policies)
        self.form_layout.addRow('Politica', self.policy)

        # Connect policy button to hide 3rd parameter
        self.policy.activated.connect(self.changed_policy)

        # Add Parameters
        self.parameters = QLabel('', self)
        self.form_layout.addRow("&Parametros", self.parameters)

        # Parameter 1
        self.p1 = QLineEdit(self, QWidget)
        self.p1_label = QLabel("Q")

        self.pam1_box = QHBoxLayout()
        self.pam1_box.addWidget(self.p1_label)
        self.pam1_box.addStretch(1)
        self.pam1_box.addWidget(self.p1)

        self.form_layout.addRow(self.pam1_box)

        # Parameter 2
        self.p2 = QLineEdit(self, QWidget)
        self.p2_label = QLabel("s")

        self.pam2_box = QHBoxLayout()
        self.pam2_box.addWidget(self.p2_label)
        self.pam2_box.addStretch(1)
        self.pam2_box.addWidget(self.p2)

        self.form_layout.addRow(self.pam2_box)

        # Parameter 3
        self.p3 = QLineEdit(self, QWidget)
        self.p3.hide()
        self.p3_label = QLabel("")

        self.pam3_box = QHBoxLayout()
        self.pam3_box.addWidget(self.p3_label)
        self.pam3_box.addStretch(1)
        self.pam3_box.addWidget(self.p3)

        self.form_layout.addRow(self.pam3_box)

        # Add Periods
        self.periods = QLineEdit(self, QWidget)
        self.periods_label = QLabel("Periodos")

        self.periods_box = QHBoxLayout()
        self.periods_box.addWidget(self.periods_label)
        self.periods_box.addStretch(1)
        self.periods_box.addWidget(self.periods)

        self.form_layout.addRow(self.periods_box)

        # Add form layout to main layout
        self.layout.addLayout(self.form_layout)

        # Add stretch to separate the form layout from the button
        self.layout.addStretch(1)

        # Create a horizontal box layout to hold the button
        self.button_box = QHBoxLayout()

        # Add stretch to push the button to the far right
        #self.button_box.addStretch(1)

        # Create the sim button with its caption
        self.sim_button = QPushButton('Simular', self)

        # Add it to the button box
        self.button_box.addWidget(self.sim_button)

        # Add the button box to the bottom of the main VBox layout
        self.layout.addLayout(self.button_box)

        self.setLayout(self.layout)

    def changed_policy(self):
        """Changes labels if the policy is changed"""
        pol = self.policy.currentText()
        if pol in ['Qs', 'Ss', 'RS']:
            self.p3_label.setText('')
            self.p3.hide()
            if pol == 'Qs':
                self.p1_label.setText('Q')
                self.p2_label.setText('s')
            elif pol == 'Ss':
                self.p1_label.setText('S')
                self.p2_label.setText('s')
            elif pol == 'RS':
                self.p1_label.setText('R')
                self.p2_label.setText('S')
        elif pol == 'RSs':
            self.p1_label.setText('R')
            self.p2_label.setText('S')
            self.p3_label.setText('s')
            self.p3.show()
    def initUI(self):
        grp = QGroupBox('Material')
        grplay = QGridLayout()

        name = QLineEdit()
        name.setText(self.mat.name)
        self.controls['name'] = name

        tex0 = QLineEdit()
        tex0.setText(self.mat.tex0)
        self.controls['tex0'] = tex0

        tex1 = QLineEdit()
        tex1.setText(self.mat.tex1)
        self.controls['tex1'] = tex1

        tex2 = QLineEdit()
        tex2.setText(self.mat.tex2)
        self.controls['tex2'] = tex2

        tex3 = QLineEdit()
        tex3.setText(self.mat.tex3)
        self.controls['tex3'] = tex3

        flags = QGroupBox('Flags')
        fllay = QGridLayout()

        for ind, flag in enumerate(self.mat.flags):
            fllay.addWidget(QLabel(self.pretty_flags[flag[0]]), ind, 0)
            box = QCheckBox()
            fllay.addWidget(box, ind, 1)
            if flag[1]:
                box.toggle()
            self.controls[flag[0]] = box

        fllay.addWidget(QLabel('<b>RenderType</b>'), 8, 0)
        numbox = QComboBox()
        numbox.addItems(self.render_types)
        numbox.setCurrentIndex(self.mat.render_type)
        fllay.addWidget(numbox)
        self.controls['render_type'] = numbox

        fllay.addWidget(QLabel('<b>Data0</b>'), 9, 0)
        d0 = QSpinBox()
        d0.setValue(self.mat.data0)
        d0.setMinimum(0)
        d0.setMaximum(255)
        fllay.addWidget(d0)
        self.controls['data0'] = d0

        fllay.addWidget(QLabel('<b>Data1</b>'), 10, 0)
        d1 = QSpinBox()
        d1.setValue(self.mat.data1)
        d1.setMinimum(0)
        d1.setMaximum(255)
        fllay.addWidget(d1)
        self.controls['data1'] = d1

        flags.setLayout(fllay)

        colors = QGroupBox('Colors')
        collay = QGridLayout()

        self.add_color('<b>Diffuse</b>', self.mat.diff_color, collay, 3)
        self.add_color('<b>Specular</b>', self.mat.spec_color, collay, 4)
        self.add_color('<b>Ambient</b>', self.mat.ambt_color, collay, 5)

        colors.setLayout(collay)

        grplay.addWidget(QLabel('<b>Name</b>'), 0, 0)
        grplay.addWidget(name, 0, 1)

        grplay.addWidget(QLabel('<b>Texture0</b>'), 1, 0)
        grplay.addWidget(tex0, 1, 1)
        grplay.addWidget(QLabel('<b>Texture1</b>'), 1, 2)
        grplay.addWidget(tex1, 1, 3)

        grplay.addWidget(QLabel('<b>Texture2</b>'), 2, 0)
        grplay.addWidget(tex2, 2, 1)
        grplay.addWidget(QLabel('<b>Texture3</b>'), 2, 2)
        grplay.addWidget(tex3, 2, 3)

        grplay.addWidget(QLabel('<b>Gloss</b>'), 3, 0)
        gloss = QDoubleSpinBox()
        gloss.setValue(self.mat.gloss)
        grplay.addWidget(gloss, 3, 1)
        self.controls['gloss'] = gloss

        grplay.addWidget(colors, 4, 0, 1, 5)
        grplay.addWidget(flags, 5, 0, 1, 3)

        grp.setLayout(grplay)

        btns = QHBoxLayout()

        save = QPushButton('Save')
        save.clicked.connect(self.save)
        cancel = QPushButton('Cancel')
        cancel.clicked.connect(self.close)

        btns.addStretch()
        btns.addWidget(save)
        btns.addWidget(cancel)

        mainlay = QVBoxLayout()
        mainlay.addWidget(grp)
        mainlay.addLayout(btns)

        self.setLayout(mainlay)
        self.setGeometry(340, 340, 440, 200)
        self.setWindowTitle('MSH Suite - {0}'.format(self.mat.name))
        self.show()
    def initUI(self):
        grp = QGroupBox('Model')
        grplay = QGridLayout()

        name = QLineEdit()
        name.setText(self.mdl.name)
        name.textChanged.connect(self.name_changed)
        self.controls['name'] = name

        grplay.addWidget(QLabel('Name'), 0, 0)
        grplay.addWidget(name, 0, 1)

        parent = QLineEdit()
        parent.setText(self.mdl.parent_name)
        self.controls['parent'] = parent

        grplay.addWidget(QLabel('Parent'), 0, 2)
        grplay.addWidget(parent, 0, 3)

        type_ = QComboBox()
        type_.addItems(self.types)
        type_.setCurrentIndex(self.types2[self.mdl.model_type])
        self.controls['type'] = type_

        grplay.addWidget(QLabel('Type'), 1, 0)
        grplay.addWidget(type_, 1, 1)

        vis = QCheckBox()
        if self.mdl.vis:
            vis.toggle()
        self.controls['vis'] = vis

        grplay.addWidget(QLabel('Hidden'), 1, 2)
        grplay.addWidget(vis, 1, 3)

        buttonlay = QHBoxLayout()

        collprim = QPushButton('Collision Primitive')
        buttonlay.addWidget(collprim)
        collprim.clicked.connect(self.edit_collprim)

        deformers = QPushButton('Deformers')
        deformers.clicked.connect(self.edit_deformers)
        buttonlay.addWidget(deformers)

        bbox_btn = QPushButton('Bounding Box')
        bbox_btn.clicked.connect(self.edit_bbox)

        trans = QPushButton('Transform')
        trans.clicked.connect(self.edit_tran)

        buttonlay.addWidget(bbox_btn)
        buttonlay.addWidget(trans)

        buttonlay2 = QHBoxLayout()

        validate = QPushButton('Validate')
        validate.clicked.connect(self.validate)

        uvs = QPushButton('UVs')
        uvs.clicked.connect(self.show_uvs)

        buttonlay2.addWidget(validate)
        buttonlay2.addWidget(uvs)
        buttonlay2.addStretch()

        grplay.addLayout(buttonlay, 2, 0, 1, 4)
        grplay.addLayout(buttonlay2, 3, 0, 1, 4)
        grp.setLayout(grplay)

        geogrp = QGroupBox('Geometry')
        geolay = QHBoxLayout()

        self.geometries = QListWidget()
        self.geometries.addItems(['{0} - {1}'.format(ind, geo.classname) for ind, geo in enumerate(self.mdl.segments)])

        geolay.addStretch()
        geolay.addWidget(self.geometries)

        edit_geo = QPushButton('Edit')
        edit_geo.clicked.connect(self.edit_geo)

        geolay.addWidget(edit_geo)

        geogrp.setLayout(geolay)

        btns = QHBoxLayout()

        save = QPushButton('Save')
        save.clicked.connect(self.save)
        cancel = QPushButton('Cancel')
        cancel.clicked.connect(self.close)
        self.status = QLabel('Model Edit Mode')

        btns.addWidget(self.status)
        btns.addStretch()
        btns.addWidget(save)
        btns.addWidget(cancel)

        mainlay = QVBoxLayout()
        mainlay.addWidget(grp)
        mainlay.addWidget(geogrp)
        mainlay.addLayout(btns)

        self.setLayout(mainlay)
        self.setGeometry(340, 340, 400, 200)
        self.setWindowTitle('MSH Suite - {0}'.format(self.mdl.name))
        self.show()
Exemple #52
0
class NewWindow(QWidget):
    def __init__(self, app=None):
        super(NewWindow, self).__init__()
        self.app = app
        glo = QVBoxLayout(self)
        icp = r_path(solve_path('static/images/favicon.png'))
        # need to used objective message boxs instead of functions to set font
        self.Arial = QFont("", 12, QFont.Bold)
        self.Arials = QFont("", 10, QFont.Bold)
        # Language support variable 
        self.Language = 'en'
        self.Runningo = False
        icon = QIcon(icp)
        self.SelfIinit(icon)
        self.center()
        self.langsList(glo)
        self.set_Abutton(icp, glo)
        self.Lists(glo)
        self.Flabel(glo)
        self.set_button(glo)
        self.setLayout(glo)
        mip = self.slchange()
        self.P = rwser(mip[1].split(',')[1], mip[0], self.app)
        self.activateWindow()
        self.show()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def get_ips(self):
        il = []
        for i in interfaces():
            try:
                if os.name != 'nt':
                    inf = i + " ,"
                else:
                    inf = ' ,'
                inf += ifaddresses(i)[2][0].get('addr')
                il.append(inf)
            except:
                pass
        return il
Exemple #53
0
    def createLayout(self):
        self.GridGroupBox = QGroupBox("ESD tranisent control")
        l1 = QLabel("HOST PORT")

        h1 = QHBoxLayout()

        a3host = QLineEdit('127.0.0.1')
        a3col = QLabel(':')
        a3port = QLineEdit('22222')
        h1.addWidget(a3host)
        h1.addWidget(a3col)
        h1.addWidget(a3port)

        l3 = QLabel("COM port")

        hbb = QHBoxLayout()
        comport = QComboBox()
        #comport.addItem('COM1')
        comport.addItems(['COM1', 'COM2', 'COM3', 'COM4', 'COM5'])
        l4 = QLabel("Baue rate")
        comBaud = QComboBox()
        comBaud.addItems(['9600'])
        hbb.addWidget(comport)
        hbb.addWidget(l4)
        hbb.addWidget(comBaud)

        l4 = QLabel("Profile CSV")
        self.prof = QLineEdit()
        hb = QHBoxLayout()
        btnSel = QPushButton("Select")
        btnSel.clicked.connect(self.openFileNameDialog)
        hb.addWidget(self.prof)
        hb.addWidget(btnSel)

        l5 = QLabel("INCA Label")
        self.label = QLineEdit("PhyMod_trq2qBas_MAP")
        self.labelType = QComboBox()
        l6 = QLabel("Type")
        self.labelType.addItems([r'MAP/CURVE', 'Single'])
        h2 = QHBoxLayout()
        h2.addWidget(self.label)
        h2.addWidget(l6)
        h2.addWidget(self.labelType)

        fbox = QFormLayout()
        fbox.addRow(l1, h1)
        fbox.addRow(l3, hbb)
        fbox.addRow(l4, hb)
        fbox.addRow(l5, h2)
        hbox = QHBoxLayout()

        init = QPushButton("Init")
        HeatBeat = QPushButton("Heart beat")
        run = QPushButton("Run")
        stop = QPushButton("Stop")
        hbox.addWidget(init)
        hbox.addWidget(stop)
        hbox.addWidget(run)
        hbox.addWidget(HeatBeat)
        fbox.addRow(QLabel("control"), hbox)

        self.GridGroupBox.setLayout(fbox)
Exemple #54
0
class ExportOrthoWin(QDialog
                     ):  #новый класс как приложение с интерфейсом и кодом
    def __init__(self, parent):
        #_____________Пременные уровня класса___________
        self.OUT_dir = ''  #выходная дирректория
        self.orthoBounds = []
        # ВЫХОДНАЯ ПРОЕКЦИЯ по умолчанию
        #out_crs='PROJCS["WGS 84 / UTM zone 37N",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9102"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator",AUTHORITY["EPSG","9807"]],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",39],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32637"]]'
        self.out_crs = PhotoScan.CoordinateSystem(
            'PROJCS["WGS 84 / UTM zone 37N",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9102"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator",AUTHORITY["EPSG","9807"]],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",39],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32637"]]'
        )
        #out_crs=PhotoScan.CoordinateSystem('PROJCS["WGS 84 / UTM zone 38N",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9102"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator",AUTHORITY["EPSG","9807"]],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",45],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32638"]]')
        self.crsShapes = PhotoScan.CoordinateSystem(
            'PROJCS["WGS 84 / UTM zone 37N",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9102"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator",AUTHORITY["EPSG","9807"]],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",39],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32637"]]'
        )
        self.DATA_OK = 0
        #print ('orthoBounds=',len(self.orthoBounds))
        #формат массива:0-имя ортофото, 1-Xmin, 2-Ymin, 3-sizeX, 4-sizeY, 5-ID полигона
        #__________________________________________________

        QDialog.__init__(self, parent)
        self.setWindowTitle("Экспорт Орто по разграфке")  #Заголвок окна
        self.resize(500, 250)  #размер окна
        self.txt_comment = QLabel(
            "	Модуль экспортирует ортофото и DEM из фотоскана по нарезке. \
Нарезка в текстовом файле: название листа, координаты нижнего левого угла, размеры. \n	Проекция нарезки должна совпадать с проекцией выходного ортофотоплана.\
Листы делятся по нарезке, а внутри нарезки по блокам, размеры задаются. ФОРМАТ JPG \n	При импорте SHP должно быть текстовое поле NAME \n \
Адрес сервера: " + ServerIP +
            " меняем в теле программы. Ваша версия фотоскана: " + PH_version +
            " \n")
        self.txt_comment.setWordWrap(True)
        self.now_prj = QLabel(str(self.out_crs))
        self.select_prj = QPushButton("Выберете проекцию")  #(" открыть ")
        self.select_prj.setFixedSize(170, 26)

        self.TXT_dif_pix = QLabel("<B>Размер пикселя: </B>")
        self.TXT_dif_pix.setFixedSize(170, 26)
        self.dif_pix = QLineEdit()
        self.dif_pix.setText('0.1')  # Задает размер пикселя по умолчанию
        self.dif_pix.setFixedSize(100, 26)

        items_bloksize = ('5000', '8192', '10000', '15000', '20000', '25000',
                          '29999', 'Full')  # список с размерами тайлов
        #items_bloksize = {5000:5000, 8192:8192, 10000:10000, 15000:15000, 20000:20000, 25000:25000, 29999:29999}
        self.TXT_block_size = QLabel("<B>Размер блока: </B>", )
        self.TXT_block_size.setFixedSize(170, 26)
        self.block_size = QComboBox()
        self.block_size.setFixedSize(100, 26)
        self.block_size.addItems(items_bloksize)
        self.block_size.setCurrentIndex(
            1)  #Устанавливает по умолчанию второе значение из списка - 8192

        self.TXT_SHPname = QLabel("Файл разграфки SHP (NAME,poligons)")
        self.SHPname = QPushButton(
            "Выберете файл разграфки SHP")  #(" открыть ")
        self.SHPname.setFixedSize(170, 26)

        self.TXT_filename = QLabel(
            "Файл разграфки TXT(имя; X0; Y0; sizeX; SizeY)")
        self.filename = QPushButton("Выберете Файл разграфки")  #(" открыть ")
        self.filename.setFixedSize(170, 26)

        self.TXT_CheckOrthoDem = QLabel("Вид выходной продукции")
        self.TXT_CheckOrthoDem.setFixedSize(170, 26)
        self.CheckOrtho_Radio = QRadioButton("Ортофото")
        self.CheckOrtho_Radio.setChecked(True)
        self.CheckDem_Radio = QRadioButton("ДЕМ")

        self.TXT_OUTFOLDER = QLabel("Выходная дирректория")
        self.OUTFOLDER = QPushButton("Выберете дирректорию")  #(" открыть ")
        self.OUTFOLDER.setFixedSize(170, 26)

        items_format = (
            'JPG', 'TIF'
        )  # список форматов, ПРИ выборе ДЕМ будет выбран второй формат - внимательно при изменении списка!!!
        self.file_format = QComboBox()
        self.file_format.setFixedSize(50, 26)
        self.file_format.addItems(items_format)
        self.file_format.setCurrentIndex(
            0)  #Устанавливает по умолчанию первое значение

        self.TXT_checkExportOrtho = QLabel("Построить ортофото:")  # Ортофото
        self.TXT_checkExportOrtho.setFixedSize(170, 26)
        self.checkExportOrtho = QCheckBox()
        self.checkExportOrtho.setChecked(False)

        self.GoGo = QPushButton("Экспорт локально")  #(" Экспорт локально ")
        self.GoGo.setFixedSize(170, 26)
        self.GoGo.setDisabled(True)

        self.GoGoNet = QPushButton("Экспорт по сети")  #(" Экспорт по сети ")
        self.GoGoNet.setFixedSize(170, 26)
        self.GoGoNet.setDisabled(True)

        hbox0 = QHBoxLayout()
        hbox0.addWidget(self.txt_comment, alignment=0)

        hbox1 = QHBoxLayout()
        hbox1.addWidget(self.select_prj, alignment=0)
        hbox1.addWidget(self.now_prj, alignment=0)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.TXT_block_size, alignment=1)
        hbox2.addWidget(self.block_size, alignment=1)

        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.TXT_dif_pix, alignment=1)
        hbox3.addWidget(self.dif_pix, alignment=1)

        hbox4 = QHBoxLayout()
        #hbox4.addStretch(1)
        hbox4.addWidget(self.SHPname, alignment=0)
        hbox4.addWidget(self.TXT_SHPname, alignment=0)

        hbox5 = QHBoxLayout()
        #hbox5.addStretch(1)
        hbox5.addWidget(self.filename, alignment=0)
        hbox5.addWidget(self.TXT_filename, alignment=0)

        hbox51 = QHBoxLayout()
        hbox51.addWidget(self.TXT_CheckOrthoDem, alignment=0)
        hbox51.addWidget(self.CheckOrtho_Radio, alignment=0)
        hbox51.addWidget(self.CheckDem_Radio, alignment=0)

        hbox6 = QHBoxLayout()
        #hbox5.addStretch(1)
        hbox6.addWidget(self.OUTFOLDER, alignment=0)
        hbox6.addWidget(self.TXT_OUTFOLDER, alignment=0)
        hbox6.addWidget(self.file_format, alignment=0)

        hbox7 = QHBoxLayout()  #build ortho
        hbox7.addWidget(self.TXT_checkExportOrtho, alignment=0)
        hbox7.addWidget(self.checkExportOrtho, alignment=0)

        hbox8 = QHBoxLayout()
        hbox8.addWidget(self.GoGo, stretch=0, alignment=0)
        hbox8.addWidget(self.GoGoNet, stretch=0, alignment=0)

        vbox = QVBoxLayout()  #Определяем вбокс и забиваем его Нбоксами
        #vbox.addStretch(1)
        vbox.addLayout(hbox0)
        vbox.addLayout(hbox1)
        vbox.addLayout(hbox2)
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)
        vbox.addLayout(hbox5)
        vbox.addLayout(hbox51)  #выбор, что строить орто или дем
        vbox.addLayout(hbox6)
        #Функция построения ортофото спрятана, поскольку работает не стабильно и построение ортофото для каждого листа в сумме занимает очень много времени,
        #гораздо больше, чем один раз построить ортофото для всех
        #vbox.addLayout(hbox7) #build ortho
        vbox.addLayout(hbox8)

        self.setLayout(vbox)

        self.select_prj.clicked.connect(self.set_projection)
        self.SHPname.clicked.connect(self.input_razgr_SHPname)
        self.filename.clicked.connect(self.input_razgr_name)
        self.OUTFOLDER.clicked.connect(self.input_out_dir)
        self.GoGo.clicked.connect(self.ortho_local)
        self.GoGoNet.clicked.connect(self.ortho_net)
        #Организация блокировки интерфейса для радио кнопок
        self.CheckOrtho_Radio.clicked.connect(self.CheckOrtho_Radio_DO)
        self.CheckDem_Radio.clicked.connect(self.CheckDem_Radio_DO)
        #____________
        self.checkExportOrtho.clicked.connect(
            self.PrintChkStat)  #Функция для проверки работы чека
        #self.WindowContextHelpButtonHint.clicked.connect(self.prog_hint)
        #self.WindowTitleHint.clicked.connect(self.prog_hint)

        self.exec()
        #____________________________________________________________________________

    def PrintChkStat(
        self
    ):  #Эта функция работает в принте с подстановкой и получение значения чека
        if self.checkExportOrtho.isChecked() == True:
            stat = 'ДА'
        else:
            stat = 'НЕТ'
        print('Строить орто %s здесь' % stat)

    def CheckOrtho_Radio_DO(
            self):  #Если выбран Ортоф - формат Джипег и свободен!!!
        print("Орто")
        self.file_format.setCurrentIndex(0)
        self.file_format.setDisabled(False)

    def CheckDem_Radio_DO(
            self):  #Если выбран ДЕМ - формат тифф и блокируется!!!
        print("DEM")
        self.file_format.setCurrentIndex(1)
        self.file_format.setDisabled(True)

    def ortho_local(self):
        self.export_ortho('local')

    def ortho_net(self):
        self.export_ortho('net')

    def prog_hint(self):
        print("OK")

    def unlock_export(self, sel):
        #Переменная нужна для разблокирования кнопки Экспорт. Два критических параметра:Файл разграфки и выходная дирректория, каждый добавляет по еденице.
        #Sel=5 блокирует кнопки при запуске сетевой обработки
        '''
		DATA_OK логика работы: Для экспорта нужно задать выходную директорию и файл разграфки, текстовый или векторный
		при запуске сетевой обработки кнопки опять блокируются
		DATA_OK меняет только эта процедура!!!
		
		0-ничего не задано экспорт заблокирован
		1-выбран  файл разграфки проверяем выбран ли путь, да, разблокируем 3
		2-выбран путь проверяем выбран ли файл разграфки, да, разблокируем 3
		'''
        if sel == 5 and self.DATA_OK == 1:
            self.DATA_OK = 0
            self.GoGo.setDisabled(True)
            self.GoGoNet.setDisabled(True)
        if sel == 5 and self.DATA_OK == 2:
            self.DATA_OK = 2
            self.GoGo.setDisabled(True)
            self.GoGoNet.setDisabled(True)
        if sel == 5 and self.DATA_OK == 3:
            self.DATA_OK = 2
            self.GoGo.setDisabled(True)
            self.GoGoNet.setDisabled(True)
        if self.DATA_OK == 1 and sel == 2: self.DATA_OK = 3
        if self.DATA_OK == 2 and sel == 1: self.DATA_OK = 3
        if self.DATA_OK == 0 and sel != 5: self.DATA_OK = sel
        if self.DATA_OK == 3 and sel != 5:
            self.GoGo.setDisabled(False)
            self.GoGoNet.setDisabled(False)
            print('unlock')
        print(sel, self.DATA_OK)

    def OrthoBoundCalc(self, Xn, Yn, XS,
                       YS):  # изменить под сетевую обработку с тайлами
        DifPix = float(self.dif_pix.text())
        ''' Округление начала Если надо
		Xnround=floor(Xn/DifPix)*DifPix #
		Ynround=floor(Yn/DifPix)*DifPix
		'''
        '''
		if self.block_size.currentText()=='Full' or CommandStack==5 : #Экспорт целикового фрагмента
			print('границы целиковые')
			Xnround=Xn
			Ynround=Yn-DifPix
			XSround=ceil(XS/DifPix+1)*DifPix #Границы округляем в большую сторону и расширяем на пиксель
			YSround=ceil(YS/DifPix+1)*DifPix
			XSround=Xnround+XSround
			YSround=Ynround+YSround
			
		elif CommandStack==1 and self.block_size.currentText()!='Full': # Экспорт по тайлам
			print("Границы со сдвигом")
			BlockSize=float(self.block_size.currentText())
			Xnround=Xn
			Ynround=Yn #-DifPix
			XSround=ceil(XS/DifPix+1)*DifPix #Границы округляем в большую сторону и расширяем на пиксель
			YSround=ceil(YS/DifPix+1)*DifPix
			YBlockSize=BlockSize*DifPix 
			TileShift=YBlockSize-YSround
			Ynround=Ynround+TileShift
			XSround=Xnround+XSround
			YSround=Ynround+YSround+TileShift
		else:
			Print("Bound version error, OrthoBoundCalc")
			pass
			'''
        Xnround = Xn
        Ynround = Yn - DifPix
        XSround = ceil(
            XS / DifPix + 1
        ) * DifPix  #Границы округляем в большую сторону и расширяем на пиксель
        YSround = ceil(YS / DifPix + 1) * DifPix
        XSround = Xnround + XSround
        YSround = Ynround + YSround
        point = [
        ]  #"Эта конструкция нужна для поиска максимальных координат квадрата при переходе из системы в систему
        print("точки")
        point.append(PhotoScan.Vector((Xnround, Ynround)))
        point.append(PhotoScan.Vector((Xnround, YSround)))
        point.append(PhotoScan.Vector((XSround, YSround)))
        point.append(PhotoScan.Vector((XSround, Ynround)))
        print("точки2")
        point_trans = []
        point_trans.append(
            PhotoScan.CoordinateSystem.transform(point[0], self.crsShapes,
                                                 self.out_crs))
        point_trans.append(
            PhotoScan.CoordinateSystem.transform(point[1], self.crsShapes,
                                                 self.out_crs))
        point_trans.append(
            PhotoScan.CoordinateSystem.transform(point[2], self.crsShapes,
                                                 self.out_crs))
        point_trans.append(
            PhotoScan.CoordinateSystem.transform(point[3], self.crsShapes,
                                                 self.out_crs))
        x = []
        y = []
        for i in range(4):
            print(i)
            x.append(point_trans[i][0])
            y.append(point_trans[i][1])
        xMin = min(x)
        yMin = min(y)
        xMax = max(x)
        yMax = max(y)
        #OrthoBound=(Xnround,Ynround,XSround,YSround)
        OrthoBound = (Xnround, Ynround, XSround, YSround)
        print(OrthoBound)
        OrthoBound = (xMin, yMin, xMax, yMax)
        print(OrthoBound)
        return OrthoBound

    def input_razgr_SHPname(self):
        #global listShapes
        SHPname = ''  #Векторный файл разграфки
        DataDir = os.path.dirname(
            __file__)  # Дирректория по умолчанию - дирректория скрипта!!
        shpfilename = QFileDialog.getOpenFileName(
            self, 'выберете векторный файл разграфки', DataDir,
            filter='*.shp')  #Координаты в выходной проекции
        #проверка  на пустоту
        if not shpfilename[0] == '':
            SHP_name = shpfilename[0]
        else:
            return
        sname = os.path.basename(SHP_name)
        file_sname = os.path.splitext(sname)[0]

        print('Путь до шейпа: ', SHP_name)
        print('Имя шейпа: ', file_sname)
        chunk.importShapes(SHP_name, True)  # Импорт шейпфайла с заменой
        shapes = chunk.shapes
        #Сделать проверку на ИМЯ ПОЛИГОНА
        #shapes=PhotoScan.app.document.chunk.shapes
        listShapes = shapes.items()  #Массив (список) шейпов в проекте
        self.crsShapes = shapes.crs  #Проекция шейпа
        print(self.crsShapes)
        PhotoScan.app.messageBox('Импортированы объекты: ' + str(shapes) +
                                 '\n Старые объекты удалены')

        #Получили список векторных объектов, загруженных в проект, теперь проходим по каждому объекту и определяем его минимум и максимум по коориднатам

        if len(listShapes) != 0:
            poligon_ID = 0
            self.orthoBounds = []
            for shape in listShapes:  # ЗДЕСЬ определяются координаты минимум и максимум в текущей проекции в другой все по другому - Могут быть дыры
                # в OrthoBoundCalc стоит заглушка - имщет максимальные коориднаты углов прямоугольника после перепроецирования - можно но не совсем корректно
                x = []
                y = []
                vertices = shape.vertices
                for vertex in vertices:
                    x.append(vertex[0])
                    y.append(vertex[1])

                # Если есть NAME - это будет имя, если нет - имя шейпа и номер фичи
                if str(shape.label) == '':
                    poligonName = str(file_sname) + '_' + str(poligon_ID)
                else:
                    poligonName = str(shape.label)
                xMin = min(x)
                yMin = min(y)
                xSize = max(x) - min(x)
                ySize = max(y) - min(y)
                element = [poligonName, xMin, yMin, xSize, ySize, poligon_ID]
                self.orthoBounds.append(
                    element)  #ЭТО МАССИВ с ГРАНИЦАМИ ОРТОФОТО
                #формат массива:0-имя ортофото, 1-Xmin, 2-Ymin, 3-sizeX, 4-sizeY
                poligon_ID += 1  #Увеличение на единицу
            print(len(self.orthoBounds), poligon_ID)
            if len(self.orthoBounds) != 0: self.unlock_export(1)
            self.TXT_SHPname.setText(str(sname))
            self.TXT_filename.setText(
                "Файл разграфки TXT(имя; X0; Y0; sizeX; SizeY)")
        else:
            PhotoScan.app.messageBox('Пустой SHP файл')
            self.unlock_export(5)
        print('orthoBounds=', len(self.orthoBounds))
        # Шейп засосали,  минимум максимум нашли, с обрезкой дальше разберемся
        #_____________________________________________________________________________

    def input_razgr_name(self):
        TXT_name = ''  #имя файла с разграфкой
        # КООРДИАНТЫ ДОЛЖНЫ БЫТЬ В ВЫХОДНОЙ ПРОЕКЦИИ!!!!!
        DataDir = os.path.dirname(
            __file__)  # Дирректория по умолчанию - дирректория скрипта!!
        textfilename = QFileDialog.getOpenFileName(
            self, 'выберете  файл разграфки', DataDir,
            filter='*.txt')  #Координаты в выходной проекции
        #проверка текстфайлнайм на пустоту
        if not textfilename[0] == '':
            with open(textfilename[0]) as f:
                for line in f:
                    znach = line.split(";")
                    try:
                        if not (isinstance(znach[0], str)):
                            PhotoScan.app.messageBox('Неверный форматS')
                            self.unlock_export(5)
                            return
                        if not (isinstance(float(znach[1]), (float, int))):
                            PhotoScan.app.messageBox('Неверный формат1i')
                            self.unlock_export(5)
                            return
                        if not (isinstance(float(znach[2]), (float, int))):
                            PhotoScan.app.messageBox('Неверный формат2i')
                            self.unlock_export(5)
                            return
                        if not (isinstance(float(znach[3]), (float, int))):
                            PhotoScan.app.messageBox('Неверный формат3i')
                            self.unlock_export(5)
                            return
                        if not (isinstance(float(znach[4]), (float, int))):
                            PhotoScan.app.messageBox('Неверный формат4i')
                            self.unlock_export(5)
                            return
                    except:
                        PhotoScan.app.messageBox('Неверный формат_;')
                        self.unlock_export(5)
                        return
        else:
            return
        if not (textfilename[0]
                == ''):  #Если все нормально заполняем orthoBounds
            TXT_name = textfilename
            self.orthoBounds = []
            with open(TXT_name[0]) as f:
                count = 0
                for line in f:
                    znach = line.split(";")
                    element = [
                        znach[0], znach[1], znach[2], znach[3], znach[4], count
                    ]
                    self.orthoBounds.append(
                        element)  #ЭТО МАССИВ с ГРАНИЦАМИ ОРТОФОТО
                    count += 1
            print('orthoBounds=', len(self.orthoBounds))
            self.unlock_export(
                1)  #разблокирует экспорт, если заданы разграфка и дирректория
            self.TXT_filename.setText(str(TXT_name[0]))
            self.TXT_SHPname.setText("Файл разграфки SHP (NAME,poligons)")

    def set_projection(self):
        self.out_crs = PhotoScan.app.getCoordinateSystem(
            'Система координат',
            self.out_crs)  #Специальная форма для задания системы координат
        self.now_prj.setText(str(self.out_crs))

    def input_out_dir(self):
        DataDir = os.path.dirname(__file__)
        outputdir = QFileDialog.getExistingDirectory(self,
                                                     'выберете дирректорию',
                                                     DataDir)
        if not outputdir == '':
            self.OUT_dir = outputdir
            self.TXT_OUTFOLDER.setText(str(self.OUT_dir))
            self.unlock_export(
                2)  #разблокирует экспорт, если заданы разграфка и дирректория
        else:
            return
        print('orthoBounds=', len(self.orthoBounds))

    def export_ortho(
        self, proc_type
    ):  # универсальная процедура экспорта для локлаьной и для сетевой обработки
        #global chunk
        ''' ЭТО ПРОВЕРКА ДЛЯ ПОСТРОЕНИЯ ОРТО ПЕРЕД РАБОТОЙ В ТЕКУЩЕЙ ВЕРСИИ ФУНКЦИЯ ОТКЛЮЧЕНА!!
		if self.checkExportOrtho.isChecked()==True:
			statOrthoBuild=True
		else:
			statOrthoBuild=False
		# 000000 Проверка на наличие ортофото или дем перед работой
		if (doc.chunk.orthomosaic==None and statOrthoBuild==False):
			PhotoScan.app.messageBox('Нет орто!!')
			return
		elif (doc.chunk.elevation==None and statOrthoBuild==True):
			PhotoScan.app.messageBox('Нет ДЕМ!!')
			return
		'''
        #Определение вида экспорта - орто или дем
        if self.CheckOrtho_Radio.isChecked() == True:
            ExportType = 'ORTHO'
        elif self.CheckDem_Radio.isChecked() == True:
            ExportType = 'DEM'
        else:
            AssertionError("Какой процесс экспорта?")

        #ПРОВЕРКИ НАЛИЧИЯ ДЕМ И ОРТО
        if (doc.chunk.orthomosaic == None and ExportType == 'ORTHO'):
            PhotoScan.app.messageBox('Нет орто!!')
            return
        elif (doc.chunk.elevation == None and ExportType == 'DEM'):
            PhotoScan.app.messageBox('Нет ДЕМ!!')
            return

        file_format = self.file_format.currentText()
        print('orthoBounds=', len(self.orthoBounds))
        task = []  #Это СПИСОК тасков
        DifPix = float(self.dif_pix.text())
        if self.block_size.currentText() == 'Full':
            BlockSize = 0
        else:
            BlockSize = int(self.block_size.currentText())

        # Цикл для запуска ортофото локально или для забивания стека на сеть из массива
        try:
            for cu_string in self.orthoBounds:
                OName = cu_string[0]
                XMLeft = float(cu_string[1])
                YMDown = float(cu_string[2])
                sizeXM = float(cu_string[3])
                sizeYM = float(cu_string[4])
                shapeNumber = int(cu_string[5])
                cu_Region = self.OrthoBoundCalc(
                    XMLeft, YMDown, sizeXM, sizeYM
                )  #Функция вычисления границ # изменить под сетевую обработку с тайлами
                if file_format == 'JPG' and ExportType == 'ORTHO':
                    fileoutname = self.OUT_dir + "\\ortho_" + OName + ".jpg"
                elif file_format == 'TIF' and ExportType == 'ORTHO':
                    fileoutname = self.OUT_dir + "\\ortho_" + OName + ".tif"
                elif file_format == 'TIF' and ExportType == 'DEM':
                    fileoutname = self.OUT_dir + "\\dem_" + OName + ".tif"
                else:
                    print("Формат файла?")

                if proc_type == 'local':  #КОММАНДЫ для локальной обработки
                    print('Обработка локально')
                    ''' ПОСТРОЕНИЕ ОРТОФОТО В ЭТОЙ ВЕРСИИ ОТКЛЮЧЕНО
					if statOrthoBuild==True: 
						#chunk.buildOrthomosaic(surface=PhotoScan.ElevationData, blending=PhotoScan.MosaicBlending, color_correction=False, projection=self.out_crs, region=cu_Region,dx=DifPix, dy=DifPix)
						chunk.buildOrthomosaic(surface=PhotoScan.ElevationData, blending=PhotoScan.MosaicBlending, projection=self.out_crs, region=cu_Region,dx=DifPix, dy=DifPix)
					'''

                    if CommandStack == 1 and ExportType == 'ORTHO':
                        if file_format == 'JPG':
                            chunk.exportOrthomosaic(fileoutname,
                                                    format="jpg",
                                                    projection=self.out_crs,
                                                    region=cu_Region,
                                                    dx=DifPix,
                                                    dy=DifPix,
                                                    blockw=BlockSize,
                                                    blockh=BlockSize,
                                                    write_kml=False,
                                                    write_world=True)
                        elif file_format == 'TIF':
                            chunk.exportOrthomosaic(fileoutname,
                                                    format="tif",
                                                    projection=self.out_crs,
                                                    region=cu_Region,
                                                    dx=DifPix,
                                                    dy=DifPix,
                                                    blockw=BlockSize,
                                                    blockh=BlockSize,
                                                    write_kml=False,
                                                    write_world=True,
                                                    tiff_compression="jpeg",
                                                    tiff_big=False)
                            #сжатие LZW
                            #elif file_format=='TIF': chunk.exportOrthomosaic(fileoutname, format="tif", region=cu_Region, projection=self.out_crs,dx=DifPix, dy=DifPix, blockw=BlockSize, blockh=BlockSize, write_kml=False, write_world=True, tiff_compression="lzw", tiff_big=False)
                        else:
                            print("Формат файла?")
                    elif CommandStack == 5 and ExportType == 'ORTHO':
                        if file_format == 'JPG':
                            chunk.exportOrthomosaic(
                                fileoutname,
                                PhotoScan.RasterFormatTiles,
                                PhotoScan.ImageFormatJPEG,
                                region=cu_Region,
                                projection=self.out_crs,
                                dx=DifPix,
                                dy=DifPix,
                                blockw=BlockSize,
                                blockh=BlockSize,
                                write_kml=False,
                                write_world=True)
                        elif file_format == 'TIF':
                            chunk.exportOrthomosaic(
                                fileoutname,
                                PhotoScan.RasterFormatTiles,
                                PhotoScan.ImageFormatTIFF,
                                region=cu_Region,
                                projection=self.out_crs,
                                dx=DifPix,
                                dy=DifPix,
                                blockw=BlockSize,
                                blockh=BlockSize,
                                write_kml=False,
                                write_world=True,
                                tiff_compression=PhotoScan.TiffCompressionJPEG,
                                tiff_big=False)
                            #сжатие LZW
                            #elif file_format=='TIF': chunk.exportOrthomosaic(fileoutname, PhotoScan.RasterFormatTiles,PhotoScan.ImageFormatTIFF, region=cu_Region, projection=self.out_crs,dx=DifPix, dy=DifPix, blockw=BlockSize, blockh=BlockSize, write_kml=False, write_world=True, tiff_compression=PhotoScan.TiffCompressionLZW, tiff_big=False)
                        else:
                            print("Формат файла?")
                    elif CommandStack == 1 and ExportType == 'DEM':
                        print("Экспорт ДЕМ локально")
                        if file_format == 'TIF':
                            chunk.exportDem(fileoutname,
                                            format="tif",
                                            projection=self.out_crs,
                                            region=cu_Region,
                                            dx=DifPix,
                                            dy=DifPix,
                                            blockw=BlockSize,
                                            blockh=BlockSize,
                                            write_kml=False,
                                            write_world=True,
                                            tiff_big=False)
                    elif CommandStack == 5 and ExportType == 'DEM':
                        print("Экспорт ДЕМ локально")
                        if file_format == 'TIF':
                            chunk.exportDem(fileoutname,
                                            PhotoScan.RasterFormatTiles,
                                            PhotoScan.ImageFormatTIFF,
                                            region=cu_Region,
                                            projection=self.out_crs,
                                            dx=DifPix,
                                            dy=DifPix,
                                            blockw=BlockSize,
                                            blockh=BlockSize,
                                            write_kml=False,
                                            write_world=True,
                                            tiff_big=False)

                elif proc_type == 'net':
                    print('Обработка по сети')
                    ''' ПОСТРОЕНИЕ ОРТОФОТО В ЭТОЙ ВЕРСИИ ОТКЛЮЧЕНО
					#Построить ортофото
					if statOrthoBuild==True:
						workBuild = PhotoScan.NetworkTask() # СОздаем ворк и забиваем его параметрами
						#Версионность
						if CommandStack==1:
							workBuild.params['ortho_surface'] = 0
							workBuild.params['resolution_x'] = DifPix
							workBuild.params['resolution_y'] = DifPix
						elif CommandStack==5:
							workBuild.params['ortho_surface'] = 4
							workBuild.params['resolution'] = DifPix
						else:
							return
						workBuild.name = "BuildOrthomosaic"
						workBuild.frames.append((chunk.key,0))
						workBuild.params['network_distribute'] = True
						
						task.append(workBuild) #Добавляем задачу построения в таск
					'''

                    #Экспортировать ортофото
                    workExport = PhotoScan.NetworkTask(
                    )  # СОздаем ворк и забиваем его параметрами
                    #ВЕРСИОННОСТЬ
                    if CommandStack == 1 and ExportType == 'ORTHO':
                        workExport.name = "ExportOrthomosaic"
                        workExport.params['resolution_x'] = DifPix
                        workExport.params['resolution_y'] = DifPix
                        if file_format == 'JPG':
                            workExport.params['raster_format'] = 2
                        elif file_format == 'TIF':
                            workExport.params['raster_format'] = 1
                        else:
                            print("Формат файла?")
                    elif CommandStack == 5 and ExportType == 'ORTHO':
                        workExport.name = "ExportRaster"
                        workExport.params['resolution'] = DifPix
                        if file_format == 'JPG':
                            workExport.params['image_format'] = 1
                        elif file_format == 'TIF':
                            workExport.params[
                                'image_format'] = 2  #Значение на шару!!! ПРОВЕРИТЬ
                        else:
                            print("Формат файла?")
                    elif CommandStack == 1 and ExportType == 'DEM':
                        print("Экспорт ДЕМ по сети")
                        workExport.name = "ExportDem"
                        workExport.params['resolution_x'] = DifPix
                        workExport.params['resolution_y'] = DifPix
                    elif CommandStack == 5 and ExportType == 'DEM':  #НЕ ОТЛАЖЕНО ПАРАМЕТРЫ НА ШАРУ
                        print("Экспорт ДЕМ по сети")
                        workExport.name = "ExportOrthomosaic"
                        workExport.params['resolution'] = DifPix
                        pass
                    else:
                        return

                    workExport.frames.append((chunk.key, 0))
                    workExport.params['write_world'] = 1
                    if self.block_size.currentText(
                    ) == 'Full':  # Условие на запись тайлов
                        workExport.params['write_tiles'] = 0
                    else:
                        workExport.params['write_tiles'] = 1
                    workExport.params['tile_width'] = BlockSize
                    workExport.params['tile_height'] = BlockSize
                    workExport.params[
                        'path'] = fileoutname  #выходная дирректория с именем файла
                    workExport.params['region'] = cu_Region
                    # ВНИМАНИЕ! По сети нельзя экспортировать в пользовательской проекции ИЛИ проекция должна быть НА ВСЕХ НОДАХ
                    workExport.params[
                        'projection'] = self.out_crs.authority  #Из объекта проекция берется только ее номер EPSG::32637
                    #ВНИМАНИЕ ЭКСПОРТ ОТКЛЮЧЕН!!!!
                    task.append(workExport)  #Добавляем задачу в таск
                else:
                    print('Пока не задано')
            PhotoScan.app.messageBox('Обработка закончена')
        except Exception as e:
            print(e)
            PhotoScan.app.messageBox('Что-то пошло не так ((')
            return
            #break
#Запуск сетевого стека, таска в обработку
        if proc_type == 'net':
            print(ProjectLocalPath_auto)
            print(ProjectPath)
            client.connect(ServerIP)
            batch_id = client.createBatch(ProjectPath, task)

            if batch_id == None:  #Проверка наличия проекта в сети
                PhotoScan.app.messageBox(
                    '<B>Этот проект уже запущен в обработку!!!<B>')
                self.unlock_export(5)
            else:
                print('Проект работает под номером ', batch_id)
                client.resumeBatch(batch_id)
                self.unlock_export(5)
                PhotoScan.app.messageBox(
                    'Проект поставлен в очередь сетевой обработки')

            client.disconnect()
            pass
class OptionSection(QWidget):
  """
  Collects options and returns proper representation when requested
  """
  def __init__(self, parent=None):
    super(OptionSection, self).__init__(parent)
    #create widgets
    label_buffer_size = QLabel("Buffer Size")
    self.spinbox_buffer_size = ValidatedSpinBox()
    self.spinbox_buffer_size.setSingleStep(10)
    self.spinbox_buffer_size.setMaximum(9999999)
    self.spinbox_buffer_size.setSuffix(" bytes")
    self.spinbox_buffer_size.setValue(55)
    label_timeout = QLabel("Timeout")
    self.spinbox_timeout = ValidatedSpinBox()
    self.spinbox_timeout.setMaximum(9999999)
    self.spinbox_timeout.setSuffix(" ms")
    self.spinbox_timeout.setSingleStep(100)
    self.spinbox_timeout.setValue(1000)
    label_delay = QLabel("Delay Between Packets")
    self.spinbox_delay = ValidatedSpinBox()
    self.spinbox_delay.setMaximum(9999999)
    self.spinbox_delay.setSuffix(" ms")
    self.spinbox_delay.setSingleStep(100)
    self.spinbox_delay.setValue(1000)
    label_delay_distribution = QLabel("Delay Distribution")
    self.combobox_delay_distribution = QComboBox()
    self.combobox_delay_distribution.addItem("Constant")
    self.combobox_delay_distribution.insertSeparator(10)
    self.combobox_delay_distribution.addItems(["Uniform", "Gaussian", "Poisson", "Exponential"])
    label_packet_count = QLabel("Packets to Send")
    self.spinbox_packet_count = ValidatedSpinBox()
    self.spinbox_packet_count.setMaximum(9999999)
    self.spinbox_packet_count.setValue(3)
    #setup layout
    layout = QFormLayout()
    layout.addRow(label_buffer_size, self.spinbox_buffer_size)
    layout.addRow(label_timeout, self.spinbox_timeout)
    layout.addRow(label_delay, self.spinbox_delay)
    layout.addRow(label_delay_distribution, self.combobox_delay_distribution)
    layout.addRow(label_packet_count, self.spinbox_packet_count)
    self.setLayout(layout)
    
  def getOptions(self):
    """
    Return a RequestData object representing selected options
    """
    buf_size = self.spinbox_buffer_size.value()
    timeout = self.spinbox_timeout.value()
    delay = self.spinbox_delay.value() / 1000
    packet_count = self.spinbox_packet_count.value()
    selected_distribution = self.combobox_delay_distribution.currentIndex()
    if selected_distribution == 0:
      distribution = RequestData.DISTRIBUTION_CONSTANT
    elif selected_distribution == 1:
      distribution = RequestData.DISTRIBUTION_UNIFORM
    elif selected_distribution == 2:
      distribution = RequestData.DISTRIBUTION_GAUSSIAN
    elif selected_distribution == 3:
      distribution = RequestData.DISTRIBUTION_POISSON
    elif selected_distribution == 4:
      distribution = RequestData.DISTRIBUTION_EXPONENTIAL
    
    return RequestData(buf_size, timeout, delay, packet_count, distribution)
  
  def disableWidgets(self):
    for widget in [self.spinbox_buffer_size, self.spinbox_delay,
                   self.spinbox_packet_count, self.spinbox_timeout, 
                   self.combobox_delay_distribution]:
      widget.setEnabled(False)
  
  def enableWidgets(self):
    for widget in [self.spinbox_buffer_size, self.spinbox_delay,
                   self.spinbox_packet_count, self.spinbox_timeout, 
                   self.combobox_delay_distribution]:
      widget.setEnabled(True)
class SelectionOptions(QWidget):
    """Widget for modifying the selected circuit or gate."""

    def __init__(self, view):
        super(SelectionOptions, self).__init__()

        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        self.view = view
        self.view.scene().selectionChanged.connect(self.updateOptions)
        self.gridLayout = QGridLayout(self)

        self.nameLabel = QLabel(self.str_name, self)
        self.gridLayout.addWidget(self.nameLabel, 0, 0, 1, 1)

        self.nameLE = QLineEdit(self)
        self.gridLayout.addWidget(self.nameLE, 0, 1, 1, 2)
        self.nameLE.returnPressed.connect(self.setItemName)

        self.showNameLabel = QLabel(self.str_showName, self)
        self.gridLayout.addWidget(self.showNameLabel, 1, 0, 1, 1)

        self.showNameCB = QCheckBox(self)
        self.gridLayout.addWidget(self.showNameCB, 1, 1, 1, 1)
        self.showNameCB.stateChanged.connect(self.setNameVisibility)

        self.showCategoryLabel = QLabel(self.str_showCategory, self)
        self.gridLayout.addWidget(self.showCategoryLabel, 2, 0, 1, 1)

        self.showCategoryCB = QCheckBox(self)
        self.gridLayout.addWidget(self.showCategoryCB, 2, 1, 1, 1)
        self.showCategoryCB.stateChanged.connect(self.setCategoryVisibility)

        self.nbInputsLabel = QLabel(self.str_nbInputs, self)
        self.gridLayout.addWidget(self.nbInputsLabel, 3, 0, 1, 1)

        self.nbInputsCB = QComboBox(self)
        self.nbInputsCB.activated.connect(self.setNbInputs)
        self.nbInputsCB.addItems([str(x) for x in range(2, 33)])
        self.gridLayout.addWidget(self.nbInputsCB, 3, 1, 1, 2)

        self.orientLabel = QLabel(self.str_orientation, self)
        self.gridLayout.addWidget(self.orientLabel, 4, 0, 1, 1)

        self.cwRotationButton = QPushButton(self)
        self.cwRotationButton.setText("↻")
        self.cwRotationButton.clicked.connect(
            lambda: self.view.rotateItems(90))
        self.gridLayout.addWidget(self.cwRotationButton, 4, 1, 1, 1)

        self.acwRotationButton = QPushButton(self)
        self.acwRotationButton.setText("↺")
        self.acwRotationButton.clicked.connect(
            lambda: self.view.rotateItems(-90))
        self.gridLayout.addWidget(self.acwRotationButton, 4, 2, 1, 1)
        self.updateOptions()

    def updateOptions(self):
        """Hides irrelevant options, and sets reasonable values for the
        visible options.
        """
        selection = self.view.scene().selectedItems()
        for widget in self.findChildren(QWidget):     # Hide all options
            widget.setHidden(True)
        if not len(selection):          # then return if no selection.
            return
        # The number of entries option only applies to gates (except NOT)
        notAllGates = any([i.data.__class__ not in [
            AndGate, NandGate, OrGate, NorGate, XorGate, XnorGate]
            for i in selection])
        self.nbInputsLabel.setHidden(notAllGates)
        self.nbInputsCB.setHidden(notAllGates)
        # Only circuits may display their category, we only show the
        # option if at least one circuit is present
        if any([isinstance(i, CircuitItem) for i in selection]):
            self.showCategoryLabel.setHidden(False)
            self.showCategoryCB.setHidden(False)
        # Wires have no name; no need for name visibility
        if not all([isinstance(i, WireItem) for i in selection]):
            self.showNameLabel.setHidden(False)
            self.showNameCB.setHidden(False)
        # We only show the name if we have exactly one non-wire item
        if len(selection) == 1 and not isinstance(selection[0], WireItem):
            self.nameLabel.setHidden(False)
            self.nameLE.blockSignals(True)
            self.nameLE.setText(selection[0].data.name)
            self.nameLE.blockSignals(False)
            self.nameLE.setHidden(False)

    def setCategoryVisibility(self, state):
        """Show/Hide the category of an item in the main view."""
        for item in self.view.scene().selectedItems():
            if isinstance(item, CircuitItem):
                item.setCategoryVisibility(True if state else False)

    def setItemName(self):
        """Show/Hide the category of an item in the main view."""
        item = self.view.scene().selectedItems()[0]
        item.data.setName(self.nameLE.text())
        item.setupPaint()

    def setNameVisibility(self, state):
        """Show/Hide the name of items in the main view."""
        for item in self.view.scene().selectedItems():
            if not isinstance(item, WireItem):
                item.setNameVisibility(True if state else False)

    def setNbInputs(self, index):
        """Add/Remove inputs from basic gates."""
        for item in self.view.scene().selectedItems():
            item.setNbInputs(index + 2)
Exemple #57
0
class EditEmployeeWidget(QWidget):
    """PySide widget that contains GUI for editing existing employee record from the database

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

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


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

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

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

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

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

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

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

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

        self.setupUI()

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

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

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

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

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

        self.setInputReadOnly(True)

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

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

            self.setInputReadOnly(False)

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

    def setupUI(self):

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

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

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

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

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

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

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

        layout.addLayout(bttnLayout)

        paneLayout.addWidget(leftPane)
        paneLayout.addLayout(layout)
        self.setLayout(paneLayout)
class MTTFilterFileDialog(QDialog):
    def __init__(self, define_path='', define_type=None):
        super(MTTFilterFileDialog, self).__init__(get_maya_window())

        self.supported_node_type = sorted(
            [node_type
             for (node_type, nice, attr) in MTTSettings.SUPPORTED_TYPE])

        self.defined_path = (
            define_path
            if os.path.isdir(define_path) or define_path == SOURCEIMAGES_TAG
            else None)

        self.defined_type = (
            define_type
            if define_type in self.supported_node_type
            else None)

        self.path_edit = None
        self.filter_reset_btn = None
        self.filter_line = None
        self.parent_folder_btn = None
        self.files_model = None
        self.files_list = None
        self.bookmark_list = None
        self.bookmark_list_sel_model = None
        self.types = None

        # move window to cursor position
        win_geo = MTTSettings.value(
            'FilterFileDialog/windowGeometry', QRect(0, 0, 400, 300))
        self.setGeometry(win_geo)
        mouse_pos = QCursor.pos()
        mouse_pos.setX(mouse_pos.x() - (win_geo.width() * 0.5))
        self.move(mouse_pos)

        self.__create_ui()

        self.filter_line.setFocus()
        self.on_change_root_path(self.defined_path or SOURCEIMAGES_TAG)

    def __create_ui(self):
        """ Create main UI """
        self.setWindowTitle(CREATE_NODE_TITLE)

        # remove window decoration if path and type is set
        if self.defined_path and self.defined_type:
            self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)

        main_layout = QVBoxLayout(self)
        main_layout.setSpacing(1)
        main_layout.setContentsMargins(2, 2, 2, 2)

        # content layout
        content_layout = QVBoxLayout()
        self.files_model = QFileSystemModel()
        self.files_model.setNameFilterDisables(False)
        self.files_list = MTTFileList()
        self.files_list.setAlternatingRowColors(True)
        self.files_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.files_list.selectionValidated.connect(self.do_validate_selection)
        self.files_list.goToParentDirectory.connect(self.on_go_up_parent)
        self.files_list.doubleClicked.connect(self.on_double_click)
        self.files_list.setModel(self.files_model)

        buttons_layout = QHBoxLayout()

        content_layout.addLayout(self.__create_filter_ui())
        content_layout.addWidget(self.files_list)
        content_layout.addLayout(buttons_layout)
        self.files_list.filter_line = self.filter_line

        if not self.defined_path:
            # path line
            path_layout = QHBoxLayout()
            # bookmark button
            bookmark_btn = QPushButton('')
            bookmark_btn.setFlat(True)
            bookmark_btn.setIcon(QIcon(':/addBookmark.png'))
            bookmark_btn.setToolTip('Bookmark this Folder')
            bookmark_btn.setStatusTip('Bookmark this Folder')
            bookmark_btn.clicked.connect(self.on_add_bookmark)
            # path line edit
            self.path_edit = QLineEdit()
            self.path_edit.editingFinished.connect(self.on_enter_path)
            # parent folder button
            self.parent_folder_btn = QPushButton('')
            self.parent_folder_btn.setFlat(True)
            self.parent_folder_btn.setIcon(QIcon(':/SP_FileDialogToParent.png'))
            self.parent_folder_btn.setToolTip('Parent Directory')
            self.parent_folder_btn.setStatusTip('Parent Directory')
            self.parent_folder_btn.clicked.connect(self.on_go_up_parent)
            # browse button
            browse_btn = QPushButton('')
            browse_btn.setFlat(True)
            browse_btn.setIcon(QIcon(':/navButtonBrowse.png'))
            browse_btn.setToolTip('Browse Directory')
            browse_btn.setStatusTip('Browse Directory')
            browse_btn.clicked.connect(self.on_browse)
            # parent widget and layout
            path_layout.addWidget(bookmark_btn)
            path_layout.addWidget(self.path_edit)
            path_layout.addWidget(self.parent_folder_btn)
            path_layout.addWidget(browse_btn)
            main_layout.addLayout(path_layout)

            # bookmark list
            bookmark_parent_layout = QHBoxLayout()
            bookmark_frame = QFrame()
            bookmark_frame.setFixedWidth(120)
            bookmark_layout = QVBoxLayout()
            bookmark_layout.setSpacing(1)
            bookmark_layout.setContentsMargins(2, 2, 2, 2)
            bookmark_frame.setLayout(bookmark_layout)
            bookmark_frame.setFrameStyle(QFrame.Sunken)
            bookmark_frame.setFrameShape(QFrame.StyledPanel)
            self.bookmark_list = MTTBookmarkList()
            self.bookmark_list.bookmarkDeleted.connect(self.do_delete_bookmark)
            self.bookmark_list.setAlternatingRowColors(True)
            self.bookmark_list.dragEnabled()
            self.bookmark_list.setAcceptDrops(True)
            self.bookmark_list.setDropIndicatorShown(True)
            self.bookmark_list.setDragDropMode(QListView.InternalMove)
            self.bookmark_list_sel_model = self.bookmark_list.selectionModel()
            self.bookmark_list_sel_model.selectionChanged.connect(
                self.on_select_bookmark)

            bookmark_layout.addWidget(self.bookmark_list)
            bookmark_parent_layout.addWidget(bookmark_frame)
            bookmark_parent_layout.addLayout(content_layout)
            main_layout.addLayout(bookmark_parent_layout)

            self.do_populate_bookmarks()

        else:
            main_layout.addLayout(content_layout)

        if not self.defined_type:
            # type layout
            self.types = QComboBox()
            self.types.addItems(self.supported_node_type)
            self.types.currentIndexChanged.connect(self.on_node_type_changed)
            if cmds.optionVar(exists='MTT_lastNodeType'):
                last = cmds.optionVar(query='MTT_lastNodeType')
                if last in self.supported_node_type:
                    self.types.setCurrentIndex(
                        self.supported_node_type.index(last))
            buttons_layout.addWidget(self.types)

        if not self.defined_path or not self.defined_type:
            create_btn = QPushButton('C&reate')
            create_btn.clicked.connect(self.accept)
            cancel_btn = QPushButton('&Cancel')
            cancel_btn.clicked.connect(self.reject)

            buttons_layout.addStretch()
            buttons_layout.addWidget(create_btn)
            buttons_layout.addWidget(cancel_btn)

    def __create_filter_ui(self):
        """ Create filter widgets """
        filter_layout = QHBoxLayout()
        filter_layout.setSpacing(1)
        filter_layout.setContentsMargins(0, 0, 0, 0)

        self.filter_reset_btn = QPushButton()
        icon = QIcon(':/filtersOff.png')
        self.filter_reset_btn.setIcon(icon)
        self.filter_reset_btn.setIconSize(QSize(22, 22))
        self.filter_reset_btn.setFixedSize(24, 24)
        self.filter_reset_btn.setToolTip('Reset filter')
        self.filter_reset_btn.setFlat(True)
        self.filter_reset_btn.clicked.connect(
            partial(self.on_filter_set_text, ''))

        self.filter_line = QLineEdit()
        self.filter_line.setPlaceholderText('Enter filter string here')
        self.filter_line.textChanged.connect(self.on_filter_change_text)

        completer = QCompleter(self)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        completer.setModel(QStringListModel([], self))
        self.filter_line.setCompleter(completer)

        filter_layout.addWidget(self.filter_reset_btn)
        filter_layout.addWidget(self.filter_line)

        return filter_layout

    def on_filter_set_text(self, text=''):
        """ Set text in filter field """
        self.filter_line.setText(text)

    def on_filter_change_text(self, text):
        """ Apply filter string """
        if len(text):
            icon = QIcon(':/filtersOn.png')
            self.filter_reset_btn.setIcon(icon)
        else:
            icon = QIcon(':/filtersOff.png')
            self.filter_reset_btn.setIcon(icon)

        self.files_model.setNameFilters(
            ['*%s*' % item.strip() for item in text.split(',') if item.strip()])

    def on_node_type_changed(self, index):
        cmds.optionVar(sv=['MTT_lastNodeType', self.supported_node_type[index]])

    def on_double_click(self, index):
        current_item = self.files_model.filePath(index)
        if os.path.isdir(current_item):
            self.on_change_root_path(current_item)
        elif os.path.isfile(current_item):
            self.accept()

    def on_change_root_path(self, current_path):
        if current_path == SOURCEIMAGES_TAG:
            current_path = os.path.join(
                cmds.workspace(query=True, rootDirectory=True),
                cmds.workspace(fileRuleEntry='sourceImages')
            )

        self.files_model.setRootPath(current_path)
        self.files_list.setRootIndex(self.files_model.index(current_path))
        if self.path_edit:
            self.path_edit.setText(current_path)

        if self.parent_folder_btn:
            current_dir = QDir(current_path)
            self.parent_folder_btn.setEnabled(current_dir.cdUp())

    def on_go_up_parent(self):
        current_path = QDir(self.files_model.rootPath())
        current_path.cdUp()
        self.on_change_root_path(current_path.absolutePath())

    def on_enter_path(self):
        new_path = self.path_edit.text()
        if os.path.isdir(new_path):
            self.on_change_root_path(new_path)
        else:
            self.path_edit.setText(self.files_model.rootPath())

    def on_browse(self):
        current_path = self.files_model.rootPath()
        file_dialog = QFileDialog(self, 'Select a Folder', current_path)
        file_dialog.setFileMode(QFileDialog.Directory)
        file_dialog.setOption(QFileDialog.ShowDirsOnly)

        if file_dialog.exec_():
            self.on_change_root_path(file_dialog.selectedFiles()[0])

    def on_select_bookmark(self, selected, deselected):
        current_item = selected.indexes()
        if current_item:
            self.on_change_root_path(
                self.bookmark_list.selectedItems()[0].root_path)

    def on_add_bookmark(self):
        current_path = self.files_model.rootPath()
        self.on_add_bookmark_item(
            '%s|%s' % (os.path.basename(current_path), current_path))

    def on_add_bookmark_item(self, item):
        if item == '':
            return

        current_item = MTTBookmarkItem()
        current_item.add_raw_data(item)
        current_item.setSizeHint(QSize(40, 25))
        current_item.setFlags(
            Qt.ItemIsEnabled | Qt.ItemIsEditable |
            Qt.ItemIsSelectable | Qt.ItemIsDragEnabled
        )

        self.bookmark_list.addItem(current_item)

    def do_delete_bookmark(self):
        current_item = self.bookmark_list.selectedItems()
        if current_item:
            item_row = self.bookmark_list.row(current_item[0])
            self.bookmark_list.takeItem(item_row)
            del current_item[0]

    def do_save_bookmark(self):
        if not self.bookmark_list:
            return

        row_count = self.bookmark_list.count()
        ordered_list = list()

        for i in range(row_count):
            item = self.bookmark_list.item(i)
            name = item.text().replace(',', '_').replace('|', '_')
            path = item.root_path
            if name != 'sourceimages':
                ordered_list.append('%s|%s' % (name, path))

        MTTSettings.set_value(
            'FilterFileDialog/bookmarks', ','.join(ordered_list))

    def do_populate_bookmarks(self):
        bookmarks = ['sourceimages|%s' % SOURCEIMAGES_TAG]
        bookmarks.extend(
            MTTSettings.value('FilterFileDialog/bookmarks').split(','))

        for bm in bookmarks:
            self.on_add_bookmark_item(bm)

    def do_validate_selection(self):
        selection = self.files_list.selectedIndexes()
        if len(selection) == 1:
            current_path = self.files_model.filePath(selection[0])
            if os.path.isdir(current_path):
                self.on_change_root_path(current_path)
                return
        self.accept()

    def get_selected_files(self):
        selected_items = list()
        for item_index in self.files_list.selectedIndexes():
            current_path = self.files_model.filePath(item_index)
            if os.path.isfile(current_path):
                selected_items.append(current_path)
        return selected_items

    def get_node_type(self):
        return self.types.currentText() if self.types else self.defined_type

    def closeEvent(self, event):
        MTTSettings.set_value(
            'FilterFileDialog/windowGeometry', self.geometry())
        self.do_save_bookmark()

        self.deleteLater()
        event.accept()
Exemple #59
0
class ReportMovementFilter(QtGui.QWidget):
    def __init__(self, parent):
        super(ReportMovementFilter, self).__init__()
        self.parent = parent
        self.layout = QtGui.QGridLayout(self)
        #lblFromDate
        self.lblFromDate = QLabel("From Date")
        self.lblFromDate.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.layout.addWidget(self.lblFromDate, 1, 0)
        #dateFromDate
        self.dateFromDate = QDateEdit(self)
        self.dateFromDate.setDisplayFormat("dd-MM-yyyy")
        self.dateFromDate.setDate(date(2018, 1, 1))
        self.dateFromDate.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.layout.addWidget(self.dateFromDate, 1, 1)
        #lblToDate
        self.lblToDate = QLabel("To Date")
        self.lblToDate.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.layout.addWidget(self.lblToDate, 2, 0)
        #dateToDate
        self.dateToDate = QDateEdit(self)
        self.dateToDate.setDisplayFormat("dd-MM-yyyy")
        self.dateToDate.setDate(QDate.currentDate())
        self.dateToDate.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.layout.addWidget(self.dateToDate, 2, 1)
        #lblMovementType
        self.lblMovementType = QLabel("Movement Type")
        self.layout.addWidget(self.lblMovementType, 3, 0)
        #cmdMovementType
        self.cmdMovementType = QComboBox(self)
        self.cmdMovementType.addItems(DaoReportMovement.getMovementType())
        self.cmdMovementType.setCurrentIndex(
            self.cmdMovementType.findText("ALL"))
        self.layout.addWidget(self.cmdMovementType, 3, 1)
        #lblAssetName
        self.lblAssetName = QLabel("Asset Name")
        self.layout.addWidget(self.lblAssetName, 4, 0)
        #cmdAssetName
        self.cmdAssetName = QComboBox(self)
        self.cmdAssetName.addItems(DaoReportMovement.getAssetNames())
        self.cmdAssetName.setCurrentIndex(self.cmdAssetName.findText("ALL"))
        self.layout.addWidget(self.cmdAssetName, 4, 1)
        #lblCustodyName
        self.lblCustodyName = QLabel("Custody Name")
        self.layout.addWidget(self.lblCustodyName, 5, 0)
        #cmdCustodyName
        self.cmdCustodyName = QComboBox(self)
        self.cmdCustodyName.addItems(DaoCustody().getCustodyNameList())
        self.cmdCustodyName.setCurrentIndex(
            self.cmdCustodyName.findText("ALL"))
        self.layout.addWidget(self.cmdCustodyName, 5, 1)
        #btnSubmit
        self.btnSubmit = QPushButton("Submit", self)
        self.btnSubmit.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.layout.addWidget(self.btnSubmit)
        self.setFixedSize(190, 150)
        self.initListener()

    def initListener(self):
        self.btnSubmit.clicked.connect(self.doSubmit)

    def doSubmit(self):
        fromDate = (self.dateFromDate.date()).toPython()
        toDate = (self.dateToDate.date()).toPython()
        movementType = self.cmdMovementType.currentText()
        assetName = self.cmdAssetName.currentText()
        custodyName = self.cmdCustodyName.currentText()
        self.parent.doSubmit(fromDate, toDate, movementType, assetName,
                             custodyName)
Exemple #60
0
class ColorMapWidget(QWidget):
    """Interface for changing ColorMap information. It shows the current
       color map selection, a selector for other colormaps, and the option
       to cycle the color map by any number of ordinal values.

       This widget was designed for use with the tab dialog. It can be used by
       itself or it can be used as part of a bigger color tab.

       Changes to this widget are emitted via a changeSignal as a ColorMap
       object and this widget's tag.
    """

    changeSignal = Signal(ColorMap, str)

    def __init__(self, parent, initial_map, tag):
        """Creates a ColorMap widget.

           parent
               The Qt parent of this widget.

           initial_map
               The colormap set on creation.

           tag
               A name for this widget, will be emitted on change.
        """
        super(ColorMapWidget, self).__init__(parent)
        self.color_map = initial_map.color_map
        self.color_map_name = initial_map.color_map_name
        self.color_step = initial_map.color_step
        self.step_size = initial_map.step_size
        self.tag = tag

        self.color_map_label = "Color Map"
        self.color_step_label = "Cycle Color Map"
        self.number_steps_label = "Colors"

        self.color_step_tooltip = "Use the given number of evenly spaced " \
            + " colors from the map and assign to discrete values in cycled " \
            + " sequence."

        layout = QVBoxLayout()

        layout.addWidget(self.buildColorBarControl())
        layout.addItem(QSpacerItem(5, 5))
        layout.addWidget(self.buildColorStepsControl())

        self.setLayout(layout)

    def buildColorBarControl(self):
        """Builds the portion of this widget for color map selection."""
        widget = QWidget()
        layout = QHBoxLayout()

        label = QLabel(self.color_map_label)
        self.colorbar = QLabel(self)
        self.colorbar.setPixmap(
            QPixmap.fromImage(ColorBarImage(self.color_map, 180, 15)))

        self.mapCombo = QComboBox(self)
        self.mapCombo.addItems(map_names)
        self.mapCombo.setCurrentIndex(map_names.index(self.color_map_name))
        self.mapCombo.currentIndexChanged.connect(self.colorbarChange)

        layout.addWidget(label)
        layout.addItem(QSpacerItem(5, 5))
        layout.addWidget(self.mapCombo)
        layout.addItem(QSpacerItem(5, 5))
        layout.addWidget(self.colorbar)

        widget.setLayout(layout)
        return widget

    @Slot(int)
    def colorbarChange(self, ind):
        """Handles a selection of a different colormap."""
        indx = self.mapCombo.currentIndex()
        self.color_map_name = map_names[indx]
        self.color_map = getMap(self.color_map_name)
        self.colorbar.setPixmap(
            QPixmap.fromImage(ColorBarImage(self.color_map, 180, 12)))
        self.changeSignal.emit(
            ColorMap(self.color_map_name, self.color_step, self.step_size),
            self.tag)

    def buildColorStepsControl(self):
        """Builds the portion of this widget for color cycling options."""
        widget = QWidget()
        layout = QHBoxLayout()

        self.stepBox = QCheckBox(self.color_step_label)
        self.stepBox.stateChanged.connect(self.colorstepsChange)

        self.stepEdit = QLineEdit("8", self)
        # Setting max to sys.maxint in the validator causes an overflow! D:
        self.stepEdit.setValidator(QIntValidator(1, 65536, self.stepEdit))
        self.stepEdit.setEnabled(False)
        self.stepEdit.editingFinished.connect(self.colorstepsChange)

        if self.color_step > 0:
            self.stepBox.setCheckState(Qt.Checked)
            self.stepEdit.setEnabled(True)

        layout.addWidget(self.stepBox)
        layout.addItem(QSpacerItem(5, 5))
        layout.addWidget(QLabel("with"))
        layout.addItem(QSpacerItem(5, 5))
        layout.addWidget(self.stepEdit)
        layout.addItem(QSpacerItem(5, 5))
        layout.addWidget(QLabel(self.number_steps_label))

        widget.setLayout(layout)
        return widget

    def colorstepsChange(self):
        """Handles a change in the state of the color cycling for this
           colormap.
        """
        if self.stepBox.checkState() == Qt.Checked:
            self.stepEdit.setEnabled(True)
            self.color_step = int(self.stepEdit.text())
            self.changeSignal.emit(
                ColorMap(self.color_map_name, self.color_step, self.step_size),
                self.tag)
        else:
            self.stepEdit.setEnabled(False)
            self.color_step = 0
            self.changeSignal.emit(
                ColorMap(self.color_map_name, self.color_step, self.step_size),
                self.tag)