def createArduinoCalibrationControls():
    gb = QGroupBox("Arduino Calibration")
    vbox = QVBoxLayout()

    #-------------------------------------------
    layout = QHBoxLayout()

    label = QLabel("Set current position as:")
    lineEdit = QLineEdit()
    degreesLabel = QLabel("deg")
    set_btn = QPushButton("Set")

    lineEdit.setMaximumWidth(30)
    set_btn.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

    set_btn.clicked.connect(lambda: send_cmd(["=" + lineEdit.displayText()]))

    layout.setContentsMargins(0, 0, 0, 0)

    layout.addWidget(label)
    layout.addWidget(lineEdit)
    layout.addWidget(degreesLabel)
    layout.addWidget(set_btn)

    upper = QWidget()
    upper.setLayout(layout)

    #-------------------------------------------

    layout = QHBoxLayout()

    btn0 = QPushButton("Set as 0")
    btn180 = QPushButton("Set as 180")

    btn0.clicked.connect(lambda: send_cmd(["=0"]))
    btn180.clicked.connect(lambda: send_cmd(["=180"]))

    layout.setContentsMargins(0, 0, 0, 0)
    layout.setSpacing(0)

    layout.addWidget(btn0)
    layout.addWidget(btn180)
    layout.addStretch(1)

    lower = QWidget()
    lower.setLayout(layout)

    #-------------------------------------------

    vbox.setContentsMargins(0, 0, 0, 0)
    vbox.setSpacing(0)

    vbox.addWidget(upper)
    vbox.addWidget(lower)
    gb.setLayout(vbox)
    return gb
class ConfigWidget(Dialog):
    def __init__(self, gui):
        self.gui = gui
        self.qlinedit_widgets = {}
        Dialog.__init__(self, _('Edit Spans & Divs Customization'), '{}plugin:spandiv_config'.format(PLUGIN_SAFE_NAME), gui)

    def setup_ui(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        columns_frame = QHBoxLayout()
        layout.addLayout(columns_frame)

        # How many columns of nine items each will it take to display
        # a text box for each tag in taglist?
        col_limit = 9
        num_cols = len(TAGLIST)/col_limit
        num_cols = int(math.ceil(num_cols))

        # If the column limit and the number of columns produces a single
        # orphan text entry widget, reduce the column limit accordingly.
        if num_cols > 1 and (len(TAGLIST) - ((num_cols - 1)*col_limit)) < 2:
            if num_cols >= 3:
                col_limit -= 1

        # Create an integer-indexed dictionary of QVBoxLayouts representing the number of
        # columns necessary. Added left to right in the parent QHBoxLayout.
        column = {}
        for i in xrange(1, num_cols+1):
            column[i] = QVBoxLayout()
            column[i].setAlignment(Qt.AlignLeft)
            columns_frame.addLayout(column[i])

        # Create a dictionary of QLineEdit widgets (indexed by tag name) and stack them
        # (top to bottom) and their labels in as many columns as it takes.
        curr_col = 1
        curr_item = 1
        tooltip = _('Comma separated list of html elements (no quotes, no angle "&lt;" brackets).')
        for tag in TAGLIST:
            # Column item limit surpassed - switch to next column.
            if curr_item > col_limit:
                column[curr_col].addStretch()
                curr_col += 1
                curr_item = 1
            # Add lable and QLineEdit widget to current column.
            label = QLabel(_('<b>Choices to change "{}" elements to:</b>').format(tag), self)
            label.setAlignment(Qt.AlignCenter)
            self.qlinedit_widgets[tag] = QLineEdit(', '.join(plugin_prefs['{}_changes'.format(tag)]), self)
            self.qlinedit_widgets[tag].setToolTip('<p>{}'.format(tooltip))
            column[curr_col].addWidget(label)
            column[curr_col].addWidget(self.qlinedit_widgets[tag])

            if not len(CHANGE_TO_MAP[tag]):
                self.qlinedit_widgets[tag].setDisabled(True)
            curr_item += 1
        column[curr_col].addStretch()

        layout.addSpacing(10)
        attrs_layout = QVBoxLayout()
        attrs_layout.setAlignment(Qt.AlignCenter)
        layout.addLayout(attrs_layout)
        label = QLabel(_('<b>HTML attributes available to search for:</b>'), self)
        label.setAlignment(Qt.AlignCenter)
        self.attrs_txtBox = QLineEdit(', '.join(plugin_prefs['attrs']), self)
        self.attrs_txtBox.setToolTip('<p>{}'.format(_('Comma separated list of html attribute names (no quotes).')))
        attrs_layout.addWidget(label)
        attrs_layout.addWidget(self.attrs_txtBox)

        layout.addSpacing(10)
        right_layout = QHBoxLayout()
        right_layout.setAlignment(Qt.AlignRight)
        layout.addLayout(right_layout)
        reset_button = QPushButton(_('Reset all defaults'), self)
        reset_button.setToolTip('<p>{}'.format(_('Reset all settings to original defaults.')))
        reset_button.clicked.connect(self.reset_defaults)
        right_layout.addWidget(reset_button)

        layout.addSpacing(10)
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.save_settings)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)

    def save_settings(self):
        # Save current dialog sttings back to JSON config file
        for tag in TAGLIST:
            tmp_list = unicode(self.qlinedit_widgets[tag].displayText()).split(',')
            tmp_list = [x.strip(' ') for x in tmp_list]
            plugin_prefs['{}_changes'.format(tag)] = filter(None, tmp_list)

        tmp_list = unicode(self.attrs_txtBox.displayText()).split(',')
        tmp_list = [x.strip(' ') for x in tmp_list]
        plugin_prefs['attrs'] = filter(None, tmp_list)
        self.accept()

    def reset_defaults(self):
        caption= _('Are you sure?')
        msg = '<p>{}'.format(_('Reset all customizable options to their original defaults?'))
        det_msg = ''
        if question_dialog(self.gui, caption, msg, det_msg):
            for tag in TAGLIST:
                plugin_prefs['{}_changes'.format(tag)] = CHANGE_TO_MAP[tag]
            plugin_prefs['attrs'] = ATTRS_LIST
            self.accept()
