def wybor(self):
        poz_lista = [
            'Wykaz narzędzi ',
            "SELECT * FROM ",
            'Baza nie zawiera żadnych pozycji. Plik nie zostanie zapisany.',
        ]

        lista_poz = []
        lista_poz.append('Brak')
        from narzedzia_poz import naglowki
        for i in naglowki():
            if "/" in i[0]:
                lista_poz.append(i[0])
        inp = QInputDialog(self)
        inp.setWhatsThis('Wybierz pozycję aby eksportować do pliku')
        inp.setLabelText('Wybierz pozycję:')
        inp.setWindowTitle('Pozycje')
        inp.setComboBoxItems(lista_poz)
        inp.setCancelButtonText('Anuluj')

        if inp.exec_() == QDialog.Accepted:
            print(inp.textValue())
            poz_lista[0] += inp.textValue()
            poz_lista[1] += "'" + inp.textValue() + "'"
            if inp.textValue() != 'Brak':
                self.export(poz_lista)
                self.statusBar().showMessage(
                    "Wyeksportowano do pliku", 10000)
            else:
                QMessageBox.critical(self, 'Wybierz pozycję',
                                     'Nie wybrano żadnej pozycji!',
                                     QMessageBox.Ok,
                                     QMessageBox.Ok)
Exemple #2
0
 def slot_set_robot_id(self):
     self.parent().releaseKeyboard()
     dialog = QInputDialog(self)
     dialog.setModal(True)
     dialog.setStyleSheet("""
     background-color: rgba(0, 0, 0, 200);
     border:1px solid rgba(0, 200, 200, 150);
     """)
     dialog.setFixedSize(350, 250)
     dialog.setWindowTitle('Set Input Flow for Improcessor')
     dialog.setInputMode(QInputDialog.TextInput)
     dialog.setLabelText('请输入……(机器人的ID)')
     dialog.setTextValue('7')
     dialog.setOkButtonText('Ok')
     dialog.setCancelButtonText('Cancel')
     if dialog.exec_() == QDialog.Accepted:
         id = dialog.textValue()
         if self.mRobot:
             self.mRobot.mId = int(id)
             self.deleteOptionList(0)
             self.insertOptionList(
                 '%s [ID: %d]' % (self.mRobot.client_addr, self.mRobot.mId),
                 self.defaultFunc, 0)
             self.parent().grabKeyboard()
             self.signalFocusedChanged.emit(self, True)
     else:
         print("dialog canceled")
     dialog.show()
Exemple #3
0
 def getEDID(self):
     pwdInputDialog = QInputDialog()
     pwdInputDialog.setFixedSize(250, 150)
     pwdInputDialog.setWindowTitle('权限申请')
     pwdInputDialog.setLabelText('请输入root账户密码:')
     pwdInputDialog.setOkButtonText('确认')
     pwdInputDialog.setCancelButtonText('取消')
     pwdInputDialog.setTextEchoMode(QLineEdit.Password)
     pwdInputDialog.setInputMode(QInputDialog.TextInput)
     okPressed = pwdInputDialog.exec_()
     pwd = pwdInputDialog.textValue()
     if okPressed and pwd != '':
         os.system('echo ' + pwd + ' | sudo -S get-edid > edid.bin')
         edidFile = open('edid.bin', 'rb')
         self.edidBytes = edidFile.read()
         edidFile.close()
         os.remove('edid.bin')
     else:
         messageBox = QMessageBox()
         messageBox.setWindowTitle('警告')
         messageBox.setText('获取屏幕信息需要root权限, 请正确输入密码!')
         messageBox.addButton(QMessageBox.Yes)
         buttonY = messageBox.button(QMessageBox.Yes)
         buttonY.setText('确定')
         messageBox.exec_()
Exemple #4
0
    def slot_add_EPuck(self):
        dialog = QInputDialog(self)
        dialog.setModal(True)
        dialog.setStyleSheet("""
        background-color: rgba(0, 0, 0, 200);
        border:1px solid rgba(0, 200, 200, 150);
        """)
        dialog.setFixedSize(350, 250)
        dialog.setWindowTitle('Set Input Flow for Improcessor')
        dialog.setInputMode(QInputDialog.TextInput)
        dialog.setLabelText('请输入……(机器人的ip)')
        dialog.setTextValue('192.168.3.5')
        dialog.setOkButtonText('Ok')
        dialog.setCancelButtonText('Cancel')
        if dialog.exec_() == QDialog.Accepted:
            ip = dialog.textValue()
            robot_controller = MainController.getController().mRobotController

            robot_controller.addRobot(RobotEpuck)
            robot = robot_controller.getRobot(-1)
            robot.connect(ip)
            view = RobotFrame(self)
            view.setRobot(robot)
            self.addSubview(view)
        else:
            print("dialog canceled")
        dialog.show()
 def chooseterm(self):
     inputdialog = QInputDialog(self)
     inputdialog.setIntRange(100000, 999999)
     inputdialog.setIntValue(201701)
     inputdialog.setWindowTitle('学期')
     inputdialog.setLabelText('输入学期(如201701):')
     inputdialog.setOkButtonText('确定')
     inputdialog.setCancelButtonText('取消')
     inputdialog.setWindowOpacity(0.7)
     ok = inputdialog.exec_()
     if ok:
         self.termValueLabel.setText(str(inputdialog.intValue()))
