Exemplo n.º 1
0
 def rehighlight(self):
     doc = self.doc
     if doc is None:
         return
     lb = doc.lastBlock()
     with BusyCursor():
         self.reformat_blocks(0, 0, lb.position() + lb.length())
Exemplo n.º 2
0
    def edit_book(self, file_name, progress_frac, selected_text):
        import subprocess

        from calibre.ebooks.oeb.polish.main import SUPPORTED
        from calibre.utils.ipc.launch import exe_path, macos_edit_book_bundle_path
        try:
            path = set_book_path.pathtoebook
        except AttributeError:
            return error_dialog(self, _('Cannot edit book'), _(
                'No book is currently open'), show=True)
        fmt = path.rpartition('.')[-1].upper().replace('ORIGINAL_', '')
        if fmt not in SUPPORTED:
            return error_dialog(self, _('Cannot edit book'), _(
                'The book must be in the %s formats to edit.'
                '\n\nFirst convert the book to one of these formats.'
            ) % (_(' or ').join(SUPPORTED)), show=True)
        exe = 'ebook-edit'
        if ismacos:
            exe = os.path.join(macos_edit_book_bundle_path(), exe)
        else:
            exe = exe_path(exe)
        cmd = [exe]
        if selected_text:
            cmd += ['--select-text', selected_text]
        from calibre.gui2.tweak_book.widgets import BusyCursor
        with sanitize_env_vars():
            subprocess.Popen(cmd + [path, file_name])
            with BusyCursor():
                time.sleep(2)
Exemplo n.º 3
0
 def fix_errors(self, container, errors):
     with BusyCursor():
         self.show_busy(_('Running fixers, please wait...'))
         QApplication.processEvents()
         changed = fix_errors(container, errors)
     self.run_checks(container)
     return changed
Exemplo n.º 4
0
 def do_search(self):
     text = unicode(self.search.text()).strip()
     if not text:
         return self.clear_search()
     with BusyCursor():
         chars = search_for_chars(text)
     self.show_chars(_('Search'), chars)
Exemplo n.º 5
0
 def do_search(self):
     text = unicode_type(self.search.text()).strip()
     if not text:
         return self.clear_search()
     with BusyCursor():
         chars = search_for_chars(text, and_tokens=not self.match_any.isChecked())
     self.show_chars(_('Search'), chars)
Exemplo n.º 6
0
def run_text_search(search, current_editor, current_editor_name, searchable_names, gui_parent, show_editor, edit_file):
    try:
        pat = get_search_regex(search)
    except InvalidRegex as e:
        return error_dialog(gui_parent, _('Invalid regex'), '<p>' + _(
            'The regular expression you entered is invalid: <pre>{0}</pre>With error: {1}').format(
                prepare_string_for_xml(e.regex), error_message(e)), show=True)
    editor, where, files, do_all, marked = initialize_search_request(search, 'count', current_editor, current_editor_name, searchable_names)
    with BusyCursor():
        if editor is not None:
            if editor.find_text(pat):
                return True
            if not files and editor.find_text(pat, wrap=True):
                return True
        for fname, syntax in iteritems(files):
            ed = editors.get(fname, None)
            if ed is not None:
                if ed.find_text(pat, complete=True):
                    show_editor(fname)
                    return True
            else:
                root = current_container().parsed(fname)
                if hasattr(root, 'xpath'):
                    raw = tostring(root, method='text', encoding='unicode', with_tail=True)
                else:
                    raw = current_container().raw_data(fname)
                if pat.search(raw) is not None:
                    edit_file(fname, syntax)
                    if editors[fname].find_text(pat, complete=True):
                        return True

    msg = '<p>' + _('No matches were found for %s') % ('<pre style="font-style:italic">' + prepare_string_for_xml(search['find']) + '</pre>')
    return error_dialog(gui_parent, _('Not found'), msg, show=True)
Exemplo n.º 7
0
    def run_checks(self, container):
        with BusyCursor():
            self.show_busy()
            QApplication.processEvents()
            errors = run_checks(container)
            self.hide_busy()

        for err in sorted(errors, key=lambda e:(100 - e.level, e.name)):
            i = QListWidgetItem('%s\xa0\xa0\xa0\xa0[%s]' % (err.msg, err.name), self.items)
            i.setData(Qt.UserRole, err)
            i.setIcon(icon_for_level(err.level))
        if errors:
            self.items.setCurrentRow(0)
            self.current_item_changed()
            self.items.setFocus(Qt.OtherFocusReason)
        else:
            self.clear_help()