Esempio n. 3
0
class ConfigWidget(QWidget):

    def __init__(self, plugin_action):
        QWidget.__init__(self)
        self.plugin_action = plugin_action
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        # --- Directory Options ---
        directory_group_box = QGroupBox(_('Default Unpack Directory:'), self)
        layout.addWidget(directory_group_box)
        directory_group_box_layout = QVBoxLayout()
        directory_group_box.setLayout(directory_group_box_layout)

        # Directory path Textbox
        # Load the textbox with the current preference setting
        self.directory_txtBox = QLineEdit(plugin_prefs['Unpack_Folder'], self)
        self.directory_txtBox.setToolTip(_('<p>Default directory to extract files to'))
        directory_group_box_layout.addWidget(self.directory_txtBox)
        self.directory_txtBox.setReadOnly(True)

        # Folder select button
        directory_button = QPushButton(_('Select/Change Unpack Directory'), self)
        directory_button.setToolTip(_('<p>Select/Change directory to extract files to.'))
        # Connect button to the getDirectory function
        directory_button.clicked.connect(self.getDirectory)
        directory_group_box_layout.addWidget(directory_button)
        self.default_folder_check = QCheckBox(_('Always use the Default Unpack Directory'), self)
        self.default_folder_check.setToolTip(_('<p>When unchecked... you will be prompted to select a destination '+
                                                                                'directory for the extracted content each time you use Mobiunpack.'))
        directory_group_box_layout.addWidget(self.default_folder_check)
        # Load the checkbox with the current preference setting
        self.default_folder_check.setChecked(plugin_prefs['Always_Use_Unpack_Folder'])

        misc_group_box = QGroupBox(_('Default settings:'), self)
        layout.addWidget(misc_group_box)
        misc_group_box_layout = QVBoxLayout()
        misc_group_box.setLayout(misc_group_box_layout)

        self.use_hd_images = QCheckBox(_('Always use HD images if present'), self)
        self.use_hd_images.setToolTip(_('<p>When checked... any HD images present in the kindlebook '+
                                                                                'will be used for creating the ePub.'))
        misc_group_box_layout.addWidget(self.use_hd_images)
        # Load the checkbox with the current preference setting
        self.use_hd_images.setChecked(plugin_prefs['Use_HD_Images'])

        combo_label = QLabel('Select epub version output:', self)
        misc_group_box_layout.addWidget(combo_label)
        self.epub_version_combobox = QComboBox()
        self.epub_version_combobox.setToolTip(_('<p>Select the type of OPF file to create.'))
        misc_group_box_layout.addWidget(self.epub_version_combobox)
        self.epub_version_combobox.addItems(['Auto-detect', 'ePub2', 'ePub3'])
        if plugin_prefs['Epub_Version'] == 'A':
            self.epub_version_combobox.setCurrentIndex(0)
        else:
            self.epub_version_combobox.setCurrentIndex(int(plugin_prefs['Epub_Version'])-1)

    def save_settings(self):
        # Save current dialog sttings back to JSON config file
            plugin_prefs['Unpack_Folder'] = unicode(self.directory_txtBox.displayText())
            plugin_prefs['Always_Use_Unpack_Folder'] = self.default_folder_check.isChecked()
            plugin_prefs['Use_HD_Images'] = self.use_hd_images.isChecked()
            if unicode(self.epub_version_combobox.currentText()) == 'Auto-detect':
                plugin_prefs['Epub_Version'] = 'A'
            else:
                plugin_prefs['Epub_Version'] = unicode(self.epub_version_combobox.currentText())[4:]

    def getDirectory(self):
        c = choose_dir(self, _(PLUGIN_NAME + 'dir_chooser'),
                _('Select Default Directory To Unpack Kindle Book/Mobi To'))
        if c:
            self.directory_txtBox.setReadOnly(False)
            self.directory_txtBox.setText(c)
            self.directory_txtBox.setReadOnly(True)

    def validate(self):
        # This is just to catch the situation where somone might
        # manually enter a non-existent path in the Default path textbox.
        # Shouldn't be possible at this point.
        if not os.path.exists(self.directory_txtBox.text()):
            errmsg = '<p>The path specified for the Default Unpack folder does not exist.</p>' \
                        '<p>Your latest preference changes will <b>NOT</b> be saved!</p>' + \
                        '<p>You should configure again and make sure your settings are correct.'
            error_dialog(None, _(PLUGIN_NAME + ' v' + PLUGIN_VERSION),
                                    _(errmsg), show=True)
            return False
        return True