Exemple #6
0
 def chooseterm(self):
     inputdialog = QInputDialog(self)
     items = [
         '大一上期', '大一下期', '大二上期', '大二下期', '大三上期', '大三下期', '大四上期', '大四下期'
     ]
     inputdialog.setComboBoxItems(items)
     inputdialog.setWindowTitle('学期')
     inputdialog.setLabelText('选择学期:')
     inputdialog.setOkButtonText('确定')
     inputdialog.setCancelButtonText('取消')
     inputdialog.setWindowOpacity(0.7)
     ok = inputdialog.exec_()
     if ok:
         self.termValueLabel.setText(str(inputdialog.textValue()))
	def getText(self,matdata):
		inputBox=QInputDialog()
		inputBox.setInputMode(0)
		inputBox.setWindowTitle('MatFileKeyInputDialog')
		itemlist=list()
		for key in matdata.keys():
			itemlist.append(key)
		inputBox.setComboBoxItems(itemlist)
		inputBox.setComboBoxEditable(False)
		inputBox.setLabelText('Please Input MatFile Key')
		inputBox.setOkButtonText(u'Ok')
		inputBox.setCancelButtonText(u'Cancel')
		if inputBox.exec_() and inputBox.textValue()!='':
			return inputBox.textValue()
Exemple #8
0
def ask_root_password(context: ApplicationContext, i18n: I18n, app_config: dict = None) -> Tuple[str, bool]:

    cur_config = read_config() if not app_config else app_config
    store_password = bool(cur_config['store_root_password'])

    if store_password and context.root_password and validate_password(context.root_password):
        return context.root_password, True

    diag = QInputDialog()
    diag.setStyleSheet("""QLineEdit {  border-radius: 5px; font-size: 16px; border: 1px solid lightblue }""")
    diag.setInputMode(QInputDialog.TextInput)
    diag.setTextEchoMode(QLineEdit.Password)
    diag.setWindowIcon(util.get_default_icon()[1])
    diag.setWindowTitle(i18n['popup.root.title'])
    diag.setLabelText('')
    diag.setOkButtonText(i18n['popup.root.continue'].capitalize())
    diag.setCancelButtonText(i18n['popup.button.cancel'].capitalize())
    diag.resize(400, 200)

    for attempt in range(3):

        ok = diag.exec_()

        if ok:
            if not validate_password(diag.textValue()):

                body = i18n['popup.root.bad_password.body']

                if attempt == 2:
                    body += '. ' + i18n['popup.root.bad_password.last_try']

                show_message(title=i18n['popup.root.bad_password.title'],
                             body=body,
                             type_=MessageType.ERROR)
                ok = False
                diag.setTextValue('')

            if ok:
                if store_password:
                    context.root_password = diag.textValue()

                return diag.textValue(), ok
        else:
            break

    return '', False
Exemple #9
0
def ask_root_password(locale_keys: dict):

    dialog_pwd = QInputDialog()
    dialog_pwd.setInputMode(QInputDialog.TextInput)
    dialog_pwd.setTextEchoMode(QLineEdit.Password)
    dialog_pwd.setWindowTitle(locale_keys['popup.root.title'])
    dialog_pwd.setLabelText(locale_keys['popup.root.password'] + ':')
    dialog_pwd.setCancelButtonText(locale_keys['popup.button.cancel'])
    dialog_pwd.resize(400, 200)

    ok = dialog_pwd.exec_()

    if ok:
        if not validate_password(dialog_pwd.textValue()):
            show_error(title=locale_keys['popup.root.bad_password.title'],
                       body=locale_keys['popup.root.bad_password.body'])
            ok = False

    return dialog_pwd.textValue(), ok
Exemple #10
0
def ask_root_password(locale_keys: dict):

    diag = QInputDialog()
    diag.setInputMode(QInputDialog.TextInput)
    diag.setTextEchoMode(QLineEdit.Password)
    diag.setWindowIcon(QIcon(resource.get_path('img/lock.svg')))
    diag.setWindowTitle(locale_keys['popup.root.title'])
    diag.setLabelText(locale_keys['popup.root.password'] + ':')
    diag.setCancelButtonText(locale_keys['popup.button.cancel'])
    diag.resize(400, 200)

    ok = diag.exec_()

    if ok:
        if not validate_password(diag.textValue()):
            show_message(title=locale_keys['popup.root.bad_password.title'],
                         body=locale_keys['popup.root.bad_password.body'],
                         type_=MessageType.ERROR)
            ok = False

    return diag.textValue(), ok
