コード例 #1
0
ファイル: masin.py プロジェクト: FelixAkk/masin
class Masin(QtGui.QMainWindow):
	def __init__(self, parent=None):
		QtGui.QWidget.__init__(self, parent)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		
		self.signals()
	
		self.gci = Gcinvoice()
	
		self.defaultBullShit()
	
	def defaultBullShit(self):
		self.ui.gnuCashEditline.setText("D:\\AerixSVN\\documents\\aerix_accounting.gnucash")
		self.ui.latexTemplateEditline.setText("D:\\Aerix\\facturen\\masin\\example\\invoice_template.tex")
		self.ui.outputFilenameEditline.setText("D:\\Aerix\\facturen\\masin\\src\\lol.tex")
		self.ui.invoiceNumberSpinbox.setValue(8)

	def gnuCashClick(self):
		filename = QtGui.QFileDialog.getOpenFileName(self, 'Choose GnuCash Data File', '.')
		self.ui.gnuCashEditline.setText(filename)

	def latexTemplateClick(self):
		filename = QtGui.QFileDialog.getOpenFileName(self, 'Choose Template File', '.')
		self.ui.latexTemplateEditline.setText(filename)

	def outputFilenameClick(self):
		filename = QtGui.QFileDialog.getSaveFileName(self, 'Create Output File', '.')
		self.ui.outputFilenameEditline.setText(filename)

	def signals(self):
		QtCore.QObject.connect(self.ui.gnuCashButton, QtCore.SIGNAL("clicked()"), self.gnuCashClick)
		QtCore.QObject.connect(self.ui.latexTemplateButton, QtCore.SIGNAL("clicked()"), self.latexTemplateClick)
		QtCore.QObject.connect(self.ui.outputFilenameButton, QtCore.SIGNAL("clicked()"), self.outputFilenameClick)
		QtCore.QObject.connect(self.ui.generateButton, QtCore.SIGNAL("clicked()"), self.generateClick)

	def generateClick(self):
		self.gci.parse(str(self.ui.gnuCashEditline.text()))
		self.gci.createInvoice(invoiceid=str(self.ui.invoiceNumberSpinbox.text()), template=str(self.ui.latexTemplateEditline.text()), outfile=str(self.ui.outputFilenameEditline.text()))
		print "done"