Esempio n. 4
0
class MyWidget(QWidget):
    log = Logger('logs/main/main.log', level='info')
    METHOD_KERNEL = Kernel(log.logger)

    def __init__(self, Parant=None):
        super().__init__(Parant)
        self.__eraser_mode_set = False
        self.__init_data()
        self.__init_view()

    def __init_data(self):
        self.__canvas = PaintBoard(self)
        self.__colorList = QColor.colorNames()

    def __init_view(self):
        self.setFixedSize(720, 530)

        self.label_university = QLabel("学校:\t华南理工大学", self)
        self.label_university.setStyleSheet("font-size:12px")
        self.label_university.setGeometry(460, 10, 120, 35)

        self.label_school = QLabel("专业:\t控制科学与工程", self)
        self.label_school.setStyleSheet("font-size:12px")
        self.label_school.setGeometry(460, 40, 140, 35)

        self.label_name = QLabel("姓名:\t***", self)
        self.label_name.setStyleSheet("font-size:12px")
        self.label_name.setGeometry(460, 70, 100, 35)

        self.label_number = QLabel("学号:\t***", self)
        self.label_number.setStyleSheet("font-size:12px")
        self.label_number.setGeometry(460, 100, 120, 35)

        self.label_im = QLabel(self)
        self.label_im.setGeometry(600, 20, 105, 105)
        self.label_im.setPixmap(QPixmap("./im_scut.jpg").scaled(105, 105))

        self.label_log = QTextEdit(self)
        self.label_log.setReadOnly(True)
        # self.label_log.moveCursor(QTextCursor.Down)
        self.label_log.setStyleSheet(
            "background:transparent; font-size:15px; font-family:Roman times")
        # self.label_log.resize(220, 200)
        self.label_log.setGeometry(460, 140, 245, 220)
        self.label_log.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.label_log.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)

        # create a horizontal layout as the main layout of the GUI
        main_layout = QHBoxLayout(self)
        # set the distance between widgets to 10px
        main_layout.setSpacing(10)

        left_layout = QVBoxLayout()
        left_layout.setContentsMargins(5, 5, 5, 5)

        left_layout.addWidget(self.__canvas)

        path_layout = QHBoxLayout()
        path_layout.setContentsMargins(5, 5, 5, 5)

        self.__lab_path = QLabel(self)
        self.__lab_path.setText("Save Path")
        self.__lab_path.setFixedHeight(10)
        path_layout.addWidget(self.__lab_path)
        left_layout.addLayout(path_layout)

        self.__txt_path = QLineEdit("./data/1")
        path_layout.addWidget(self.__txt_path)

        self.__choose_path = QPushButton("index")
        self.__choose_path.setParent(self)
        # self.__choose_path.setShortcut("Ctrl+S")
        self.__choose_path.clicked.connect(self.btn_save_clicked)
        path_layout.addWidget(self.__choose_path)

        btn_layout = QHBoxLayout()
        btn_layout.setContentsMargins(5, 5, 5, 5)

        self.__btn_save = QPushButton("Save")
        self.__btn_save.setParent(self)
        self.__btn_save.setShortcut("Ctrl+A")
        self.__btn_save.clicked.connect(self.save_image)
        btn_layout.addWidget(self.__btn_save)

        self.__btn_recognize = QPushButton("Predict")
        self.__btn_recognize.setParent(self)
        self.__btn_recognize.setShortcut("Ctrl+R")
        self.__btn_recognize.clicked.connect(self.btn_recog_clicked)
        btn_layout.addWidget(self.__btn_recognize)

        self.__btn_clear = QPushButton("Clear")
        self.__btn_clear.setShortcut("Ctrl+X")
        self.__btn_clear.setParent(self)
        self.__btn_clear.clicked.connect(self.btn_clear_clicked)
        btn_layout.addWidget(self.__btn_clear)

        self.__btn_exit = QPushButton("EXIT")
        self.__btn_exit.setParent(self)
        # self.__btn_exit.setShortcut("Ctrl+Q")
        self.__btn_exit.clicked.connect(self.btn_exit_clicked)
        btn_layout.addWidget(self.__btn_exit)

        left_layout.addLayout(btn_layout)
        main_layout.addLayout(left_layout)

        # put canvas in the left GUI
        # main_layout.addWidget(self.__canvas)
        # main_layout.addWidget(left_layout)

        # set the right layout
        right_layout = QVBoxLayout()
        # set the space between right contents
        right_layout.setContentsMargins(5, 5, 5, 14)

        splitter = QSplitter(self)
        right_layout.addWidget(splitter)

        method_layout = QHBoxLayout()

        self.__lab_method = QLabel(self)
        self.__lab_method.setText("Recognition Method")
        self.__lab_method.setFixedHeight(30)
        method_layout.addWidget(self.__lab_method)

        self.kernel_list = [
            'NaiveBayesian', 'VoteFisher', 'MultiFisher', 'SklearnFisher',
            'CNN'
        ]

        self.__box_method = QComboBox(self)
        self.__box_method.addItems(self.kernel_list)
        self.__box_method.setCurrentIndex(0)
        method_layout.addWidget(self.__box_method)

        right_layout.addLayout(method_layout)

        show_layout = QHBoxLayout()
        canv_layout = QVBoxLayout()

        self.__cbtn_eraser = QCheckBox("Eraser")
        self.__cbtn_eraser.setParent(self)
        self.__cbtn_eraser.clicked.connect(self.btn_eraser_clicked)
        canv_layout.addWidget(self.__cbtn_eraser)

        pen_size_layout = QHBoxLayout()

        self.__lab_pen_size = QLabel(self)
        self.__lab_pen_size.setText("Pen Size")
        self.__lab_pen_size.setFixedHeight(20)
        # self.__lab_pen_size.setFixedSize(50, 20)
        pen_size_layout.addWidget(self.__lab_pen_size)

        self.__box_pen_size = QSpinBox(self)
        self.__box_pen_size.setMaximum(40)
        self.__box_pen_size.setMinimum(20)
        self.__box_pen_size.setValue(30)
        self.__box_pen_size.setSingleStep(2)
        self.__box_pen_size.setFixedSize(50, 20)
        self.__box_pen_size.valueChanged.connect(self.box_pen_size_change)
        pen_size_layout.addWidget(self.__box_pen_size)
        canv_layout.addLayout(pen_size_layout)

        pen_color_layout = QHBoxLayout()

        self.__label_pen_color = QLabel(self)
        self.__label_pen_color.setText("Pen Color")
        self.__label_pen_color.setFixedHeight(20)
        pen_color_layout.addWidget(self.__label_pen_color)

        self.__combo_pen_color = QComboBox(self)
        self.__combo_pen_color.setFixedSize(50, 20)
        self.__fillColorList(self.__combo_pen_color)
        self.__combo_pen_color.currentIndexChanged.connect(
            self.pen_color_changed)
        pen_color_layout.addWidget(self.__combo_pen_color)
        canv_layout.addLayout(pen_color_layout)
        show_layout.addLayout(canv_layout)

        self.feature_map = QLabel()
        self.feature_map.setFixedSize(100, 100)
        self.feature_map.setText("")
        self.feature_map.setObjectName('feature map')
        show_layout.addWidget(self.feature_map)
        right_layout.addLayout(show_layout)

        main_layout.addLayout(right_layout)

    def btn_recog_clicked(self):
        self.update()
        savePath = "./recog.jpg"
        image = self.__canvas.get_current_image()
        image.save(savePath)
        save_path = os.path.abspath(savePath)
        self.label_log.append("image saved in path:\n{}".format(save_path))
        method_text = self.__box_method.currentText()
        self.label_log.append('method: {}'.format(method_text))
        predict = self.METHOD_KERNEL.set_kernel(savePath, method_text)
        # pic = QTextImageFormat()
        # pic.setName('./feature_map.jpg')
        # pic.setHeight(100)
        # pic.setWidth(100)
        showImage = QImage('./feature_map.jpg').scaled(100, 100)
        self.feature_map.setPixmap(QPixmap.fromImage(showImage))
        # self.label_log.append('feature map:\n')
        # self.label_log.textCursor().insertImage('./feature_map.jpg')
        self.label_log.append("recognition result is: {}".format(predict))
        # self.label_log.moveCursor(QTextCursor.End)
        # self.label_log.textCursor().clearSelection()
        # del pic
        message = QMessageBox()
        message.setText("recognition result is: {}".format(predict))
        # message.addButton()
        message.exec_()

    def btn_clear_clicked(self):
        self.__canvas.clear()
        self.label_log.append("Canvas is clean now!")

    def btn_save_clicked(self):
        save_path = QFileDialog.getSaveFileName(self, 'save your paint', '.\\',
                                                '*.jpg')
        if save_path[0] == "":
            self.label_log.append("save cancel")
            return
        self.__txt_path.setText(save_path[0])
        save_image = self.__canvas.get_current_image()
        save_image.save(save_path[0])
        save_path_ = os.path.abspath(save_path[0])
        self.label_log.append("image saved in path:\n{}".format(save_path_))

    def save_image(self):
        self.__txt_path.setText(self.__txt_path.displayText())
        save_path = self.__txt_path.text()
        created = create_dir_path(save_path)
        if created:
            self.label_log.append("create an directory:\n{}".format(save_path))
        file_path = create_file_path(save_path)
        save_image = self.__canvas.get_current_image()
        save_image.save(file_path)
        file_path_ = os.path.abspath(file_path)
        self.label_log.append("image saved in path:\n{}".format(file_path_))

    def btn_exit_clicked(self):
        self.close()
        QApplication.quit()

    def btn_eraser_clicked(self):
        self.__eraser_mode_set = ~self.__eraser_mode_set
        if self.__eraser_mode_set:
            self.label_log.append("Attention! Eraser Mode!")
        else:
            self.label_log.append("Writing Mode!")
        if self.__cbtn_eraser.isChecked():
            self.__canvas.EraserMode = True
        else:
            self.__canvas.EraserMode = False

    def box_pen_size_change(self):
        pen_size = self.__box_pen_size.value()
        self.__canvas.pen_size(pen_size)

    def __fillColorList(self, comboBox):
        index_black = 0
        index = 0
        for color in self.__colorList:
            if color == "black":
                index_black = index
            index += 1
            pix = QPixmap(70, 20)
            pix.fill(QColor(color))
            comboBox.addItem(QIcon(pix), None)
            comboBox.setIconSize(QSize(70, 20))
            comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        comboBox.setCurrentIndex(index_black)

    def pen_color_changed(self):
        color_index = self.__combo_pen_color.currentIndex()
        color_str = self.__colorList[color_index]
        self.__canvas.pen_color(color_str)