Exemple #11
0
 def handle_action_save_theory_data(self):
     """Save theory data of current theory"""
     th = self.current_theory
     if th:
         # file browser window
         dir_start = "data/"
         dilogue_name = "Select Folder"
         folder = QFileDialog.getExistingDirectory(self, dilogue_name, dir_start)
         if os.path.isdir(folder):
             dialog = QInputDialog(self)
             dialog.setWindowTitle('Add label to filename(s)?')
             dialog.setLabelText('Add the following text to each saved theory filename(s):')
             dialog.setTextValue('')
             dialog.setCancelButtonText('None')
             if dialog.exec():
                 txt = dialog.textValue()
                 if txt != '':
                     txt = '_' + txt
             else:
                 txt = ''
             self.theories[th].do_save(folder, txt)
Exemple #12
0
 def on_image_save_dir_set(self):
     dialog = QInputDialog()
     dialog.setModal(True)
     dialog.setStyleSheet("""
     background-color: rgba(0, 0, 0, 200);
     border:1px solid rgba(0, 200, 200, 150);
     color:rgb(255, 255, 255);
     """)
     dialog.setFixedSize(350, 250)
     dialog.setWindowTitle('Set save dir')
     dialog.setInputMode(QInputDialog.TextInput)
     dialog.setLabelText('请输入……(保存路径)')
     dialog.setTextValue('./general_image_save')
     dialog.setOkButtonText('Ok')
     dialog.setCancelButtonText('Cancel')
     if dialog.exec_() == QDialog.Accepted:
         self.mImageSaveDir = dialog.textValue()
         self.mImageHandle.setImageSaveDir(self.mImageSaveDir)
     else:
         print("dialog canceled")
     dialog.show()
Exemple #13
0
 def slot_add_multi_robots_view(self):
     dialog = QInputDialog(self)
     dialog.setModal(True)
     dialog.setStyleSheet("""
     background-color: rgba(0, 0, 0, 200);
     border:1px solid rgba(0, 200, 200, 150);
     """)
     dialog.setFixedSize(350, 250)
     dialog.setWindowTitle('Set config file path')
     dialog.setInputMode(QInputDialog.TextInput)
     dialog.setLabelText('配置文件地址')
     dialog.setTextValue('./multi_robot_config.conf')
     dialog.setOkButtonText('Ok')
     dialog.setCancelButtonText('Cancel')
     if dialog.exec_() == QDialog.Accepted:
         config_path = dialog.textValue()
         view = MultiRobotControlFrame(self)
         view.loadConfigFile(config_path)
         self.addSubview(view)
     else:
         print("dialog canceled")
     dialog.show()
Exemple #14
0
def ask_root_password(i18n: I18n):
    diag = QInputDialog()
    diag.setStyleSheet(
        """QLineEdit {  border-radius: 5px; font-size: 16px; border: 1px solid lightblue }"""
    )
    diag.setInputMode(QInputDialog.TextInput)
    diag.setTextEchoMode(QLineEdit.Password)
    diag.setWindowIcon(QIcon(resource.get_path('img/lock.png')))
    diag.setWindowTitle(i18n['popup.root.title'])
    diag.setLabelText('')
    diag.setOkButtonText(i18n['popup.root.continue'].capitalize())
    diag.setCancelButtonText(i18n['popup.button.cancel'].capitalize())
    diag.resize(400, 200)

    for attempt in range(3):

        ok = diag.exec_()

        if ok:
            if not validate_password(diag.textValue()):

                body = i18n['popup.root.bad_password.body']

                if attempt == 2:
                    body += '. ' + i18n['popup.root.bad_password.last_try']

                show_message(title=i18n['popup.root.bad_password.title'],
                             body=body,
                             type_=MessageType.ERROR)
                ok = False
                diag.setTextValue('')

            if ok:
                return diag.textValue(), ok
        else:
            break

    return '', False
Exemple #15
0
 def handle_action_save_theory_data(self):
     """Save theory data of current theory"""
     th = self.current_theory
     if th:
         # file browser window
         dir_start = join(RepTate.root_dir, "data")
         dilogue_name = "Select Folder"
         folder = QFileDialog.getExistingDirectory(self, dilogue_name,
                                                   dir_start)
         if isdir(folder):
             dialog = QInputDialog(self)
             dialog.setWindowTitle("Add label to filename(s)?")
             dialog.setLabelText(
                 "Add the following text to each saved theory filename(s):")
             dialog.setTextValue("")
             dialog.setCancelButtonText("None")
             if dialog.exec():
                 txt = dialog.textValue()
                 if txt != "":
                     txt = "_" + txt
             else:
                 txt = ""
             self.theories[th].do_save(folder, txt)
Exemple #16
0
 def _click(self, event):
     if self._hexpass:
         self.note_win = Note(self, hexpass=self._hexpass)
     else:
         qid = QInputDialog(self)
         qid.setWindowIcon(QIcon(OPEN_PIXMAP))
         qid.setWindowTitle(self.lang['pass_title'])
         qid.setOkButtonText(self.lang['ok_button'])
         qid.setCancelButtonText(self.lang['pass_cancel_button'])
         if 'note' in self.conf:
             qid.setLabelText(self.lang['pass_text'])
             qid.setTextEchoMode(QLineEdit.Password)
         else:
             qid.setLabelText(self.lang['create_pass_text'])
         if qid.exec() == QInputDialog.Accepted:
             text = qid.textValue()
             if text:
                 self.note_win = Note(self, text)
                 if self._session:
                     self._hexpass = self.note_win.cip.hexpass
                     self._start_timer()
             else:
                 self.show_pass_error(True)