Exemplo n.º 8
0
def run_search(searches, action, current_editor, current_editor_name,
               searchable_names, gui_parent, show_editor, edit_file,
               show_current_diff, add_savepoint, rewind_savepoint,
               set_modified):

    if isinstance(searches, dict):
        searches = [searches]

    editor, where, files, do_all, marked = initialize_search_request(
        searches[0], action, current_editor, current_editor_name,
        searchable_names)
    wrap = searches[0]['wrap']

    errfind = searches[0]['find']
    if len(searches) > 1:
        errfind = _('the selected searches')

    searches = [(get_search_regex(search), search['replace'])
                for search in searches]

    def no_match():
        QApplication.restoreOverrideCursor()
        msg = '<p>' + _('No matches were found for %s') % (
            '<pre style="font-style:italic">' +
            prepare_string_for_xml(errfind) + '</pre>')
        if not wrap:
            msg += '<p>' + _(
                'You have turned off search wrapping, so all text might not have been searched.'
                ' Try the search again, with wrapping enabled. Wrapping is enabled via the'
                ' "Wrap" checkbox at the bottom of the search panel.')
        return error_dialog(gui_parent, _('Not found'), msg, show=True)

    def do_find():
        for p, __ in searches:
            if editor is not None:
                if editor.find(p, marked=marked, save_match='gui'):
                    return
                if wrap and not files and editor.find(
                        p, wrap=True, marked=marked, save_match='gui'):
                    return
            for fname, syntax in files.iteritems():
                ed = editors.get(fname, None)
                if ed is not None:
                    if not wrap and ed is editor:
                        continue
                    if ed.find(p, complete=True, save_match='gui'):
                        return show_editor(fname)
                else:
                    raw = current_container().raw_data(fname)
                    if p.search(raw) is not None:
                        edit_file(fname, syntax)
                        if editors[fname].find(p,
                                               complete=True,
                                               save_match='gui'):
                            return
        return no_match()

    def no_replace(prefix=''):
        QApplication.restoreOverrideCursor()
        if prefix:
            prefix += ' '
        error_dialog(gui_parent,
                     _('Cannot replace'),
                     prefix +
                     _('You must first click Find, before trying to replace'),
                     show=True)
        return False

    def do_replace():
        if editor is None:
            return no_replace()
        for p, repl in searches:
            if editor.replace(p, repl, saved_match='gui'):
                return True
        return no_replace(
            _('Currently selected text does not match the search query.'))

    def count_message(action, count, show_diff=False):
        msg = _('%(action)s %(num)s occurrences of %(query)s' %
                dict(num=count, query=errfind, action=action))
        if show_diff and count > 0:
            d = MessageBox(MessageBox.INFO,
                           _('Searching done'),
                           prepare_string_for_xml(msg),
                           parent=gui_parent,
                           show_copy_button=False)
            d.diffb = b = d.bb.addButton(_('See what &changed'),
                                         d.bb.ActionRole)
            b.setIcon(QIcon(
                I('diff.png'))), d.set_details(None), b.clicked.connect(
                    d.accept)
            b.clicked.connect(partial(show_current_diff, allow_revert=True))
            d.exec_()
        else:
            info_dialog(gui_parent,
                        _('Searching done'),
                        prepare_string_for_xml(msg),
                        show=True)

    def do_all(replace=True):
        count = 0
        if not files and editor is None:
            return 0
        lfiles = files or {current_editor_name: editor.syntax}
        updates = set()
        raw_data = {}
        for n, syntax in lfiles.iteritems():
            if n in editors:
                raw = editors[n].get_raw_data()
            else:
                raw = current_container().raw_data(n)
            raw_data[n] = raw

        for p, repl in searches:
            for n, syntax in lfiles.iteritems():
                raw = raw_data[n]
                if replace:
                    raw, num = p.subn(repl, raw)
                    if num > 0:
                        updates.add(n)
                        raw_data[n] = raw
                else:
                    num = len(p.findall(raw))
                count += num

        for n in updates:
            raw = raw_data[n]
            if n in editors:
                editors[n].replace_data(raw)
            else:
                with current_container().open(n, 'wb') as f:
                    f.write(raw.encode('utf-8'))
        QApplication.restoreOverrideCursor()
        count_message(_('Replaced') if replace else _('Found'),
                      count,
                      show_diff=replace)
        return count

    with BusyCursor():
        if action == 'find':
            return do_find()
        if action == 'replace':
            return do_replace()
        if action == 'replace-find' and do_replace():
            return do_find()
        if action == 'replace-all':
            if marked:
                return count_message(
                    _('Replaced'),
                    sum(editor.all_in_marked(p, repl) for p, repl in searches))
            add_savepoint(_('Before: Replace all'))
            count = do_all()
            if count == 0:
                rewind_savepoint()
            else:
                set_modified()
            return
        if action == 'count':
            if marked:
                return count_message(
                    _('Found'),
                    sum(editor.all_in_marked(p) for p, __ in searches))
            return do_all(replace=False)
 def build(self):
     with BusyCursor():
         self.beginResetModel()
         self.font_data = font_family_data(current_container())
         self.do_sort()
         self.endResetModel()