Esempio n. 5
0
class RemoveDialog(Dialog):
    def __init__(self, parent):
        from calibre_plugins.diaps_toolbag.span_div_config import plugin_prefs as prefs
        self.criteria = None
        self.prefs = prefs
        self.parent = parent
        self.help_file_name = '{0}_span_div_help.html'.format(PLUGIN_SAFE_NAME)
        self.taglist = TAGLIST
        Dialog.__init__(self, _('Edit Spans & Divs'), 'toolbag_spans_divs_dialog', parent)

    def setup_ui(self):
        DELETE_STR = _('Delete')
        MODIFY_STR = _('Modify')
        NO_ATTRIB_STR = _('No attributes ("naked" tag)')
        self.NO_CHANGE_STR = _('No change')

        layout = QVBoxLayout(self)
        self.setLayout(layout)

        help_layout = QHBoxLayout()
        layout.addLayout(help_layout)
        # Add hyperlink to a help file at the right. We will replace the correct name when it is clicked.
        help_label = QLabel('<a href="http://www.foo.com/">Plugin Help</a>', self)
        help_label.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard)
        help_label.setAlignment(Qt.AlignRight)
        help_label.linkActivated.connect(self.help_link_activated)
        help_layout.addWidget(help_label)

        action_layout = QHBoxLayout()
        layout.addLayout(action_layout)
        label = QLabel(_('Action type:'), self)
        action_layout.addWidget(label)
        self.action_combo = QComboBox()
        action_layout.addWidget(self.action_combo)
        self.action_combo.addItems([DELETE_STR, MODIFY_STR])
        self.action_combo.currentIndexChanged.connect(self.update_gui)

        tag_layout = QHBoxLayout()
        layout.addLayout(tag_layout)
        label = QLabel(_('Tag name:'), self)
        tag_layout.addWidget(label)
        self.tag_combo = QComboBox()
        tag_layout.addWidget(self.tag_combo)
        self.tag_combo.addItems(self.taglist)
        self.tag_combo.currentIndexChanged.connect(self.update_gui)

        attr_layout = QHBoxLayout()
        layout.addLayout(attr_layout)
        label = QLabel(_('Having the attribute:'), self)
        attr_layout.addWidget(label)
        self.attr_combo = QComboBox()
        attr_layout.addWidget(self.attr_combo)
        self.attr_combo.addItems(self.prefs['attrs'])
        self.attr_combo.addItem(NO_ATTRIB_STR)
        self.attr_combo.currentIndexChanged.connect(self.update_gui)

        srch_layout = QHBoxLayout()
        layout.addLayout(srch_layout)
        label = QLabel(_("Whose value is (no quotes):"), self)
        srch_layout.addWidget(label)
        self.srch_txt = QLineEdit('', self)
        srch_layout.addWidget(self.srch_txt)
        self.srch_method = QCheckBox(_('Regex'), self)
        srch_layout.addWidget(self.srch_method)

        newtag_layout = QHBoxLayout()
        layout.addLayout(newtag_layout)
        label = QLabel(_('Change tag to:'), self)
        newtag_layout.addWidget(label)
        self.newtag_combo = QComboBox()
        newtag_layout.addWidget(self.newtag_combo)

        self.newtag_combo.addItem(self.NO_CHANGE_STR)
        self.newtag_combo.addItems(self.prefs['{}_changes'.format(unicode(self.tag_combo.currentText()))])

        if self.action_combo.currentIndex() == 0:
            self.newtag_combo.setDisabled(True)

        newattr_layout = QVBoxLayout()
        layout.addLayout(newattr_layout)
        label = QLabel(_('New attribute string to insert (entire):'), self)
        newattr_layout.addWidget(label)
        self.newattr_txt = QLineEdit('', self)
        newattr_layout.addWidget(self.newattr_txt)
        self.copy_attr = QCheckBox(_('Copy existing attribute string'), self)
        self.copy_attr.stateChanged.connect(self.update_txt_box)
        newattr_layout.addWidget(self.copy_attr)
        if self.action_combo.currentIndex() == 0:
            self.copy_attr.setDisabled(True)
            self.newattr_txt.setDisabled(True)

        layout.addSpacing(10)
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self._ok_clicked)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)

    def update_gui(self):
        if self.attr_combo.currentIndex() == self.attr_combo.count()-1:
            self.srch_txt.clear()
            self.srch_txt.setDisabled(True)
            self.srch_method.setChecked(False)
            self.srch_method.setDisabled(True)
        else:
            self.srch_txt.setDisabled(False)
            self.srch_method.setDisabled(False)

        self.newtag_combo.clear()
        self.newtag_combo.addItem(self.NO_CHANGE_STR)
        self.newtag_combo.addItems(self.prefs['{}_changes'.format(unicode(self.tag_combo.currentText()))])

        if self.action_combo.currentIndex() == 0:
            self.newtag_combo.setCurrentIndex(0)
            self.newtag_combo.setDisabled(True)
            self.newattr_txt.clear()
            self.newattr_txt.setDisabled(True)
            self.copy_attr.setChecked(False)
            self.copy_attr.setDisabled(True)
        else:
            self.newtag_combo.setDisabled(False)
            self.newattr_txt.setDisabled(False)
            self.copy_attr.setDisabled(False)

    def update_txt_box(self):
        if self.copy_attr.isChecked():
            self.newattr_txt.clear()
            self.newattr_txt.setDisabled(True)
        else:
            self.newattr_txt.setDisabled(False)

    def _ok_clicked(self):
        if self.action_combo.currentIndex() == 0:
            action = 'delete'
        else:
            action = 'modify'
        if self.attr_combo.currentIndex() == self.attr_combo.count()-1:
            attribute = None
        else:
            attribute = unicode(self.attr_combo.currentText())
        srch_str = unicode(self.srch_txt.displayText())
        if not len(srch_str):
            srch_str = None
        if srch_str is None and attribute is not None:
            return error_dialog(self.parent, _('Error'), '<p>{0}'.format(
                    _('Must enter a value for the attribute selected')), det_msg='', show=True)
        srch_method = 'normal'
        if self.srch_method.isChecked():
            srch_method = 'regex'
        if self.newtag_combo.currentIndex() == 0:
            newtag = None
        else:
            newtag = unicode(self.newtag_combo.currentText())
        if action == 'modify' and newtag is None and self.copy_attr.isChecked():
            return error_dialog(self.parent, _('Error'), '<p>{0}'.format(
                    _('What--exactly--would that achieve?')), det_msg='', show=True)
        new_str = unicode(self.newattr_txt.displayText())
        copy_attr = False
        if self.copy_attr.isChecked():
            copy_attr = True
        if not len(new_str):
            new_str = ''

        self.criteria = (srch_str, srch_method, unicode(self.tag_combo.currentText()), attribute, action, newtag, new_str, copy_attr)
        self.accept()

    def getCriteria(self):
        return self.criteria

    def help_link_activated(self, url):
        def get_help_file_resource():
            # Copy the HTML helpfile to the plugin directory each time the
            # link is clicked in case the helpfile is updated in newer plugins.
            file_path = os.path.join(config_dir, 'plugins', self.help_file_name)
            with open(file_path,'w') as f:
                f.write(load_resource('resources/{}'.format(self.help_file_name)))
            return file_path
        url = 'file:///' + get_help_file_resource()
        open_url(QUrl(url))