Exemple #17
0
 def _add(self, checked):
     id = QInputDialog(self)
     id.setWindowIcon(QIcon(HELP))
     id.setWindowTitle(self.lang['input_title'])
     id.setLabelText(self.lang['input_text'])
     id.setTextValue('s.vomine.ru:25565')
     id.setOkButtonText(self.lang['input_ok_button'])
     id.setCancelButtonText(self.lang['input_cancel_button'])
     if id.exec() == QInputDialog.Accepted:
         text = id.textValue()
         if not text or len(text.split(':')) != 2 \
                 or not text.split(':')[1].isdigit():
             self._show_error()
         else:
             self.main.servers.append(text)
             self.main.widget_manager.config.config[
                 self.main.info.NAME]['servers'] = json.dumps(
                     self.main.servers)
             self.main.widget_manager.config.save()
             self.main._list_fill()
             self._list_fill()
             self.__change_enabeld()
             self.list.setCurrentRow(self.list.count() - 1)
Exemple #18
0
def ask_root_password(context: ApplicationContext,
                      i18n: I18n,
                      app_config: dict = None) -> Tuple[str, bool]:

    cur_config = read_config() if not app_config else app_config
    store_password = bool(cur_config['store_root_password'])

    if store_password and context.root_password and validate_password(
            context.root_password):
        return context.root_password, True

    diag = QInputDialog(flags=Qt.CustomizeWindowHint | Qt.WindowTitleHint)
    diag.setStyleSheet(
        """QLineEdit {  border-radius: 5px; font-size: 16px; border: 1px solid lightblue }"""
    )
    diag.setInputMode(QInputDialog.TextInput)
    diag.setTextEchoMode(QLineEdit.Password)
    diag.setWindowIcon(util.get_default_icon()[1])
    diag.setWindowTitle(i18n['popup.root.title'])
    diag.setLabelText('')
    diag.setOkButtonText(i18n['popup.root.continue'].capitalize())
    diag.setCancelButtonText(i18n['popup.button.cancel'].capitalize())

    bt_box = [c for c in diag.children() if isinstance(c, QDialogButtonBox)][0]

    for bt in bt_box.buttons():
        if bt_box.buttonRole(bt) == QDialogButtonBox.AcceptRole:
            bt.setStyleSheet(css.OK_BUTTON)

        bt.setCursor(QCursor(Qt.PointingHandCursor))
        bt.setIcon(QIcon())

    diag.resize(400, 200)

    for attempt in range(3):

        ok = diag.exec_()

        if ok:
            if not validate_password(diag.textValue()):

                body = i18n['popup.root.bad_password.body']

                if attempt == 2:
                    body += '. ' + i18n['popup.root.bad_password.last_try']

                show_message(title=i18n['popup.root.bad_password.title'],
                             body=body,
                             type_=MessageType.ERROR)
                ok = False
                diag.setTextValue('')

            if ok:
                if store_password:
                    context.root_password = diag.textValue()

                return diag.textValue(), ok
        else:
            break

    return '', False