コード例 #2
0
class RtGui(qtw.QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.rhost = RenderHost()
        self.rhost.outputSignal.connect(self.onOutput)

        # Make frameless & add drop shadow
        self.setWindowTitle("Scene Editor")
        self.setWindowFlags(qtc.Qt.FramelessWindowHint)
        set_frameless_attrs(self, self.ui.drop_shadow_frame)
        self.setAttribute(qtc.Qt.WA_TranslucentBackground)

        # Initialize Blur Effect
        self.blur = qtw.QGraphicsBlurEffect(self)
        self.blur.setBlurRadius(7)
        self.blur.setBlurHints(qtw.QGraphicsBlurEffect.QualityHint)
        self.ui.centralwidget.setGraphicsEffect(self.blur)
        self.blur.setEnabled(False)

        # Initialize Colorize Effect
        self.colorize = qtw.QGraphicsColorizeEffect(self)
        self.colorize.setColor(QColor(0, 0, 0))
        self.colorize2 = qtw.QGraphicsColorizeEffect(self)
        self.colorize2.setColor(QColor(0, 0, 0))
        self.colorize3 = qtw.QGraphicsColorizeEffect(self)
        self.colorize3.setColor(QColor(0, 0, 0))
        self.ui.title_bar.setGraphicsEffect(self.colorize)
        self.ui.credits_bar.setGraphicsEffect(self.colorize2)
        self.ui.content_bar.setGraphicsEffect(self.colorize3)
        self.colorize.setEnabled(False)
        self.colorize2.setEnabled(False)
        self.colorize3.setEnabled(False)

        # Initialize Settings
        self.settings = QWidget()
        self.settings.setWindowTitle("Settings")
        self.settings.ui = Ui_Settings()
        self.settings.ui.setupUi(self.settings)
        self.settings.ui.exitSettingsBtn.clicked.connect(self.exitsettings)
        set_frameless_attrs(self.settings, self.settings.ui.drop_shadow_frame)

        # Drag function bindings
        self.ui.title_bar.mouseMoveEvent = self.moveWindow
        self.ui.title_bar.mousePressEvent = self.setDragPos
        self.ui.label_title.mouseMoveEvent = self.moveWindow
        self.ui.label_title.mousePressEvent = self.setDragPos

        # Color Preview
        self.ui.difx.textChanged.connect(self.updateVis)
        self.ui.dify.textChanged.connect(self.updateVis)
        self.ui.difz.textChanged.connect(self.updateVis)
        self.ui.specx.textChanged.connect(self.updateVis)
        self.ui.specy.textChanged.connect(self.updateVis)
        self.ui.specz.textChanged.connect(self.updateVis)
        self.ui.emisx.textChanged.connect(self.updateVis)
        self.ui.emisy.textChanged.connect(self.updateVis)
        self.ui.emisz.textChanged.connect(self.updateVis)

        # Color Picking
        self.ui.diffusevis.clicked.connect(lambda: self.pick_color("diffuse"))
        self.ui.specularvis.clicked.connect(
            lambda: self.pick_color("specular"))
        self.ui.emissionvis.clicked.connect(
            lambda: self.pick_color("emission"))

        # Connect Buttons to Functions
        self.ui.btn_close.clicked.connect(self.exit)
        self.ui.btn_minimize.clicked.connect(self.showMinimized)
        self.ui.addobj.clicked.connect(self.addobj)
        self.ui.delobj.clicked.connect(self.delobj)
        self.ui.applyobj.clicked.connect(self.applyobj)
        self.ui.clearobj.clicked.connect(self.clearobj)
        self.ui.obj_list.itemClicked.connect(self.loadobj)
        self.ui.addmat.clicked.connect(self.addmat)
        self.ui.delmat.clicked.connect(self.delmat)
        self.ui.applymat.clicked.connect(self.applymat)
        self.ui.clearmat.clicked.connect(self.clearmat)
        self.ui.mat_list.itemClicked.connect(self.loadmat)
        self.ui.diffusemap.clicked.connect(self.loadDiffuse)
        self.ui.specularmap.clicked.connect(self.loadSpecular)
        self.ui.normalmap.clicked.connect(self.loadNormal)
        self.ui.openbtn.clicked.connect(self.openScene)
        self.ui.savebtn.clicked.connect(self.saveScene)
        self.ui.renderbtn.clicked.connect(self.renderScene)
        self.ui.settingsbtn.clicked.connect(self.opensettings)

        # Select first input
        self.ui.objname.setFocus(True)

        #Data Variables
        self.scenepath = None
        self.savetoexit = True
        self.rrtloc = '"D:/Files/Code/Ruby Raytracer/rrt_render.rb"'
        self.rrtloc = '"D:/Files/Code/repos/ruby-raytracer/rrt_render.exe"'
        #self.rrtloc = '"C:/Users/Avaze/Desktop/rrt_render.exe"'

        self.DEFAULTMAT = {
            "name": "default",
            "difx": 200,
            "dify": 200,
            "difz": 200,
            "specx": 255,
            "specy": 255,
            "specz": 255,
            "reflectivity": 0,
            "emisx": 0,
            "emisy": 0,
            "emisz": 0,
            "diftex": None,
            "spectex": None,
            "normaltex": None,
            "normalstrength": 1
        }
        self.diffuse = None
        self.specular = None
        self.normal = None

        self.lastobjindex = None
        self.lastmatindex = None

        self.objects = []
        self.materials = [self.DEFAULTMAT]
        self.vis_materials()

    # UI Functions
    def openScene(self):
        dialog = qtw.QFileDialog()
        dialog.setNameFilter("Scene Files (*.sc)")
        dialog.setWindowTitle("Open Scene")

        if (dialog.exec_()):
            self.scenepath = str(dialog.selectedFiles()[0])
            self.ui.path_label.setText(self.scenepath)
            file = open(self.scenepath)
            data = json.load(file)

            self.objects = data["objects"]
            self.materials = data["materials"]
            sets = data["settings"]
            self.settings.ui.width.setText(str(sets["width"]))
            self.settings.ui.height.setText(str(sets["height"]))
            self.settings.ui.reflection_depth.setText(
                str(sets["reflection_depth"]))

            file.close()
            self.vis_objects()
            self.vis_materials()

    def saveScene(self):

        if self.scenepath == None:
            dialog = qtw.QFileDialog.getSaveFileName(self, "Save Scene",
                                                     "C:/Users/new_scene.sc",
                                                     "Scene Files (*.sc)")
        else:
            dialog = (self.scenepath, "")

        if (dialog != ('', '')):
            self.scenepath = dialog[0]
            self.ui.path_label.setText(self.scenepath)
            file = open(self.scenepath, "w")

            data = {
                "objects": self.objects,
                "materials": self.materials,
                "settings": {
                    "width":
                    int(self.settings.ui.width.text()),
                    "height":
                    int(self.settings.ui.height.text()),
                    "reflection_depth":
                    int(self.settings.ui.reflection_depth.text())
                }
            }

            file.write(json.dumps(data, indent=2))
            file.close()
            self.savetoexit = True

    def opensettings(self):
        self.unfocusGui()
        self.settings.show()

    def exitsettings(self):
        self.settings.close()
        self.focusGui()

    def renderScene(self):
        self.saveScene()
        cmd = f'{self.rrtloc} ' + str(self.scenepath)
        self.ui.label_status.setText("Rendering")
        self.rhost.run(cmd)

    def exit(self):

        if self.savetoexit:
            self.close()
        else:
            self.unfocusGui()
            dialog = QDialog()
            ui = Dlg_yn()
            ui.setupUi(dialog)
            ui.title.setText("Exit App?")
            ui.title.setStyleSheet('font-size: 25pt; color: #dd3322')
            ui.description.setText("All unsaved changes will be lost")
            set_frameless_attrs(dialog, ui.dropshadow_frame)
            # Show in Middle
            w, h = dialog.frameGeometry().width(), dialog.frameGeometry(
            ).height()
            ww, wh = self.frameGeometry().width(), self.frameGeometry().height(
            )
            dialog.setGeometry(self.pos().x() + ww / 2 - w / 2,
                               self.pos().y() + wh / 2 - h / 2, w, h)

            if dialog.exec_():
                self.close()

            self.focusGui()

    # Utility
    def checkBtn(self, b):
        if b.isCheckable():
            if not b.isChecked():
                b.toggle()

    def uncheckBtn(self, b):
        if b.isCheckable():
            if b.isChecked():
                b.toggle()

    def updateVis(self):
        difx, dify, difz, specx, specy, specz, emisx, emisy, emisz = 0, 0, 0, 0, 0, 0, 0, 0, 0
        if len(self.ui.difx.text()) != 0: difx = self.ui.difx.text()
        if len(self.ui.dify.text()) != 0: dify = self.ui.dify.text()
        if len(self.ui.difz.text()) != 0: difz = self.ui.difz.text()
        if len(self.ui.specx.text()) != 0: specx = self.ui.specx.text()
        if len(self.ui.specy.text()) != 0: specy = self.ui.specy.text()
        if len(self.ui.specz.text()) != 0: specz = self.ui.specz.text()
        if len(self.ui.emisx.text()) != 0: emisx = self.ui.emisx.text()
        if len(self.ui.emisy.text()) != 0: emisy = self.ui.emisy.text()
        if len(self.ui.emisz.text()) != 0: emisz = self.ui.emisz.text()
        self.ui.diffusevis.setStyleSheet(
            "QPushButton{border: 2px solid rgb(64, 64, 64);border-radius: 10px;"
            + f"background-color: rgb({difx}, {dify}, {difz});" +
            "}QPushButton:hover{border-color: rgb(221, 51, 34);}QPushButton:pressed{border-color: rgb(255, 102, 85);}"
        )
        self.ui.specularvis.setStyleSheet(
            "QPushButton{border: 2px solid rgb(64, 64, 64);border-radius: 10px;"
            + f"background-color: rgb({specx}, {specy}, {specz});" +
            "}QPushButton:hover{border-color: rgb(221, 51, 34);}QPushButton:pressed{border-color: rgb(255, 102, 85);}"
        )
        self.ui.emissionvis.setStyleSheet(
            "QPushButton{border: 2px solid rgb(64, 64, 64);border-radius: 10px;"
            + f"background-color: rgb({emisx}, {emisy}, {emisz});" +
            "}QPushButton:hover{border-color: rgb(221, 51, 34);}QPushButton:pressed{border-color: rgb(255, 102, 85);}"
        )

    def onOutput(self, str):
        value = int(str.strip())
        if value == 100: self.ui.label_status.setText("Finished")
        self.ui.bar.move(-200 + 2 * value, 0)

    def pick_color(self, mode):

        cp = ColorPicker()
        self.unfocusGui()

        if mode == "diffuse":
            try:
                oldr, oldg, oldb = (int(self.ui.difx.text()),
                                    int(self.ui.dify.text()),
                                    int(self.ui.difz.text()))
            except:
                oldr, oldg, oldb = (0, 0, 0)
            r, g, b = cp.getColor((oldr, oldg, oldb))
            self.ui.difx.setText(str(int(r)))
            self.ui.dify.setText(str(int(g)))
            self.ui.difz.setText(str(int(b)))

        if mode == "specular":
            try:
                oldr, oldg, oldb = (int(self.ui.specx.text()),
                                    int(self.ui.specy.text()),
                                    int(self.ui.specz.text()))
            except:
                oldr, oldg, oldb = (0, 0, 0)
            r, g, b = cp.getColor((oldr, oldg, oldb))
            self.ui.specx.setText(str(int(r)))
            self.ui.specy.setText(str(int(g)))
            self.ui.specz.setText(str(int(b)))

        if mode == "emission":
            try:
                oldr, oldg, oldb = (int(self.ui.emisx.text()),
                                    int(self.ui.emisy.text()),
                                    int(self.ui.emisz.text()))
            except:
                oldr, oldg, oldb = (0, 0, 0)
            r, g, b = cp.getColor((oldr, oldg, oldb))
            self.ui.emisx.setText(str(int(r)))
            self.ui.emisy.setText(str(int(g)))
            self.ui.emisz.setText(str(int(b)))

        self.focusGui()

    def focusGui(self):
        self.colorize.setEnabled(False)
        self.colorize2.setEnabled(False)
        self.colorize3.setEnabled(False)
        self.blur.setEnabled(False)

    def unfocusGui(self):
        self.colorize.setEnabled(True)
        self.colorize2.setEnabled(True)
        self.colorize3.setEnabled(True)
        self.blur.setEnabled(True)

    # Dragging Functions
    def setDragPos(self, event):
        self.dragPos = event.globalPos()

    def moveWindow(self, event):
        # MOVE WINDOW
        if event.buttons() == Qt.LeftButton:
            self.move(self.pos() + event.globalPos() - self.dragPos)
            self.dragPos = event.globalPos()
            event.accept()

    # Object Functions
    def addobj(self):

        for i in range(0, 99999):
            found = False
            for obj in self.objects:
                if obj["name"] == ("sphere" + str(i)):
                    found = True
                    break
            if not found:
                newname = "sphere" + str(i)
                self.objects.append({
                    "name": newname,
                    "posx": 0,
                    "posy": 0,
                    "posz": 0,
                    "radius": 1,
                    "material": "default"
                })
                break
        self.vis_objects()
        self.loadobj(len(self.objects) - 1)
        self.savetoexit = False

    def delobj(self):
        itms = self.ui.obj_list.selectedItems()
        if itms != []:
            index = self.ui.obj_list.row(itms[0])
            del self.objects[index]
            self.ui.obj_list.takeItem(index)
            self.ui.objname.clear()
            self.ui.posx.clear()
            self.ui.posy.clear()
            self.ui.posz.clear()
            self.ui.radius.clear()
            self.ui.objmat.clear()
            self.savetoexit = False

    def loadobj(self, index):

        self.ui.objname.setFocus(True)
        if type(index) == QListWidgetItem:
            indx = self.ui.obj_list.row(index)
        else:
            indx = index

        self.lastobjindex = indx
        objname = self.objects[indx]["name"]
        for obj in self.objects:
            if objname == obj["name"]:
                o = obj
                break

        self.ui.objname.setText(str(o["name"]))
        self.ui.posx.setText(str(o["posx"]))
        self.ui.posy.setText(str(o["posy"]))
        self.ui.posz.setText(str(o["posz"]))
        self.ui.radius.setText(str(o["radius"]))
        self.ui.objmat.setText(str(o["material"]))

    def applyobj(self):
        objname = self.ui.objname.text()
        if objname == "" or len(self.objects) == 0:
            return
        index = None
        for obj in self.objects:
            if objname == obj["name"]:
                index = self.objects.index(obj)

        if index == None:
            index = self.lastobjindex

        self.objects[index] = {
            "name": objname,
            "posx": self.ui.posx.text(),
            "posy": self.ui.posy.text(),
            "posz": self.ui.posz.text(),
            "radius": self.ui.radius.text(),
            "material": self.ui.objmat.text()
        }

        self.vis_objects()
        self.savetoexit = False

    def clearobj(self):
        self.objects = []
        self.ui.objname.clear()
        self.ui.posx.clear()
        self.ui.posy.clear()
        self.ui.posz.clear()
        self.ui.radius.clear()
        self.ui.objmat.clear()
        self.vis_objects()
        self.savetoexit = False

    def vis_objects(self):
        self.ui.obj_list.clear()
        for obj in self.objects:
            self.ui.obj_list.addItem(obj["name"])

    # Material Functions
    def addmat(self):

        for i in range(0, 99999):
            found = False
            for mat in self.materials:
                if mat["name"] == ("mat" + str(i)):
                    found = True
                    break
            if not found:
                self.materials.append({
                    "name": "mat" + str(i),
                    "difx": 200,
                    "dify": 200,
                    "difz": 200,
                    "specx": 255,
                    "specy": 255,
                    "specz": 255,
                    "reflectivity": 0,
                    "emisx": 0,
                    "emisy": 0,
                    "emisz": 0,
                    "diftex": None,
                    "spectex": None,
                    "normaltex": None,
                    "normalstrength": 1
                })

                break
        self.vis_materials()
        self.loadmat(len(self.materials) - 1)
        self.savetoexit = False

    def delmat(self):
        itms = self.ui.mat_list.selectedItems()
        if itms != []:
            index = self.ui.mat_list.row(itms[0])
            del self.materials[index]
            self.ui.mat_list.takeItem(index)
            self.ui.matname.clear()
            self.ui.difx.clear()
            self.ui.dify.clear()
            self.ui.difz.clear()
            self.ui.specx.clear()
            self.ui.specy.clear()
            self.ui.specz.clear()
            self.ui.emisx.clear()
            self.ui.emisy.clear()
            self.ui.emisz.clear()
            self.ui.reflectivity.clear()
            self.ui.normalstrength.clear()
            self.diffuse = None
            self.specular = None
            self.normal = None
            self.savetoexit = False

    def loadmat(self, index):

        self.ui.matname.setFocus(True)
        if type(index) == QListWidgetItem:
            indx = self.ui.mat_list.row(index)
        else:
            indx = index

        self.lastmatindex = indx
        matname = self.materials[indx]["name"]
        for mat in self.materials:
            if matname == mat["name"]:
                m = mat
                break

        self.ui.matname.setText(str(m["name"]))
        self.ui.difx.setText(str(m["difx"]))
        self.ui.dify.setText(str(m["dify"]))
        self.ui.difz.setText(str(m["difz"]))
        self.ui.specx.setText(str(m["specx"]))
        self.ui.specy.setText(str(m["specy"]))
        self.ui.specz.setText(str(m["specz"]))
        self.ui.emisx.setText(str(m["emisx"]))
        self.ui.emisy.setText(str(m["emisy"]))
        self.ui.emisz.setText(str(m["emisz"]))
        self.ui.reflectivity.setText(str(m["reflectivity"]))
        self.ui.normalstrength.setText(str(m["normalstrength"]))
        self.diffuse = m["diftex"]
        self.specular = m["spectex"]
        self.normal = m["normaltex"]
        self.checkBtn(
            self.ui.diffusemap) if self.diffuse != None else self.uncheckBtn(
                self.ui.diffusemap)
        self.checkBtn(
            self.ui.specularmap) if self.specular != None else self.uncheckBtn(
                self.ui.specularmap)
        self.checkBtn(
            self.ui.normalmap) if self.normal != None else self.uncheckBtn(
                self.ui.normalmap)

    def applymat(self):
        matname = self.ui.matname.text()
        if matname == "":
            return
        index = None
        for mat in self.materials:
            if matname == mat["name"]:
                index = self.materials.index(mat)

        if index == None:
            index = self.lastmatindex

        self.materials[index] = {
            "name": matname,
            "difx": str(self.ui.difx.text()),
            "dify": str(self.ui.dify.text()),
            "difz": str(self.ui.difz.text()),
            "specx": str(self.ui.specx.text()),
            "specy": str(self.ui.specy.text()),
            "specz": str(self.ui.specz.text()),
            "reflectivity": str(self.ui.reflectivity.text()),
            "emisx": str(self.ui.emisx.text()),
            "emisy": str(self.ui.emisy.text()),
            "emisz": str(self.ui.emisz.text()),
            "diftex": self.diffuse,
            "spectex": self.specular,
            "normaltex": self.normal,
            "normalstrength": self.ui.normalstrength.text()
        }

        self.vis_materials()
        self.savetoexit = False

    def clearmat(self):
        self.materials = []
        self.ui.matname.clear()
        self.ui.difx.clear()
        self.ui.dify.clear()
        self.ui.difz.clear()
        self.ui.specx.clear()
        self.ui.specy.clear()
        self.ui.specz.clear()
        self.ui.emisx.clear()
        self.ui.emisy.clear()
        self.ui.emisz.clear()
        self.ui.reflectivity.clear()
        self.ui.normalstrength.clear()
        self.vis_materials()
        self.savetoexit = False

    def loadDiffuse(self):
        if self.diffuse != None:
            self.diffuse = None
            self.savetoexit = False
            return
        dialog = qtw.QFileDialog()
        dialog.setNameFilter("Image Files (*.png *.jpg *.tif *.gif)")
        dialog.setWindowTitle("Diffuse Map")

        if (dialog.exec_()):
            self.diffuse = str(dialog.selectedFiles()[0])
            self.savetoexit = False
        else:
            self.ui.diffusemap.toggle()

    def loadSpecular(self):
        if self.specular != None:
            self.specular = None
            return
        dialog = qtw.QFileDialog()
        dialog.setNameFilter("Image Files (*.png *.jpg *.tif *.gif)")
        dialog.setWindowTitle("Specular Map")

        if (dialog.exec_()):
            self.specular = str(dialog.selectedFiles()[0])
        else:
            self.ui.specularmap.toggle()

    def loadNormal(self):
        if self.normal != None:
            self.normal = None
            return
        dialog = qtw.QFileDialog()
        dialog.setNameFilter("Image Files (*.png *.jpg *.tif *.gif)")
        dialog.setWindowTitle("Normal Map")

        if (dialog.exec_()):
            self.normal = str(dialog.selectedFiles()[0])
        else:
            self.ui.normalmap.toggle()

    def vis_materials(self):
        self.ui.mat_list.clear()
        for mat in self.materials:
            self.ui.mat_list.addItem(mat["name"])
コード例 #3
0
ファイル: frames.py プロジェクト: slh0302/pyLabel
class Tracker_window(QtWidgets.QMainWindow):
    def __init__(self):
        super(Tracker_window, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.cwd = os.getcwd()
        self.scene = None
        self.printer = None
        self.draw_w = 0
        self.draw_h = 0
        self._func_bind()
        self.cv_cap_loader = None
        self.video_path = ""
        self.save_path = self.cwd
        self.save_name = 'results.txt'
        self.tacker_status = False
        self.cuda_state = torch.cuda.is_available()
        self.tracker_net = init_net(gpus=0,
                                    rel_path=os.path.join(
                                        __prefix_path__, '../checkpoint/'),
                                    cuda_state=self.cuda_state)
        self.total_frames = 0
        self.before_img = None
        self.cur_img = None
        self.cur_frames = 0
        """ reinit status """
        self.skip_frame = 0
        self.before_frame = 0
        self.move_value = 1
        self.reinit_status = False
        """ reinit status """
        self.frameRate = 0
        self.tracker_res = []
        self.thread_status = []
        self.img_scale_ratio = []  # w, h
        self.frame_state = []
        self.stopEvent = threading.Event()
        self.stopEvent.clear()
        self.timer = QBasicTimer()
        self.pause_status = False
        self.timer.start(1000, self)

        # train detector model
        self.train_dialog_ui = Ui_Dialog()
        self.train_dialog = QDialog()
        self.train_dialog_ui.setupUi(self.train_dialog)
        self.model_name = ""
        self.LabelFilePath = "./"
        self.outModelPath = "./"
        self.detect_status = False
        self._func_bind_train_dialog()

    def _func_bind(self):
        self.ui.progressBar.setEnabled(False)
        self.ui.displayLabel.setScaledContents(True)
        # self.ui.plainTextEdit.setEnabled(False)
        self._button_status_change(False)
        self.ui.actionOpen_video.triggered.connect(self.open_event)
        self.ui.actionSave_video.triggered.connect(self.save_event)
        self.ui.actionTrain_Faster_RCNN.triggered.connect(self.showTrainDialog)
        self.ui.redrawPushButton.clicked.connect(self._redraw_button)
        self.ui.startPushButton.clicked.connect(self.start_tracking)
        self.ui.pausPushButton.clicked.connect(self.pause_tracking)
        self.ui.stoPushButton.clicked.connect(self.stop_tracking)
        self.ui.chooseModelButton.clicked.connect(self.open_model_event)
        self.ui.nextPushButton.clicked.connect(self.next_tracking)
        self.ui.prePushButton.clicked.connect(self.prev_tracking)
        self.ui.FramesSpinBox.valueChanged.connect(self.spinValueChange)

    def _func_bind_train_dialog(self):
        self.train_dialog_ui.pushButtonOK.clicked.connect(self.train_ok)
        self.train_dialog_ui.pushButtonCancel.clicked.connect(
            self.train_cancel)
        self.train_dialog_ui.pushButtonLabelPath.clicked.connect(
            self.trainDialog_openLabel)
        self.train_dialog_ui.pushButtonOutModel.clicked.connect(
            self.trainDialog_outputPath)

    def _button_status_change(self, status, need_detect=False):
        self.ui.startPushButton.setEnabled(status)
        self.ui.pausPushButton.setEnabled(status)
        self.ui.redrawPushButton.setEnabled(status)
        self.ui.stoPushButton.setEnabled(status)
        self.ui.prePushButton.setEnabled(status)
        self.ui.nextPushButton.setEnabled(status)
        # self.ui.chooseModelButton.setEnabled(status)
        self.ui.FramesSpinBox.setEnabled(status)
        if not need_detect:
            self.ui.turnDetectorButton.setEnabled(status)

    def _write_logs_to_plain_text(self, text):
        self.ui.textBrowser.append(text)

    def _redraw_button(self):
        self.ui.displayLabel.setdrawDoneStatus(self.cur_img.copy(),
                                               self.img_scale_ratio)
        if self.cur_frames != 0:
            self.reinit_status = True
            self.ui.startPushButton.setText("re-start")
            self.ui.startPushButton.setEnabled(True)

    def _coord_to_text(self, x, y):
        return "X: %d, Y: %d" % (int(x), int(y))

    def _fresh_progresssBar(self):
        if self.total_frames != 0:
            self.ui.progressBar.setValue(
                int(self.cur_frames / self.total_frames * 100))

    def _set_img_ratio(self, img_wh):
        img_w = img_wh[1]
        img_h = img_wh[0]
        self.draw_h = self.ui.displayLabel.size().height()
        self.draw_w = self.ui.displayLabel.size().width()
        self.img_scale_ratio = [
            1.0 * img_w / self.draw_w, 1.0 * img_h / self.draw_h
        ]
        self._write_logs_to_plain_text("Img scale w: %.2f h: %.2f" %
                                       tuple(self.img_scale_ratio))

    def open_event(self):
        fileName_, f_type = QFileDialog.getOpenFileName(
            self, "Open videos", self.cwd,
            'All Files (*);;Mp4 (*.mp4);;Avi (*.avi)')
        if fileName_ == "":
            print("no files")
            return

        if check_filters(fileName_):
            self.video_path = fileName_
            self.init_trackers()
            print(fileName_, f_type)
        else:
            print(fileName_, ' is wrong!')
            return

    def open_model_event(self):
        fileName_, f_type = QFileDialog.getOpenFileName(
            self, "Open models", self.cwd,
            'All Files (*);;pth (*.pth);;Avi (*.model)')
        if fileName_ == "":
            print("no files")
            return

        if os.path.getsize(fileName_) > 100:
            self.model_name = fileName_
            if self.load_model(self.model_name):
                self.ui.turnDetectorButton.setEnabled(True)

            print(fileName_, f_type)
        else:
            print(fileName_, ' is wrong!')
            return

    def load_model(self, filename):
        if os.path.exists(filename):
            # try:
            #     # with open(filename, 'rb') as f:
            #
            # except:

            return True
        else:
            return False

    def save_event(self):
        fileName_, f_type = QFileDialog.getSaveFileName(self,
                                                        "Save videos",
                                                        self.cwd,
                                                        initialFilter='*.txt')
        if fileName_ == "":
            print('use default files')
            out_res_path = os.path.join(self.save_path, self.save_name)
        else:
            self.save_path = os.path.dirname(fileName_)
            self.save_name = os.path.basename(fileName_)
            out_res_path = os.path.join(self.save_path, self.save_name)
            self.LabelFilePath = out_res_path
            print('new path: ', out_res_path)

        if len(self.tracker_res) != 0:
            t1 = threading.Thread(target=save_files,
                                  args=(out_res_path, self.tracker_res))
            t1.start()
        else:
            print(fileName_, ' can\'t save, because the empty res')

        print(fileName_)

    def reinit_tracker(self):
        self.before_img = None
        self.cur_img = None
        self.cur_frames = 0
        self.frameRate = 0
        self.skip_frame = 0
        self.before_frame = 0
        # self.tracker_res = []

    def init_trackers(self):
        if self.total_frames != 0 and self.cv_cap_loader.isOpened():
            self.cv_cap_loader.release()
            self.cur_frames = 0

        if self.cur_frames != 0:
            self.cur_frames = 0

        self.tracker_res = []

        self.cv_cap_loader = cv2.VideoCapture(self.video_path)
        self.total_frames = self.cv_cap_loader.get(7)
        self.frameRate = self.cv_cap_loader.get(cv2.CAP_PROP_FPS)
        if self.cv_cap_loader.isOpened():
            ret, frame = self.cv_cap_loader.read()
            if ret:
                # self.scene.clear()
                self.cur_img = frame.copy()
                height, width, bytesPerComponent = frame.shape
                cv2.cvtColor(frame, cv2.COLOR_RGB2BGR, frame)
                bytesPerLine = 3 * width
                QImg = QImage(frame.data, width, height, bytesPerLine,
                              QImage.Format_RGB888)
                pix = QPixmap.fromImage(QImg)
                self.ui.displayLabel.setPixmap(pix)
                self._write_logs_to_plain_text('Read Video done.')
                self.ui.startPushButton.setEnabled(True)
                self.ui.progressBar.setEnabled(True)
                self.ui.redrawPushButton.setEnabled(True)
                self._fresh_progresssBar()
                self._set_img_ratio(frame.shape)
                self.ui.displayLabel.setNewFrames()
                self.ui.displayLabel.setdrawDoneStatus(self.cur_img.copy(),
                                                       self.img_scale_ratio)

    def start_tracking(self):

        if self.stopEvent.is_set():
            self.stopEvent.clear()

        if self.ui.startPushButton.text() != 'Start':
            if self.before_frame != 0:
                self.cur_frames = self.before_frame

            self.tracker_res = self.tracker_res[:self.cur_frames + 1]
            self.ui.progressBar.setValue(
                int(self.cur_frames / self.total_frames * 100))
            if draw_state.draw_done:
                x0, y0, x1, y1 = self.ui.displayLabel.return_x_y()
            else:
                x0, y0, x1, y1 = self.tracker_res[self.cur_frames][1:-1]

            self.tracker_res.pop()
            self._write_logs_to_plain_text("re-start at: " +
                                           self._coord_to_text(x0, y0))
            self._write_logs_to_plain_text("re-start at: " +
                                           self._coord_to_text(x0, y0))
            ori_x, ori_x1 = x0 * self.img_scale_ratio[
                0], x1 * self.img_scale_ratio[0]
            ori_y, ori_y1 = y0 * self.img_scale_ratio[
                1], y1 * self.img_scale_ratio[1]
            frame_bbox = [ori_x, ori_y, ori_x1 - ori_x, ori_y1 - ori_y]
            self.tracker_res.append([self.cur_frames + 1] + frame_bbox + [2.0])
            self.frame_state = init_track(self.tracker_net, self.cur_img,
                                          frame_bbox)
            self.ui.startPushButton.setText("Start")
            self.ui.startPushButton.setEnabled(False)
            self.ui.pausPushButton.click()
        else:
            if draw_state.draw_done:
                self.ui.progressBar.setValue(0)
                x0, y0, x1, y1 = self.ui.displayLabel.return_x_y()
                self._write_logs_to_plain_text(self._coord_to_text(x0, y0))
                self._write_logs_to_plain_text(self._coord_to_text(x1, y1))
                ori_x, ori_x1 = x0 * self.img_scale_ratio[
                    0], x1 * self.img_scale_ratio[0]
                ori_y, ori_y1 = y0 * self.img_scale_ratio[
                    1], y1 * self.img_scale_ratio[1]
                frame_bbox = [ori_x, ori_y, ori_x1 - ori_x, ori_y1 - ori_y]
                self.tracker_res.append([self.cur_frames + 1] + frame_bbox +
                                        [2.0])
                self.frame_state = init_track(self.tracker_net,
                                              self.cur_img,
                                              frame_bbox,
                                              cuda_state=self.cuda_state)
                self.ui.startPushButton.setEnabled(False)
                self.ui.pausPushButton.setEnabled(True)
                self.ui.redrawPushButton.setEnabled(False)
                self.ui.stoPushButton.setEnabled(True)
                th = threading.Thread(target=self.tracking)
                th.start()
            else:
                self._write_logs_to_plain_text("Bbox undone")

    def tracking(self):
        while self.cv_cap_loader.isOpened():
            if True == self.stopEvent.is_set():
                self.stopEvent.clear()
                break
            success, frame = self.cv_cap_loader.read()
            if success:
                self.cur_frames += 1
                self.before_img = self.cur_frames
                self.cur_img = frame.copy()
                self.frame_state = SiamRPN_track(self.frame_state,
                                                 frame,
                                                 cuda_state=self.cuda_state)
                res = cxy_wh_2_rect(self.frame_state['target_pos'],
                                    self.frame_state['target_sz'])
                self.tracker_res.append([self.cur_frames + 1] + list(res) +
                                        [self.frame_state['score']])
                if self.cur_frames % 2 == 0:
                    # TODO: skip frame changes
                    height, width, bytesPerComponent = frame.shape
                    frame = rect_box(frame, res, self.frame_state['score'],
                                     self.cur_frames + 1)
                    cv2.cvtColor(frame, cv2.COLOR_RGB2BGR, frame)
                    bytesPerLine = 3 * width
                    QImg = QImage(frame.data, width, height, bytesPerLine,
                                  QImage.Format_RGB888)
                    pix = QPixmap.fromImage(QImg)
                    self.ui.displayLabel.setPixmap(pix)
            else:
                self.cv_cap_loader.release()
                self.ui.stoPushButton.click()
                # self._button_status_change(False)
                break

            if self.stopEvent.is_set() == False:
                time.sleep(0.02)

    def call_backlog(self, msg):
        self.pbar.setValue(int(msg))

    def timerEvent(self, event):
        if self.total_frames != 0:
            self._fresh_progresssBar()
            if not self.cv_cap_loader.isOpened():
                self.cur_frames = 0

    def pause_tracking(self):
        if self.ui.pausPushButton.text() == 'Pause':
            self.stopEvent.set()
            time.sleep(0.5)
            self.pause_status = True
            """ draw res """
            frame = self.cur_img.copy()
            res = self.tracker_res[self.cur_frames]
            height, width, bytesPerComponent = frame.shape
            frame = rect_box(frame, res[1:-1], res[-1], self.cur_frames + 1)
            cv2.cvtColor(frame, cv2.COLOR_RGB2BGR, frame)
            bytesPerLine = 3 * width
            QImg = QImage(frame.data, width, height, bytesPerLine,
                          QImage.Format_RGB888)
            pix = QPixmap.fromImage(QImg)
            self.ui.displayLabel.setPixmap(pix)
            """ end draw res """
            self.ui.pausPushButton.setText('Continue')
            self.ui.prePushButton.setEnabled(True)
            self.ui.nextPushButton.setEnabled(True)
            self.ui.FramesSpinBox.setEnabled(True)
            self.ui.redrawPushButton.setEnabled(True)
        else:
            self.pause_status = False
            self.ui.pausPushButton.setText('Pause')
            self.ui.FramesSpinBox.setEnabled(False)
            self.ui.prePushButton.setEnabled(False)
            self.ui.nextPushButton.setEnabled(False)
            self.ui.redrawPushButton.setEnabled(False)
            self.skip_frame = 0
            self.before_frame = 0
            self.cv_cap_loader.set(cv2.CAP_PROP_POS_FRAMES,
                                   self.cur_frames + 1)
            self.stopEvent.clear()
            th = threading.Thread(target=self.tracking)
            th.start()

    def next_tracking(self):
        frame_skip = self.move_value
        if frame_skip <= 0:
            frame_skip = 1

        if self.skip_frame == 0:
            self.skip_frame = self.cur_frames
        else:
            self.skip_frame = self.before_frame

        if self.skip_frame + frame_skip < self.total_frames:
            self.cv_cap_loader.set(cv2.CAP_PROP_POS_FRAMES,
                                   self.skip_frame + frame_skip)
            _, tmp_frame = self.cv_cap_loader.read()
            self.cur_img = tmp_frame.copy()
            res_id = self.skip_frame + frame_skip
            if res_id < self.cur_frames:
                height, width, bytesPerComponent = tmp_frame.shape
                frame = rect_box(tmp_frame, self.tracker_res[res_id][1:-1],
                                 self.tracker_res[res_id][-1], res_id + 1)
                cv2.cvtColor(frame, cv2.COLOR_RGB2BGR, frame)
                bytesPerLine = 3 * width
                QImg = QImage(frame.data, width, height, bytesPerLine,
                              QImage.Format_RGB888)
                pix = QPixmap.fromImage(QImg)
                self.ui.displayLabel.setPixmap(pix)
                self.before_frame = self.skip_frame + frame_skip
            else:
                print("undone!")
        else:
            print(" frames can't over the total videos !")

    def prev_tracking(self):
        frame_skip = self.move_value
        if frame_skip <= 0:
            frame_skip = 1

        if self.skip_frame == 0:
            self.skip_frame = self.cur_frames
        else:
            self.skip_frame = self.before_frame

        if self.skip_frame - frame_skip >= 0:
            self.cv_cap_loader.set(cv2.CAP_PROP_POS_FRAMES,
                                   self.skip_frame - frame_skip)
            _, tmp_frame = self.cv_cap_loader.read()
            self.cur_img = tmp_frame.copy()
            res_id = self.skip_frame - frame_skip
            if res_id >= 0:
                height, width, bytesPerComponent = tmp_frame.shape
                frame = rect_box(tmp_frame, self.tracker_res[res_id][1:-1],
                                 self.tracker_res[res_id][-1], res_id + 1)
                cv2.cvtColor(frame, cv2.COLOR_RGB2BGR, frame)
                bytesPerLine = 3 * width
                QImg = QImage(frame.data, width, height, bytesPerLine,
                              QImage.Format_RGB888)
                pix = QPixmap.fromImage(QImg)
                self.ui.displayLabel.setPixmap(pix)
                self.before_frame = self.skip_frame - frame_skip
        else:
            print(" frames can't less the zero !")

    def spinValueChange(self):
        self.move_value = self.ui.FramesSpinBox.value()

    def stop_tracking(self):
        if self.ui.pausPushButton.text() == 'Continue':
            self.ui.pausPushButton.setText('Pause')

        if self.cv_cap_loader.isOpened():
            self.stopEvent.set()
            self.reinit_tracker()
            self.cv_cap_loader.release()
        else:
            self.reinit_tracker()
            self._write_logs_to_plain_text("Done all videos !!")
        self._button_status_change(False, need_detect=self.detect_status)

    """ train dialog"""

    def showTrainDialog(self):
        self.train_dialog.setWindowModality(Qt.ApplicationModal)
        self.train_dialog_ui.lineEditLabelPath.setText(self.LabelFilePath)
        self.train_dialog.exec_()

    def trainDialog_openLabel(self):
        fileName_, f_type = QFileDialog.getOpenFileName(
            self, "Open Labels", self.cwd, 'All Files (*);;TXT (*.txt)')
        if fileName_ == "":
            print("no files")
            return

        if ".txt" in fileName_:
            self.LabelFilePath = fileName_
            # self.init_trackers()
            print(fileName_, f_type)
        else:
            print(fileName_, ' is wrong!')
            return

    def trainDialog_outputPath(self):
        fileName_, f_type = QFileDialog.getOpenFileName(
            self, "Out Model", self.cwd, 'All Files (*);;PTH (*.pth)')
        if fileName_ == "":
            print("no files")
            return

        if ".txt" in fileName_:
            self.outModelPath = fileName_
            # self.init_trackers()
            print(fileName_, f_type)
        else:
            print(fileName_, ' is wrong!')
            return

    def train_ok(self):
        self.train_dialog.close()

    def train_cancel(self):
        self.train_dialog.close()
コード例 #4
0
    print(text)
    if text == 'True':
        ui_main.bt_start.setText('2.全部暂停')
    else:
        ui_main.ed_log.append(text)


if __name__ == '__main__':
    dataPath = 'datas/set.pkl'
    # 自定义一个信号
    ms = log_sg = Myignals()
    # 绑定日志更新的信号
    ms.log_add.connect(log_add)
    #实例化抢购对象
    hw = PanicBuying()
    t = []  #线程容器
    driver = []  #浏览器容器
    start = False  #全局暂停和开始的开关
    close_all = False
    app = QApplication(sys.argv)
    window_main = QMainWindow()  # 主界面
    ui_main = Ui_MainWindow()  # 实例化
    ui_main.setupUi(window_main)  # 运行里面的代码
    init_window_main()  # 初始化和对接代码功能
    with open('datas\main.qss', 'r') as f:
        style = f.read()
    window_main.setStyleSheet(style)

    window_main.show()
    sys.exit(app.exec_())
コード例 #5
0
ファイル: main.py プロジェクト: Fairbrook/proyecto-SBD
class MainWindow(QMainWindow):
    showMessageBox = Signal(str)
    exitThread = Signal()

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

        # modelos
        self.editorial = Editorial()
        self.genero = Genero()
        self.autor = Autor()
        self.libro = Libro()
        self.sucursal = Sucursal()
        self.supervisor = Supervisor()
        self.empleado = Empleado()
        self.venta = Compra()
        self.existencia = LibroSucursal()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.exit = False
        self.showMessageBox.connect(self.onNotify)
        self.exitThread.connect(self.customExit)
        self.canExit = False

        self.worker = Worker(self, 'existencias')
        self.thread = QThread()
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker._listener)
        self.thread.start()

        # connections
        self.ui.push_editorial_nuevo.clicked.connect(self.onEditorialNuevo)
        self.ui.push_editorial_mostrar.clicked.connect(self.onEditorialMostrar)
        self.ui.push_editorial_eliminar.clicked.connect(
            self.onEditorialEliminar)
        self.ui.push_editorial_buscar.clicked.connect(self.onEditorialBuscar)

        self.ui.push_genero_mostrar.clicked.connect(self.onGeneroMostrar)
        self.ui.push_genero_guardar.clicked.connect(self.onGeneroGuardar)
        self.ui.push_genero_eliminar.clicked.connect(self.onGeneroEliminar)
        self.ui.push_genero_buscar.clicked.connect(self.onGeneroBuscar)

        self.ui.push_autor_mostrar.clicked.connect(self.onAutorMostrar)
        self.ui.push_autor_guardar.clicked.connect(self.onAutorGuardar)
        self.ui.push_autor_eliminar.clicked.connect(self.onAutorEliminar)
        self.ui.push_autor_buscar.clicked.connect(self.onAutorBuscar)

        self.ui.push_libro_nuevo.clicked.connect(self.onLibroNuevo)
        self.ui.push_libro_mostrar.clicked.connect(self.onLibroMostrar)
        self.ui.push_libro_eliminar.clicked.connect(self.onLibroEliminar)
        self.ui.push_libro_buscar.clicked.connect(self.onLibroBuscar)

        self.ui.push_sucursal_nuevo.clicked.connect(self.onSucursalNuevo)
        self.ui.push_sucursal_mostrar.clicked.connect(self.onSucursalMostrar)
        self.ui.push_sucursal_eliminar.clicked.connect(self.onSucursalEliminar)
        self.ui.push_sucursal_buscar.clicked.connect(self.onSucursalBuscar)
        self.ui.push_sucursal_inactiva.clicked.connect(self.onSucursalInactiva)

        self.ui.push_empleado_nuevo.clicked.connect(self.onEmpleadoNuevo)
        self.ui.push_empleado_mostrar.clicked.connect(self.onEmpleadoMostrar)
        self.ui.push_empleado_eliminar.clicked.connect(self.onEmpleadoEliminar)
        self.ui.push_empleado_buscar.clicked.connect(self.onEmpleadoBuscar)
        self.ui.push_supervisor_mostrar.clicked.connect(
            self.onSupervisorMostrar)
        self.ui.push_empleado_inactivos.clicked.connect(
            self.onEmpleadoInactivo)

        self.ui.push_venta_nuevo.clicked.connect(self.onVentaNuevo)
        self.ui.push_venta_mostrar.clicked.connect(self.onVentaMostrar)
        self.ui.push_venta_eliminar.clicked.connect(self.onVentaEliminar)
        self.ui.push_venta_buscar.clicked.connect(self.onVentaBuscar)

        self.ui.push_existencia_nuevo.clicked.connect(self.onExistenciaNuevo)
        self.ui.push_existencia_mostrar.clicked.connect(
            self.onExistenciaMostrar)
        self.ui.push_existencia_buscar.clicked.connect(self.onExistenciaBuscar)

        # double clicks
        self.ui.table_libro.doubleClicked.connect(self.onLibroEdit)
        self.ui.table_editorial.doubleClicked.connect(self.onEditorialEdit)
        self.ui.table_existencia.doubleClicked.connect(self.onExistenciaEdit)
        self.ui.table_empleado.doubleClicked.connect(self.onEmpleadoEdit)
        self.ui.table_sucursal.doubleClicked.connect(self.onSucursalEdit)
        self.ui.table_venta.doubleClicked.connect(self.onVentaEdit)

        # no edit
        self.ui.table_editorial.setEditTriggers(
            QAbstractItemView.NoEditTriggers)
        self.ui.table_libro.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.ui.table_existencia.setEditTriggers(
            QAbstractItemView.NoEditTriggers)
        self.ui.table_empleado.setEditTriggers(
            QAbstractItemView.NoEditTriggers)
        self.ui.table_venta.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.ui.table_sucursal.setEditTriggers(
            QAbstractItemView.NoEditTriggers)

        # edit
        self.ui.table_autor.itemChanged.connect(self.onAutorChange)
        self.ui.table_genero.itemChanged.connect(self.onGeneroChange)

        self.onEditorialMostrar()
        self.onLibroMostrar()
        self.onExistenciaMostrar()
        self.onAutorMostrar()
        self.onEmpleadoMostrar()
        self.onGeneroMostrar()
        self.onVentaMostrar()
        self.onSucursalMostrar()

    # Nuevo
    @Slot()
    def onEditorialNuevo(self):
        editorial = EditorialWindow()
        editorial.exec_()
        self.onEditorialMostrar()

    @Slot()
    def onLibroNuevo(self):
        libro = LibroWindow()
        libro.exec_()
        self.onLibroMostrar()

    @Slot()
    def onSucursalNuevo(self):
        sucursal = SucursalWindow()
        sucursal.exec_()
        self.onSucursalMostrar()

    @Slot()
    def onSupervisorNuevo(self):
        supervisor = SupervisorWindow()
        supervisor.exec_()
        self.onSupervisorMostrar()

    @Slot()
    def onEmpleadoNuevo(self):
        empleado = EmpleadoWindow()
        empleado.exec_()
        self.onEmpleadoMostrar()

    @Slot()
    def onVentaNuevo(self):
        venta = VentaWindow()
        venta.exec_()
        self.onVentaMostrar()

    @Slot()
    def onExistenciaNuevo(self):
        venta = ExistenciaWindow()
        venta.exec_()
        self.onExistenciaMostrar()

    @Slot()
    def onGeneroGuardar(self):
        tipo = self.ui.edit_genero_nuevo.text()
        cat = Genero(tipo)
        cat.save()
        self.ui.edit_genero_nuevo.clear()
        self.onGeneroMostrar()

    @Slot()
    def onAutorGuardar(self):
        nombre = self.ui.edit_autor_guardar.text()
        autor = Autor(nombre)
        autor.save()
        self.ui.edit_autor_guardar.clear()
        self.onAutorMostrar()

    # mostrar
    @Slot()
    def onEditorialMostrar(self):
        self.editoriales = self.editorial.getAll()
        self.setEditoriales()

    def setEditoriales(self):
        headers = ['Nombre', 'Pais']
        self.ui.table_editorial.setRowCount(len(self.editoriales))
        self.ui.table_editorial.setColumnCount(len(headers))
        self.ui.table_editorial.setHorizontalHeaderLabels(headers)
        for row, editorial in enumerate(self.editoriales):
            self.ui.table_editorial.setItem(
                row, 0, QTableWidgetItem(editorial['nombre']))
            self.ui.table_editorial.setItem(
                row, 1, QTableWidgetItem(editorial['paisorigen']))

    @Slot()
    def onGeneroMostrar(self):
        allGenero = self.genero.getAll()
        self.generos = allGenero
        self.setGeneros()

    def setGeneros(self):
        headers = ['Tipo']
        self.ui.table_genero.setRowCount(len(self.generos))
        self.ui.table_genero.setColumnCount(len(headers))
        self.ui.table_genero.setHorizontalHeaderLabels(headers)
        for row, categoria in enumerate(self.generos):
            self.ui.table_genero.setItem(row, 0,
                                         QTableWidgetItem(categoria['tipo']))

    @Slot()
    def onAutorMostrar(self):
        all = self.autor.getAll()
        self.autores = all
        self.setAutores()

    def setAutores(self):
        headers = ['Nombre']
        self.ui.table_autor.setRowCount(len(self.autores))
        self.ui.table_autor.setColumnCount(len(headers))
        self.ui.table_autor.setHorizontalHeaderLabels(headers)
        for row, categoria in enumerate(self.autores):
            self.ui.table_autor.setItem(row, 0,
                                        QTableWidgetItem(categoria['nombre']))

    @Slot()
    def onLibroMostrar(self):
        self.libros = self.libro.getAll()
        self.setLibros()

    def setLibros(self):
        headers = [
            'Codigo', 'Titulo', 'Precio', 'ISBN', 'Idioma', 'Encuadernacion',
            'Publicación', 'Editorial', 'Autor', 'Genero'
        ]
        self.ui.table_libro.setRowCount(len(self.libros))
        self.ui.table_libro.setColumnCount(len(headers))
        self.ui.table_libro.setHorizontalHeaderLabels(headers)
        for row, libro in enumerate(self.libros):
            self.ui.table_libro.setItem(row, 0,
                                        QTableWidgetItem(str(libro['codigo'])))
            self.ui.table_libro.setItem(row, 1,
                                        QTableWidgetItem(libro['titulo']))
            self.ui.table_libro.setItem(row, 2,
                                        QTableWidgetItem(str(libro['precio'])))
            self.ui.table_libro.setItem(row, 3,
                                        QTableWidgetItem(libro['isbn']))
            self.ui.table_libro.setItem(row, 4,
                                        QTableWidgetItem(libro['idioma']))
            self.ui.table_libro.setItem(
                row, 5, QTableWidgetItem(libro['encuadernacion']))
            self.ui.table_libro.setItem(
                row, 6, QTableWidgetItem(str(libro['publicacion'])))
            self.ui.table_libro.setItem(row, 7,
                                        QTableWidgetItem(libro['editorial']))
            self.ui.table_libro.setItem(row, 8,
                                        QTableWidgetItem(libro['autor']))
            self.ui.table_libro.setItem(row, 9,
                                        QTableWidgetItem(libro['genero']))

    @Slot()
    def onSucursalMostrar(self):
        all = self.sucursal.getAll()
        self.sucursales = all
        self.setSucursales()

    @Slot()
    def onSucursalInactiva(self):
        all = self.sucursal.getInactivos()
        self.sucursales = all
        self.setSucursales()

    def setSucursales(self):
        headers = ['Nombre', 'Direccion', 'Telefono']
        self.ui.table_sucursal.setRowCount(len(self.sucursales))
        self.ui.table_sucursal.setColumnCount(len(headers))
        self.ui.table_sucursal.setHorizontalHeaderLabels(headers)
        for row, sucursal in enumerate(self.sucursales):
            self.ui.table_sucursal.setItem(
                row, 0, QTableWidgetItem(sucursal['nombre']))
            self.ui.table_sucursal.setItem(
                row, 1, QTableWidgetItem(sucursal['direccion']))
            self.ui.table_sucursal.setItem(
                row, 2, QTableWidgetItem(str(sucursal['telefono'])))

    @Slot()
    def onSupervisorMostrar(self):
        all = self.supervisor.getAll()
        self.empleados = all
        self.setEmpleados()

    @Slot()
    def onEmpleadoMostrar(self):
        all = self.empleado.getAll()
        self.empleados = all
        self.setEmpleados()

    @Slot()
    def onEmpleadoInactivo(self):
        all = self.empleado.getInactivos()
        self.empleados = all
        self.setEmpleados()

    def setEmpleados(self):
        headers = [
            'Código', 'Nombre', 'Telefono', 'Tipo', 'Supervisor', 'Direccion',
            'Sucursal', 'Activo'
        ]
        self.ui.table_empleado.setRowCount(len(self.empleados))
        self.ui.table_empleado.setColumnCount(len(headers))
        self.ui.table_empleado.setHorizontalHeaderLabels(headers)
        for row, empleado in enumerate(self.empleados):
            self.ui.table_empleado.setItem(
                row, 0, QTableWidgetItem(str(empleado['codigo'])))
            self.ui.table_empleado.setItem(
                row, 1, QTableWidgetItem(empleado['nombre']))
            self.ui.table_empleado.setItem(
                row, 2, QTableWidgetItem(empleado['telefono']))
            self.ui.table_empleado.setItem(row, 3,
                                           QTableWidgetItem(empleado['tipo']))
            self.ui.table_empleado.setItem(
                row, 4, QTableWidgetItem(empleado['supervisor']))
            self.ui.table_empleado.setItem(
                row, 5, QTableWidgetItem(empleado['direccion']))
            self.ui.table_empleado.setItem(
                row, 6, QTableWidgetItem(empleado['sucursal']))
            self.ui.table_empleado.setItem(
                row, 7, QTableWidgetItem(str(empleado['activo'])))

    @Slot()
    def onVentaMostrar(self):
        all = self.venta.getAll()
        self.ventas = all
        self.setVentas()

    def setVentas(self):
        headers = ['Folio', 'Empleado', 'Fecha', 'Total']
        self.ui.table_venta.setRowCount(len(self.ventas))
        self.ui.table_venta.setColumnCount(len(headers))
        self.ui.table_venta.setHorizontalHeaderLabels(headers)
        for row, venta in enumerate(self.ventas):
            self.ui.table_venta.setItem(row, 0,
                                        QTableWidgetItem(str(venta['folio'])))
            self.ui.table_venta.setItem(row, 1,
                                        QTableWidgetItem(venta['empleado']))
            self.ui.table_venta.setItem(
                row, 2, QTableWidgetItem(venta['fecha'].strftime('%d/%m/%Y')))
            self.ui.table_venta.setItem(row, 3,
                                        QTableWidgetItem(str(venta['total'])))

    @Slot()
    def onExistenciaMostrar(self):
        all = self.existencia.getAll()
        self.existencias = all
        self.setExistencias()

    def setExistencias(self):
        headers = ['Libro', 'Sucursal', 'Existencia']
        self.ui.table_existencia.setRowCount(len(self.existencias))
        self.ui.table_existencia.setColumnCount(len(headers))
        self.ui.table_existencia.setHorizontalHeaderLabels(headers)
        for row, existencia in enumerate(self.existencias):
            self.ui.table_existencia.setItem(
                row, 0, QTableWidgetItem(existencia['libro']))
            self.ui.table_existencia.setItem(
                row, 1, QTableWidgetItem(existencia['sucursal']))
            self.ui.table_existencia.setItem(
                row, 2, QTableWidgetItem(str(existencia['existencia'])))

    # Edit functions
    @Slot()
    def onLibroEdit(self, item):
        window = LibroWindow(self.libros[item.row()])
        window.exec_()
        self.onLibroMostrar()

    @Slot()
    def onVentaEdit(self, item):
        window = VentaDetallesWindow(self.ventas[item.row()])
        window.exec_()

    @Slot()
    def onEditorialEdit(self, item):
        window = EditorialWindow(self.editoriales[item.row()])
        window.exec_()
        self.onEditorialMostrar()

    @Slot()
    def onExistenciaEdit(self, item):
        window = ExistenciaWindow(self.existencias[item.row()])
        window.exec_()
        self.onExistenciaMostrar()

    @Slot()
    def onAutorChange(self, item):
        autor = Autor(nombre=self.autores[item.row()]['nombre'],
                      codigo=self.autores[item.row()]['codigo'])
        if autor.nombre != item.text():
            autor.nombre = item.text()
            autor.update()
            self.onAutorMostrar()

    @Slot()
    def onEmpleadoEdit(self, item):
        window = EmpleadoWindow(self.empleados[item.row()])
        window.exec_()
        self.onEmpleadoMostrar()

    @Slot()
    def onSucursalEdit(self, item):
        window = SucursalWindow(self.sucursales[item.row()])
        window.exec_()
        self.onSucursalMostrar()

    @Slot()
    def onGeneroChange(self, item):
        genero = Genero(self.generos[item.row()]['tipo'])
        if genero.tipo != item.text():
            genero.tipo = item.text()
            genero.update()
            self.onGeneroMostrar()

    # eliminar
    @Slot()
    def onSucursalEliminar(self):
        for item in self.ui.table_sucursal.selectedIndexes():
            nombre = self.sucursales[item.row()]['nombre']
            Sucursal(nombre=nombre).delete()
        self.onSucursalMostrar()

    @Slot()
    def onLibroEliminar(self):
        for item in self.ui.table_libro.selectedIndexes():
            try:
                codigo = self.libros[item.row()]['codigo']
                Libro(codigo=codigo).delete()
            except ForeignKeyViolation:
                QMessageBox.warning(
                    self, "Atención",
                    f'El libro con codigo "{codigo}" no puede eliminarse')
        self.onAutorMostrar()

    @Slot()
    def onAutorEliminar(self):
        for item in self.ui.table_autor.selectedIndexes():
            try:
                nombre = self.autores[item.row()]['nombre']
                Autor(codigo=self.autores[item.row()]['codigo']).delete()
            except ForeignKeyViolation:
                QMessageBox.warning(
                    self, "Atención",
                    f'El autor "{nombre}" no puede eliminarse')
        self.onAutorMostrar()

    @Slot()
    def onGeneroEliminar(self):
        for item in self.ui.table_genero.selectedIndexes():
            try:
                tipo = self.generos[item.row()]['tipo']
                Genero(tipo=tipo).delete()
            except ForeignKeyViolation:
                QMessageBox.warning(self, "Atención",
                                    f'El genero "{tipo}" no puede eliminarse')
        self.onGeneroMostrar()

    @Slot()
    def onEditorialEliminar(self):
        for item in self.ui.table_editorial.selectedIndexes():
            try:
                nombre = self.editoriales[item.row()]['nombre']
                Editorial(nombre=nombre).delete()
            except ForeignKeyViolation:
                QMessageBox.warning(
                    self, "Atención",
                    f'La editorial "{nombre}" no puede eliminarse')
        self.onEditorialMostrar()

    @Slot()
    def onVentaEliminar(self):
        for item in self.ui.table_venta.selectedIndexes():
            compra = Compra()
            compra.folio = self.ventas[item.row()]['folio']
            compra.delete()
        self.onVentaMostrar()

    @Slot()
    def onEmpleadoEliminar(self):
        for item in self.ui.table_empleado.selectedIndexes():
            empleado = Empleado()
            empleado._key = self.empleados[item.row()]['codigo']
            try:
                empleado.delete()
                self.onEmpleadoMostrar()
            except ForeignKeyViolation:
                QMessageBox.warning(
                    self, "Atención",
                    f'El empleado "{empleado._key}" no puede eliminarse')
        self.onEmpleadoMostrar()

    # Buscar
    @Slot()
    def onVentaBuscar(self):
        self.ventas = self.venta.search(
            self.ui.date_venta_buscar.date().toPython())
        self.setVentas()

    @Slot()
    def onExistenciaBuscar(self):
        self.existencias = self.existencia.search(
            self.ui.edit_existencia_buscar.text())
        self.setExistencias()

    @Slot()
    def onGeneroBuscar(self):
        self.generos = self.genero.search(self.ui.edit_genero_buscar.text())
        self.setGeneros()

    @Slot()
    def onAutorBuscar(self):
        self.autores = self.autor.search(self.ui.edit_autor_buscar.text())
        self.setAutores()

    @Slot()
    def onEditorialBuscar(self):
        self.editoriales = self.editorial.search(
            self.ui.edit_editorial_buscar.text())
        self.setEditoriales()

    @Slot()
    def onLibroBuscar(self):
        self.libros = self.libro.search(self.ui.edit_libro_buscar.text())
        self.setLibros()

    @Slot()
    def onSucursalBuscar(self):
        self.sucursales = self.sucursal.search(
            self.ui.edit_sucursal_buscar.text())
        self.setSucursales()

    @Slot()
    def onEmpleadoBuscar(self):
        self.empleados = self.empleado.search(
            self.ui.edit_empleado_buscar.text())
        self.setEmpleados()

    #notify
    @Slot(str)
    def onNotify(self, data):
        QMessageBox.warning(self, "Atención", data)

    @Slot()
    def customExit(self):
        self.canExit = True
        self.close()

    def closeEvent(self, event):
        self.exit = True
        if self.canExit == True:
            self.thread.terminate()
            event.accept()
        else:
            event.ignore()