Esempio n. 6
0
class PunctDialog(Dialog):
    def __init__(self, parent):
        self.prefs = self.prefsPrep()
        self.criteria = None
        self.parent = parent
        self.help_file_name = '{0}_smarten_help.html'.format(PLUGIN_SAFE_NAME)
        Dialog.__init__(self, _('Smarten Punctuation (the sequel)'), 'toolbag_smarter_dialog', parent)

    def setup_ui(self,):
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        help_layout = QHBoxLayout()
        layout.addLayout(help_layout)
        # Add hyperlink to a help file at the right. We will replace the correct name when it is clicked.
        help_label = QLabel('<a href="http://www.foo.com/">Plugin Help</a>', self)
        help_label.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard)
        help_label.setAlignment(Qt.AlignRight)
        help_label.linkActivated.connect(self.help_link_activated)
        help_layout.addWidget(help_label)

        self.edu_quotes = QCheckBox(_('Smarten Quotation marks'), self)
        layout.addWidget(self.edu_quotes)
        self.edu_quotes.setChecked(self.prefs['edu_quotes'])
        self.edu_quotes.stateChanged.connect(self.quotes_gui_changes)

        exceptions_group_box = QGroupBox('', self)
        layout.addWidget(exceptions_group_box)
        exceptions_group_box_layout = QVBoxLayout()
        exceptions_group_box.setLayout(exceptions_group_box_layout)
        self.use_file = QCheckBox(_('Use custom apostrophe exceptions file'), self)
        exceptions_group_box_layout.addWidget(self.use_file)
        if not self.edu_quotes.isChecked():
            self.use_file.setDisabled(True)
        else:
            self.use_file.setChecked(self.prefs['use_file'])
        self.use_file.stateChanged.connect(self.use_file_gui_changes)

        path_layout = QHBoxLayout()
        exceptions_group_box_layout.addLayout(path_layout)
        self.file_path = QLineEdit('', self)
        if not self.edu_quotes.isChecked() and not self.use_file.isChecked():
            self.file_path.setReadOnly(True)
        else:
            self.file_path.setText(self.prefs['file_path'])
            self.file_path.setReadOnly(True)
        path_layout.addWidget(self.file_path)
        self.file_button = QPushButton('...', self)
        self.file_button.clicked.connect(self.getFile)
        path_layout.addWidget(self.file_button)
        if not self.edu_quotes.isChecked() and not self.use_file.isChecked():
            self.file_button.setDisabled(True)

        combo_layout = QVBoxLayout()
        layout.addLayout(combo_layout)
        label = QLabel(_('(em|en)-dash settings'), self)
        combo_layout.addWidget(label)
        self.dashes_combo = QComboBox()
        combo_layout.addWidget(self.dashes_combo)
        values = [_('Do not educate dashes'), _('-- = emdash (no endash support)'),
                  _('-- = emdash | --- = endash'), _('--- = emdash | -- = endash')]
        self.dashes_combo.addItems(values)
        self.dashes_combo.setCurrentIndex(self.prefs['dashes'])
        # self.dashes_combo.currentIndexChanged.connect(self.update_gui)

        self.ellipses = QCheckBox(_('Smarten ellipses'), self)
        layout.addWidget(self.ellipses)
        self.ellipses.setChecked(self.prefs['ellipses'])

        self.unicode = QCheckBox(_('Educate with unicode characters (instead of entities)'), self)
        layout.addWidget(self.unicode)
        self.unicode.setChecked(self.prefs['unicode'])

        layout.addSpacing(10)
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self._ok_clicked)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)

    def getFile(self):
        unique_dlg_name = '{0}plugin:smarter_choose_dialog'.format(PLUGIN_SAFE_NAME)
        caption = _('Select custom apostrophe exceptions file')
        filters = [('Text files', ['txt'])]
        c = choose_files(self, unique_dlg_name, caption, filters, all_files=True)

        if c:
            self.file_path.setReadOnly(False)
            self.file_path.setText(c[0])
            self.file_path.setReadOnly(True)

    def _ok_clicked(self):
        quotes_setting = 'q' if self.edu_quotes.isChecked() else ''
        if self.dashes_combo.currentIndex() == 0:
            dash_setting = ''
        elif self.dashes_combo.currentIndex() == 1:
            dash_setting = 'd'
        elif self.dashes_combo.currentIndex() == 2:
            dash_setting = 'i'
        elif self.dashes_combo.currentIndex() == 3:
            dash_setting = 'D'
        else:
            dash_setting = ''
        ellipses_setting = 'e' if self.ellipses.isChecked() else ''
        smarty_attr = quotes_setting + dash_setting + ellipses_setting
        if smarty_attr == '':
            smarty_attr = '0'

        self.file_path.setReadOnly(False)
        if self.use_file.isChecked() and not len(self.file_path.displayText()):
            self.file_path.setReadOnly(True)
            return error_dialog(self.parent, _('Error'), '<p>' +
                    _('Must select a custom exception file'), det_msg='', show=True)
        if self.use_file.isChecked():
            apos_exception_file = unicode(self.file_path.displayText())
            if not os.path.exists(apos_exception_file):
                apos_exception_file = None
        else:
            apos_exception_file = None
        self.file_path.setReadOnly(True)
        apos_words_list = []
        if apos_exception_file is not None:
            apos_words_list = self.parseExceptionsFile(os.path.normpath(apos_exception_file))
        self.criteria = (smarty_attr, self.unicode.isChecked(), apos_words_list)
        self.savePrefs()
        self.accept()

    def getCriteria(self):
        return self.criteria

    def quotes_gui_changes(self):
        if self.edu_quotes.isChecked():
            self.use_file.setDisabled(False)
            if self.use_file.isChecked():
                self.file_button.setDisabled(False)
        else:
            self.use_file.setChecked(False)
            self.file_path.setReadOnly(False)
            self.file_path.clear()
            self.file_path.setReadOnly(True)
            self.use_file.setDisabled(True)
            self.file_button.setDisabled(True)

    def use_file_gui_changes(self):
        if self.use_file.isChecked():
            self.file_button.setDisabled(False)
        else:
            self.file_path.setReadOnly(False)
            self.file_path.clear()
            self.file_path.setReadOnly(True)
            self.file_button.setDisabled(True)

    def prefsPrep(self):
        from calibre.utils.config import JSONConfig
        plugin_prefs = JSONConfig('plugins/{0}_SmarterPunct_settings'.format(PLUGIN_SAFE_NAME))
        plugin_prefs.defaults['edu_quotes'] = True
        plugin_prefs.defaults['use_file'] = False
        plugin_prefs.defaults['file_path'] = ''
        plugin_prefs.defaults['dashes'] = 1
        plugin_prefs.defaults['ellipses'] = True
        plugin_prefs.defaults['unicode'] = True
        return plugin_prefs

    def savePrefs(self):
        self.prefs['edu_quotes'] = self.edu_quotes.isChecked()
        self.prefs['use_file'] = self.use_file.isChecked()
        self.prefs['file_path'] = unicode(self.file_path.displayText()) if len(self.file_path.displayText()) else ''
        self.prefs['dashes'] = self.dashes_combo.currentIndex()
        self.prefs['ellipses'] = self.ellipses.isChecked()
        self.prefs['unicode'] = self.unicode.isChecked()

    def help_link_activated(self, url):
        def get_help_file_resource():
            # Copy the HTML helpfile to the plugin directory each time the
            # link is clicked in case the helpfile is updated in newer plugins.
            file_path = os.path.join(config_dir, 'plugins', self.help_file_name)
            with open(file_path,'w') as f:
                f.write(load_resource('resources/{}'.format(self.help_file_name)))
            return file_path
        url = 'file:///' + get_help_file_resource()
        open_url(QUrl(url))

    def parseExceptionsFile(self, filename):
        import os, codecs, chardet
        words_list = []
        bytes = min(32, os.path.getsize(filename))
        raw = open(filename, 'rb').read(bytes)
        if raw.startswith(codecs.BOM_UTF8):
            enc = 'utf-8-sig'
        else:
            result = chardet.detect(raw)
            enc = result['encoding']
        try:
            with codecs.open(filename, encoding=enc, mode='r') as fd:
                words_list = [line.rstrip() for line in fd]
            words_list = filter(None, words_list)
            print('Exceptions list:', words_list)
        except:
            pass
        return words_list