Exemple #19
0
class Ui_H_Form(object):
    def setupUi(self, H_Form):
        self.horizontalLayout = QtWidgets.QHBoxLayout(H_Form)
        self.label = QtWidgets.QLabel(H_Form)
        self.horizontalLayout.addWidget(self.label)
        self.haslo = QtWidgets.QPushButton(H_Form)
        self.horizontalLayout.addWidget(self.haslo)
        self.login = QtWidgets.QPushButton(H_Form)
        self.horizontalLayout.addWidget(self.login)
        self.usun = QtWidgets.QPushButton(H_Form)
        self.horizontalLayout.addWidget(self.usun)

        self.retranslateUi(H_Form)
        QtCore.QMetaObject.connectSlotsByName(H_Form)

        self.usun.clicked.connect(self.usun_konto)
        self.login.clicked.connect(self.zmien_login)
        self.haslo.clicked.connect(self.zmien_haslo)

    def id_uz(self):
        # ID użytkownika
        query = 'SELECT iduzytkownicy FROM uzytkownicy WHERE nazwa_uz IS ("' + str(
            self.label.text()) + '");'
        return polaczenie(query)[0]

    def retranslateUi(self, H_Form):
        _translate = QtCore.QCoreApplication.translate
        self.haslo.setText(_translate("H_Form", "Zmień hasło"))
        self.login.setText(_translate("H_Form", "Zmień login"))
        self.usun.setText(_translate("H_Form", "Usuń użytkownika"))

    def zmien_login(self):
        from PyQt5.QtWidgets import QInputDialog
        self.input_msg = QInputDialog()
        self.input_msg.setWindowIcon(QIcon('icons/cow.png'))
        self.input_msg.setWindowTitle('Zmiana loginu')
        self.input_msg.setLabelText('Wpisz nowy login:'******'Anuluj')
        id = str(self.id_uz())
        if self.input_msg.exec_():
            login = str(self.input_msg.textValue())
            query = 'UPDATE uzytkownicy SET nazwa_uz = "' + login + '" WHERE iduzytkownicy = ' + id + ';'
            polaczenie(query)

    def zmien_haslo(self):
        from PyQt5.QtWidgets import QInputDialog
        from PyQt5.QtWidgets import QLineEdit
        self.input_msgh = QInputDialog()
        self.input_msgh.setWindowIcon(QIcon('icons/cow.png'))
        self.input_msgh.setWindowTitle('Zmiana hasła')
        self.input_msgh.setLabelText('Wpisz nowe hasło:')
        self.input_msgh.setCancelButtonText('Anuluj')
        self.input_msgh.setTextEchoMode(QLineEdit.Password)
        id = str(self.id_uz())
        if self.input_msgh.exec_():
            haslo = str(self.input_msgh.textValue())
            query = 'UPDATE uzytkownicy SET haslo_uz = "' + haslo + '" WHERE iduzytkownicy = ' + id + ';'
            polaczenie(query)

    def usun_konto(self):
        from PyQt5.QtWidgets import QMessageBox
        self.msg = QMessageBox()
        self.msg.setIcon(QMessageBox.Warning)
        self.msg.setWindowIcon(QIcon('icons/cow.png'))
        self.msg.setText('Czy na pewno chcesz usunąć konto?')
        self.msg.setWindowTitle('Usuwanie konta')
        self.msg.addButton('Tak', QMessageBox.YesRole)
        self.msg.addButton('Nie', QMessageBox.NoRole)
        msg = self.msg.exec_()
        id = self.id_uz()

        if not msg:
            query = 'DELETE FROM "uzytkownicy" WHERE "iduzytkownicy" IS ("' + str(
                id) + '");'
            polaczenie(query)
            self.horizontalLayout.removeWidget(self.label)
            self.label.hide()
            self.horizontalLayout.removeWidget(self.haslo)
            self.haslo.hide()
            self.horizontalLayout.removeWidget(self.login)
            self.login.hide()
            self.horizontalLayout.removeWidget(self.usun)
            self.usun.hide()
Exemple #20
0
    def nueva_sol(self, restricciones, mensaje, respuesta, iteraciones,
                  holgura, artificial, data):

        vars_sol = []

        vars_entrada = []

        ultima_iteracion = iteraciones[len(iteraciones) - 1]

        for var in respuesta:
            tmp = str(var).split(" = ")
            if float(tmp[1]) > 0 and tmp[0] != 'Z':
                vars_sol.append(tmp[0])

        print("VARIABLES DE LA SOLUCION: ", vars_sol)

        for var in range(len(ultima_iteracion[0])):
            if ultima_iteracion[0][var] != "V.B" and ultima_iteracion[0][
                    var] != 'bi' and not ultima_iteracion[0][var] in vars_sol:
                if ultima_iteracion[len(ultima_iteracion) - 1][var] == 0:
                    vars_entrada.append(ultima_iteracion[0][var])

        print("VARIABLES DE ENTRADA: ", vars_entrada)

        input_ = QInputDialog(self)
        input_.setLabelText("Seleccione la nueva Variable de Entrada")
        input_.setWindowTitle("Seleccione la Nueva Variable de entrada")
        input_.setComboBoxItems(vars_entrada)
        input_.setOkButtonText("Encontrar la nueva Solución")
        input_.setCancelButtonText("Cancelar")
        button = input_.exec()

        print("RESULT: ", input_.textValue())
        print("BUTTON: ", button)

        pivote = sp.special_solution(
            ultima_iteracion[0].index(input_.textValue()), ultima_iteracion)

        sol_ = copy.deepcopy(ultima_iteracion)
        sol_ = sp.var_salida(sol_, pivote)
        sol_ = sp.reducir_fila_pivote(sol_, pivote)

        sol_ = sp.nueva_solucion_v2(sol_, pivote, holgura, artificial)
        sol_ = sp.depurar_nueva_solucion(sol_)
        iteraciones.append(sol_)
        respuesta = sp.generar_solucion(sol_, 2)

        message = QMessageBox()
        message.setWindowTitle("Simplex")
        message.setText("Nueva Solución")

        sol = ""
        for var in respuesta:
            sol = sol + var + "\n"

        message.setInformativeText("Solución: \n\n" + sol + "\n" +
                                   "¿Desea obtener una nueva solución?")
        yes = message.addButton("Sí", QMessageBox.YesRole)
        no = message.addButton("No", QMessageBox.NoRole)
        message.setIcon(QMessageBox.Information)
        message.setStyleSheet("font-weight: bold;")

        message.exec()

        if message.clickedButton() == yes:
            self.nueva_sol(restricciones, mensaje, respuesta, iteraciones,
                           holgura, artificial, data)
        elif message.clickedButton() == no:

            reporte = saveReport(restricciones, respuesta, iteraciones,
                                 mensaje, data)
            reporte.crear_pdf()
            reporte.mostrar_pdf()
Exemple #21
0
class PainterMain(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init()

    def init(self):
        self.setWindowIcon(QIcon("paint.ico"))

        self.posIndicator = QLabel("Coord", self)
        self.posIndicator.move(50, 50)
        self.posIndicator.setFixedWidth(100)

        self.height = 600
        self.width = 800
        self.color = QColor(0, 0, 0)

        self.resize(self.width, self.height)
        self.move(300, 300)
        self.img = QImage(self.width, self.height, QImage.Format_RGB32)
        self.img.fill(Qt.white)
        self.tmpimg = QImage(self.img)

        self.idCount = 0

        self.status = "NONE"
        self.points = []
        self.mousePos = []
        self.cmds = []
        self.box = []
        self.dot = []
        self.choosing = {}

        menubar = self.menuBar()

        resetCanvasAction = QAction("&resetCanvas", self)
        resetCanvasAction.triggered.connect(self.resetCanvas)
        saveCanvasAction = QAction("&saveCanvas", self)
        saveCanvasAction.triggered.connect(self.saveCanvas)

        canvasMenu = menubar.addMenu("&Canvas")
        canvasMenu.addAction(resetCanvasAction)
        canvasMenu.addAction(saveCanvasAction)

        drawNewLineDDA = QAction("&DDA", self)
        drawNewLineDDA.name = "DLDDA"
        drawNewLineDDA.triggered.connect(self.DRAW)

        drawNewLineBresenham = QAction("&Bresenham", self)
        drawNewLineBresenham.name = "DLBSH"
        drawNewLineBresenham.triggered.connect(self.DRAW)

        drawPolygonDDA = QAction("&DDA", self)
        drawPolygonDDA.name = "DPDDA"
        drawPolygonDDA.triggered.connect(self.DRAW)

        drawPolygonBresenham = QAction("&Bresenham", self)
        drawPolygonBresenham.name = "DPBSH"
        drawPolygonBresenham.triggered.connect(self.DRAW)

        drawEllipse = QAction("&Ellipse", self)
        drawEllipse.name = "DE"
        drawEllipse.triggered.connect(self.DRAW)

        drawCurveBezier = QAction("&Bezier", self)
        drawCurveBezier.name = "DCBZ"
        drawCurveBezier.triggered.connect(self.DRAW)

        drawCurveBspline = QAction("&B-spline", self)
        drawCurveBspline.name = "DCBS"
        drawCurveBspline.triggered.connect(self.DRAW)

        drawMenu = menubar.addMenu("&Drawing")
        drawNewLineMenu = drawMenu.addMenu("&Line")
        drawNewLineMenu.addAction(drawNewLineDDA)
        drawNewLineMenu.addAction(drawNewLineBresenham)
        drawPolygonMenu = drawMenu.addMenu("&Polygon")
        drawPolygonMenu.addAction(drawPolygonDDA)
        drawPolygonMenu.addAction(drawPolygonBresenham)
        drawMenu.addAction(drawEllipse)
        drawCurveMenu = drawMenu.addMenu("&Curve")
        drawCurveMenu.addAction(drawCurveBezier)
        drawCurveMenu.addAction(drawCurveBspline)

        oprTranslate = QAction("&Translate", self)
        oprTranslate.name = "T"
        oprTranslate.triggered.connect(self.OPR)

        oprRotate = QAction("&Rotate", self)
        oprRotate.name = "R"
        oprRotate.triggered.connect(self.OPR)

        oprScale = QAction("&Scale", self)
        oprScale.name = "S"
        oprScale.triggered.connect(self.OPR)

        oprClipCohen = QAction("&Cohen-Sutherland", self)
        oprClipCohen.name = "CC"
        oprClipCohen.triggered.connect(self.CLIP)

        oprClipLiang = QAction("&Liang-Barsky", self)
        oprClipLiang.name = "CL"
        oprClipLiang.triggered.connect(self.CLIP)

        oprMenu = menubar.addMenu("&Operations")
        oprMenu.addAction(oprTranslate)
        oprMenu.addAction(oprRotate)
        oprMenu.addAction(oprScale)
        oprClipMenu = oprMenu.addMenu("&Clip")
        oprClipMenu.addAction(oprClipCohen)
        oprClipMenu.addAction(oprClipLiang)

        pickColor = QAction("&Color", self)
        pickColor.triggered.connect(self.pickColor)

        menubar.addAction(pickColor)

    def mousePressEvent(self, e):
        self.posIndicator.setText("{},{}".format(e.x(), e.y()))
        if e.button() == Qt.LeftButton:
            self.pressHandler(e.pos())

    def mouseMoveEvent(self, e):
        self.posIndicator.setText("{},{}".format(e.x(), e.y()))
        self.moveHandler(e.pos())

    def mouseReleaseEvent(self, e):
        self.posIndicator.setText("{},{}".format(e.x(), e.y()))
        if e.button() == Qt.LeftButton:
            self.releaseHandler(e.pos())

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Shift:
            self.shift = True

    def keyReleaseEvent(self, e):
        if e.key() == Qt.Key_Shift:
            self.shift = False

    def resetCanvas(self):
        width, wok = QInputDialog.getInt(self, '重置画布', '输入画布宽度:', 800, 100,
                                         1000)
        if wok:
            height, hok = QInputDialog.getInt(self, '重置画布', '输入画布高度:', 600,
                                              100, 1000)
            if hok:
                self.height = height
                self.width = width

                self.resize(self.width, self.height)
                self.img = QImage(self.width, self.height, QImage.Format_RGB32)
                self.img.fill(Qt.white)
                self.tmpimg = QImage(self.img)

                self.status = "NONE"
                self.points = []
                self.cmds = []

    def saveCanvas(self):
        fname, _ = QFileDialog.getSaveFileName(self, '保存文件', '', '位图 (*.bmp)')
        if fname:
            self.img.save(fname)

    def DRAW(self):
        if self.status == "NONE":
            self.status = self.sender().name
            self.points = []
            #start drawing, waiting mouse event...

    def OPR(self):
        if self.status != "NONE":
            return

        if self.cmds:
            isRotate = "R" == self.sender().name
            self.pt = primitivePicker(self.cmds, isRotate)
            self.pt.selecting.connect(self.updateSelecting)
            if self.pt.exec_():
                for cmd in self.cmds:
                    if cmd["id"] == self.pt.getResult():
                        self.choosing = cmd
                        break
                self.status = self.sender().name
                #start operating, waiting mouse event...
            else:
                self.box = []
                self.draw()
        else:
            QMessageBox.information(self, "提示", "当前没有可供操作的图元!",
                                    QMessageBox.Yes)

    def updateSelecting(self, id):
        for cmd in self.cmds:
            if cmd["id"] == id:
                self.box = getBoxPoint(cmd["points"])
                self.draw()
                break

    def CLIP(self):
        if self.status == "NONE":
            self.status = self.sender().name

    def pickColor(self):
        self.color = QColorDialog.getColor()

    def pressHandler(self, pos):
        #draw
        if self.status in ["DLDDA", "DLBSH", "DE"]:
            self.points.append(pos)
        elif self.status in ["DPDDA", "DPBSH"]:
            if self.points:  # have previous point
                self.tmpimg = drawNewLine(self.img, self.points[-1], pos,
                                          self.status[2:], self.color)
                self.update()
            else:
                self.points.append(pos)
        elif self.status in ["DCBZ", "DCBS"]:
            if len(self.points) == 0:  # first press
                self.points.append(pos)
            if len(self.points) == 2:  # first control point
                self.cmds = self.cmds[:-1]
                self.draw()
                self.tmpimg = drawNewCurve(
                    self.img, [self.points[0], pos, pos, self.points[-1]],
                    self.status[2:], self.color)
                self.update()
            if len(self.points) == 3:  # second control point
                self.cmds = self.cmds[:-1]
                self.draw()
                self.tmpimg = drawNewCurve(
                    self.img,
                    [self.points[0], self.points[1], pos, self.points[-1]],
                    self.status[2:], self.color)
                self.update()

        #opr
        elif self.status in ["T", "R", "S", "CC", "CL"]:
            self.mousePos = pos
            if self.status not in ["CC", "CL"]:
                self.points = self.choosing["points"]

    def moveHandler(self, pos):
        #draw
        if self.status in ["DLDDA", "DPDDA"]:
            self.tmpimg = drawNewLine(self.img, self.points[-1], pos, "DDA",
                                      self.color)
        elif self.status in ["DLBSH", "DPBSH"]:
            self.tmpimg = drawNewLine(self.img, self.points[-1], pos, "BSH",
                                      self.color)
        elif self.status in ["DE"]:
            self.tmpimg = drawNewEllipse(self.img, self.points[-1], pos,
                                         self.color)
        elif self.status in ["DCBZ", "DCBS"]:
            if len(self.points
                   ) == 1:  # two point curve would fall back to line
                self.tmpimg = drawNewLine(self.img, self.points[-1], pos,
                                          "BSH", self.color)
            elif len(self.points) == 2:
                self.tmpimg = drawNewCurve(
                    self.img, [self.points[0], pos, pos, self.points[-1]],
                    self.status[2:], self.color)
            elif len(self.points) == 3:
                self.tmpimg = drawNewCurve(
                    self.img,
                    [self.points[0], self.points[1], pos, self.points[-1]],
                    self.status[2:], self.color)

        # opr
        elif self.status == "T":
            dx = pos.x() - self.mousePos.x()
            dy = pos.y() - self.mousePos.y()
            self.choosing["points"] = translate(self.points, dx, dy)
            self.box = getBoxPoint(self.choosing["points"])
            self.draw()
        elif self.status == "R":
            if self.dot:
                self.box = []
                self.choosing["points"] = rotate(
                    self.points, self.dot[0], self.mousePos,
                    pos)  # rotate center, base point, target point
                self.draw()
        elif self.status in ["CC", "CL"]:
            self.box = [self.mousePos, pos]
            self.draw()

        self.update()

    def releaseHandler(self, pos):

        if self.status == "NONE":
            return

        # draw() would be called after all ifs

        #opr
        if self.status == "T":
            if pos == self.mousePos:  # can drag at anytime if not clicking
                self.status = "NONE"
                self.box = []

        elif self.status == "R":
            if not self.dot:
                self.dot = [pos]
            else:
                self.status = "NONE"
                self.dot = []
                self.box = []

        elif self.status == "S":

            def scaling(value):
                self.choosing["points"] = scale(self.points, self.mousePos,
                                                value)
                self.box = getBoxPoint(self.choosing["points"])
                self.draw()

            def resetScale():
                self.choosing["points"] = self.points

            def confirmScale():
                self.box = []
                self.dot = []
                self.status = "NONE"
                self.draw()

            self.dot = [pos]
            self.getScale = QInputDialog()
            self.getScale.setLabelText("输入缩放倍数(0.1 ~ 5.0):")
            self.getScale.setWindowTitle("倍数选择")
            self.getScale.setCancelButtonText("取消")
            self.getScale.setOkButtonText("确定")
            self.getScale.setInputMode(QInputDialog.DoubleInput)
            self.getScale.setDoubleMinimum(0.1)
            self.getScale.setDoubleMaximum(5.0)
            self.getScale.setDoubleValue(1.0)
            self.getScale.setDoubleStep(0.1)
            self.getScale.doubleValueChanged.connect(scaling)
            self.getScale.accepted.connect(confirmScale)
            self.getScale.rejected.connect(resetScale)
            self.getScale.show()

        elif self.status in ["CC", "CL"]:
            self.cmds = clip(self.cmds, self.mousePos, pos, self.status)
            self.box = []
            self.status = "NONE"

        #draw
        elif self.status[:2] == "DL":
            self.status = "NONE"
            if pos != self.points[0]:
                self.points.append(pos)
                self.cmds.append({
                    "name": "DL",
                    "id": self.idCount,
                    "mode": self.status[2:],  # DDA or BSH
                    "points": deepcopy(self.points),
                    "color": self.color
                })
                self.idCount += 1

        elif self.status[:2] == "DP":
            # close the polygon if double clicked or points closed
            if pos == self.points[-1] or tooClose(pos, self.points[0]):
                if len(self.points) != 1:  #in case of single point
                    self.cmds = self.cmds[:-1]  # pop the temp polygon
                self.status = "NONE"
                self.points.append(self.points[0])  # close it
                self.cmds.append({
                    "name": "DP",
                    "id": self.idCount,
                    "mode": self.status[2:],
                    "points": deepcopy(self.points),
                    "color": self.color
                })
                self.idCount += 1
            # add a temp draw command if not closed yet
            else:
                if len(self.points) != 1:  #in case of single point
                    self.cmds = self.cmds[:-1]  # pop the temp polygon
                self.points.append(pos)
                self.cmds.append({
                    "name": "DP",
                    "mode": self.status[2:],
                    "points": deepcopy(self.points),
                    "color": self.color,
                })
        elif self.status == "DE":
            self.status = "NONE"
            if pos != self.points[0]:
                self.points.append(pos)
                self.cmds.append({
                    "name": "DE",
                    "id": self.idCount,
                    "points": deepcopy(self.points),
                    "color": self.color,
                })
                self.idCount += 1
        elif self.status[:2] == "DC":
            if len(self.points) == 1:
                if pos != self.points[0]:
                    self.points.append(pos)
                    self.cmds.append({
                        "name": "DC",
                        "mode": self.status[2:],
                        "points": [self.points[0]] + [pos] * 3,
                        "color": self.color,
                    })
                else:
                    self.status = "NONE"
            elif len(self.points) == 2:
                self.points = [self.points[0], pos, self.points[1]]
                self.cmds.append({
                    "name":
                    "DC",
                    "mode":
                    self.status[2:],
                    "points":
                    self.points[:1] + [pos] * 2 + self.points[-1:],
                    "color":
                    self.color
                })
            # this is the only case that adds a draw cmd
            elif len(self.points) == 3:
                self.points = self.points[:2] + [pos] + self.points[-1:]
                self.cmds.append({
                    "name": "DC",
                    "id": self.idCount,
                    "mode": self.status[2:],
                    "points": self.points,
                    "color": self.color
                })
                self.idCount += 1
                self.status = "NONE"

        self.draw()

    def draw(self):
        self.img.fill(Qt.white)  # reset the canvas and draw all components
        for cmd in self.cmds:
            name = cmd["name"]
            if name == "DL":
                self.img = drawNewLine(self.img, cmd["points"][0],
                                       cmd["points"][1], cmd["mode"],
                                       cmd["color"])
            elif name == "DP":
                self.img = drawNewPolygon(self.img, cmd["points"], cmd["mode"],
                                          cmd["color"])
            elif name == "DE":
                self.img = drawNewEllipse(self.img, cmd["points"][0],
                                          cmd["points"][1], cmd["color"])
            elif name == "DC":
                self.img = drawNewCurve(self.img, cmd["points"], cmd["mode"],
                                        cmd["color"])

        if self.box:
            self.img = drawBox(self.img, self.box)
        if self.dot:
            self.img = drawDot(self.img, self.dot[0])  # recv QPoint

        self.update()

    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        if self.status in ["NONE", "T", "S", "R", "CC", "CL"]:
            qp.drawImage(0, 0, self.img)
        else:
            qp.drawImage(0, 0, self.tmpimg)
        qp.end()