def createGotoControls():
    gb = QGroupBox("Goto Controls")

    #-------------------------------------------

    layout = QHBoxLayout()

    label = QLabel("Goto angle:")
    lineEdit = QLineEdit()
    go_btn = QPushButton("Go")

    lineEdit.setMaximumWidth(30)
    go_btn.clicked.connect(lambda: send_cmd(["g" + lineEdit.displayText()]))

    layout.setContentsMargins(0, 0, 0, 0)
    layout.setSpacing(0)

    layout.addWidget(label)
    layout.addWidget(lineEdit)
    layout.addSpacing(10)
    layout.addWidget(go_btn)

    upper = QWidget()
    upper.setLayout(layout)

    #------------------------------------------

    layout = QHBoxLayout()

    btn0 = QPushButton("0")
    btn90 = QPushButton("90")
    btn180 = QPushButton("180")
    btn270 = QPushButton("270")

    btn0.clicked.connect(lambda: send_cmd(["g0"]))
    btn90.clicked.connect(lambda: send_cmd(["g90"]))
    btn180.clicked.connect(
        lambda: send_cmd(["g" + str(180 + float(offAt180_sb.value()))]))
    btn270.clicked.connect(lambda: send_cmd(["g270"]))

    btn0.setMaximumWidth(40)
    btn90.setMaximumWidth(40)
    btn180.setMaximumWidth(40)
    btn270.setMaximumWidth(40)

    layout.setContentsMargins(0, 0, 0, 0)
    layout.setSpacing(0)

    layout.addWidget(btn0)
    layout.addWidget(btn90)
    layout.addWidget(btn180)
    layout.addWidget(btn270)

    lower = QWidget()
    lower.setLayout(layout)

    #------------------------------------------
    vbox = QVBoxLayout()

    vbox.addWidget(upper)
    vbox.addWidget(lower)
    vbox.addStretch(1)

    vbox.setContentsMargins(0, 0, 0, 0)
    vbox.setSpacing(0)

    gb.setLayout(vbox)
    return gb