rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
r[abs(float(img['height'])/float(img['width'])-1.25)] = img['src']
r[abs(float(re.search(r'[0-9.]+', img['height']).group())/float(re.search(r'[0-9.]+', img['width']).group())-1.25)] = img['src']
def _get_cover(soup, rdr): ans = None try: ans = soup.find('img', alt=re.compile('cover', flags=re.I))['src'] except TypeError: # meeehh, no handy alt-tag goodness, try some hackery # the basic idea behind this is that in general, the cover image # has a height:width ratio of ~1.25, whereas most of the nav # buttons ar...
def get_printer(self):
def get_printer(self, set_horz_margins=False):
def get_printer(self): printer = get_pdf_printer() printer.setPaperSize(QSizeF(self.size[0] * 10, self.size[1] * 10), QPrinter.Millimeter) printer.setPageMargins(0, 0, 0, 0, QPrinter.Point) printer.setOrientation(orientation(self.opts.orientation)) printer.setOutputFormat(QPrinter.PdfFormat) printer.setFullPage(True) r...
printer.setPageMargins(0, 0, 0, 0, QPrinter.Point)
if set_horz_margins: printer.setPageMargins(0., self.opts.margin_top, 0., self.opts.margin_bottom, QPrinter.Point) else: printer.setPageMargins(0, 0, 0, 0, QPrinter.Point)
def get_printer(self): printer = get_pdf_printer() printer.setPaperSize(QSizeF(self.size[0] * 10, self.size[1] * 10), QPrinter.Millimeter) printer.setPageMargins(0, 0, 0, 0, QPrinter.Point) printer.setOrientation(orientation(self.opts.orientation)) printer.setOutputFormat(QPrinter.PdfFormat) printer.setFullPage(True) r...
printer.setFullPage(True)
printer.setFullPage(not set_horz_margins)
def get_printer(self): printer = get_pdf_printer() printer.setPaperSize(QSizeF(self.size[0] * 10, self.size[1] * 10), QPrinter.Millimeter) printer.setPageMargins(0, 0, 0, 0, QPrinter.Point) printer.setOrientation(orientation(self.opts.orientation)) printer.setOutputFormat(QPrinter.PdfFormat) printer.setFullPage(True) r...
printer = self.get_printer()
printer = self.get_printer(set_horz_margins=True)
def _render_html(self, ok): if ok: item_path = os.path.join(self.tmp_path, '%i.pdf' % len(self.combine_queue)) self.logger.debug('\tRendering item %s as %i' % (os.path.basename(str(self.view.url().toLocalFile())), len(self.combine_queue))) printer = self.get_printer() printer.setOutputFileName(item_path) self.view.prin...
set_metadata=True,
def sync_to_device(self, on_card, delete_from_library, specific_format=None, send_ids=None, do_auto_convert=True): ids = [self.library_view.model().id(r) \ for r in self.library_view.selectionModel().selectedRows()] \ if send_ids is None else send_ids if not self.device_manager or not ids or len(ids) == 0: return
self.isbn = book.get('isbn13', book.get('isbn')) self.title = book.find('titlelong').string
self.isbn = unicode(book.get('isbn13', book.get('isbn'))) self.title = unicode(book.find('titlelong').string)
def __init__(self, book): Metadata.__init__(self, None, [])
self.title = book.find('title').string
self.title = unicode(book.find('title').string)
def __init__(self, book): Metadata.__init__(self, None, [])
self.publisher = book.find('publishertext').string
self.publisher = unicode(book.find('publishertext').string)
def __init__(self, book): Metadata.__init__(self, None, [])
self.comments = 'SUMMARY:\n'+summ.string
self.comments = 'SUMMARY:\n'+unicode(summ.string)
def __init__(self, book): Metadata.__init__(self, None, [])
if self.header_record.compression == 2:
if self.header_record.compression == 2 or self.header_record.compression == 258:
def decompress_text(self, number): if self.header_record.compression == 1: return self.section_data(number).decode('cp1252' if self.encoding is None else self.encoding) if self.header_record.compression == 2: from calibre.ebooks.compression.palmdoc import decompress_doc return decompress_doc(self.section_data(number))....
aTag['name'] = "%s-%s" % (current_date.year, current_date.month)
aTag['name'] = "bda_%s-%s" % (current_date.year, current_date.month)
def add_books_to_HTML_by_month(this_months_list, dtc): if len(this_months_list):
aTag['name'] = date_range.replace(' ','')
aTag['name'] = "bda_%s" % date_range.replace(' ','')
def add_books_to_HTML_by_date_range(date_range_list, date_range, dtc): if len(date_range_list): pIndexTag = Tag(soup, "p") pIndexTag['class'] = "date_index" aTag = Tag(soup, "a") aTag['name'] = date_range.replace(' ','') pIndexTag.insert(0,aTag) pIndexTag.insert(1,NavigableString(date_range)) divTag.insert(dtc,pIndexTa...
navPointByMonthTag['id'] = "%s-%s-ID" % (books_by_month[1].year,books_by_month[1].month )
navPointByMonthTag['id'] = "bda_%s-%s-ID" % (books_by_month[1].year,books_by_month[1].month )
def add_to_master_date_range_list(current_titles_list): book_count = len(current_titles_list) current_titles_list = " • ".join(current_titles_list) current_titles_list = self.formatNCXText(current_titles_list, dest='description') master_date_range_list.append((current_titles_list, date_range, book_count))
elif frag: self.view.scroll_to(frag)
else: if frag: self.view.scroll_to(frag) else: self.view.scroll_to('
def link_clicked(self, url): path = os.path.abspath(unicode(url.toLocalFile())) frag = None if path in self.iterator.spine: self.history.add(self.pos.value()) path = self.iterator.spine[self.iterator.spine.index(path)] if url.hasFragment(): frag = unicode(url.fragment()) if path != self.current_page: self.pending_ancho...
PRODUCT_ID = [0x129a,0x1292]
PRODUCT_ID = [0x129a]
def __init__(self, msg, details, level): Exception.__init__(self, msg) self.level = level self.details = details self.msg = msg
subprocess.check_call(['/usr/bin/hdiutil', 'create', '-srcfolder', os.path.abspath(d),
tdir = tempfile.mkdtemp() shutil.copytree(d, os.path.join(tdir, os.path.basename(d)), symlinks=True) os.symlink('/Applications', os.path.join(tdir, 'Applications')) subprocess.check_call(['/usr/bin/hdiutil', 'create', '-srcfolder', tdir,
def makedmg(self, d, volname, destdir='dist', internet_enable=True, format='UDBZ'): ''' Copy a directory d into a dmg named volname ''' info('\nCreating dmg') sys.stdout.flush() if not os.path.exists(destdir): os.makedirs(destdir) dmg = os.path.join(destdir, volname+'.dmg') if os.path.exists(dmg): os.unlink(dmg) subpro...
self.qaction.triggered.connect(self.choose_library)
self.qaction.triggered.connect(self.choose_library, type=Qt.QueuedConnection)
def genesis(self): self.count_changed(0) self.qaction.triggered.connect(self.choose_library)
self.action_choose.triggered.connect(self.choose_library)
self.action_choose.triggered.connect(self.choose_library, type=Qt.QueuedConnection)
def genesis(self): self.count_changed(0) self.qaction.triggered.connect(self.choose_library)
ac.triggered.connect(partial(self.qs_requested, i))
ac.triggered.connect(partial(self.qs_requested, i), type=Qt.QueuedConnection)
def genesis(self): self.count_changed(0) self.qaction.triggered.connect(self.choose_library)
self.quick_menu.addAction(name, partial(self.switch_requested, loc))
self.quick_menu.addAction(name, Dispatcher(partial(self.switch_requested, loc)))
def build_menus(self): db = self.gui.library_view.model().db locations = list(self.stats.locations(db)) for ac in self.switch_actions: ac.setVisible(False) self.quick_menu.clear() self.qs_locations = [i[1] for i in locations] for name, loc in locations: self.quick_menu.addAction(name, partial(self.switch_requested, loc...
if not (islinux or isfreebsd):
if not self.is_case_sensitive(path):
def create_oebbook(self, htmlpath, basedir, opts, log, mi): from calibre.ebooks.conversion.plumber import create_oebbook from calibre.ebooks.oeb.base import DirContainer, \ rewrite_links, urlnormalize, urldefrag, BINARY_MIME, OEB_STYLES, \ xpath from calibre import guess_type import cssutils oeb = create_oebbook(log, N...
if not (islinux or isfreebsd):
if not self.is_case_sensitive(tempfile.gettempdir()):
def resource_adder(self, link_, base=None): link = self.urlnormalize(link_) link, frag = self.urldefrag(link) link = unquote(link).replace('/', os.sep) if not link.strip(): return link_ if base and not os.path.isabs(link): link = os.path.join(base, link) try: link = os.path.abspath(link) except: return link_ if not os....
QThread.__init__(self, parent)
QObject.__init__(self, parent)
def __init__(self, parent, db, duplicates, db_adder): QThread.__init__(self, parent) self.db, self.db_adder = db, db_adder self.duplicates = duplicates
self.duplicates = duplicates def run(self): count = 1 for mi, cover, formats in self.duplicates: formats = [f for f in formats if not f.lower().endswith('.opf')] id = self.db.create_book_entry(mi, cover=cover, add_duplicates=True) self.db_adder.add_formats(id, formats) self.db_adder.number_of_books_added += 1 self.em...
self.duplicates = list(duplicates) self.count = 0 single_shot(self.add_one) def add_one(self): if not self.duplicates: self.adding_done.emit() return mi, cover, formats = self.duplicates.pop() formats = [f for f in formats if not f.lower().endswith('.opf')] id = self.db.create_book_entry(mi, cover=cover, add_duplicat...
def __init__(self, parent, db, duplicates, db_adder): QThread.__init__(self, parent) self.db, self.db_adder = db, db_adder self.duplicates = duplicates
self.emit(SIGNAL('update(PyQt_PyObject)'), _('Searching in')+' '+dirpath[0])
self.update.emit( _('Searching in')+' '+dirpath[0])
def walk(self, root): self.books = [] for dirpath in os.walk(root): if self.canceled: return self.emit(SIGNAL('update(PyQt_PyObject)'), _('Searching in')+' '+dirpath[0]) self.books += list(self.db.find_books_in_directory(dirpath[0], self.single_book_per_directory))
self.emit(SIGNAL('found(PyQt_PyObject)'), msg)
self.found.emit(msg)
def run(self): root = os.path.abspath(self.path) try: self.walk(root) except: try: if isinstance(root, unicode): root = root.encode(filesystem_encoding) self.walk(root) except Exception, err: import traceback traceback.print_exc() try: msg = unicode(err) except: msg = repr(err) self.emit(SIGNAL('found(PyQt_PyObject)'),...
self.emit(SIGNAL('found(PyQt_PyObject)'), self.books)
self.found.emit(self.books)
def run(self): root = os.path.abspath(self.path) try: self.walk(root) except: try: if isinstance(root, unicode): root = root.encode(filesystem_encoding) self.walk(root) except Exception, err: import traceback traceback.print_exc() try: msg = unicode(err) except: msg = repr(err) self.emit(SIGNAL('found(PyQt_PyObject)'),...
class DBAdder(Thread): def __init__(self, db, ids, nmap):
class DBAdder(QObject): def __init__(self, parent, db, ids, nmap): QObject.__init__(self, parent)
def run(self): root = os.path.abspath(self.path) try: self.walk(root) except: try: if isinstance(root, unicode): root = root.encode(filesystem_encoding) self.walk(root) except Exception, err: import traceback traceback.print_exc() try: msg = unicode(err) except: msg = repr(err) self.emit(SIGNAL('found(PyQt_PyObject)'),...
self.end = False
def __init__(self, db, ids, nmap): self.db, self.ids, self.nmap = db, dict(**ids), dict(**nmap) self.end = False self.critical = {} self.number_of_books_added = 0 self.duplicates = [] self.names, self.paths, self.infos = [], [], [] Thread.__init__(self) self.daemon = True self.input_queue = Queue() self.output_queue = ...
Thread.__init__(self) self.daemon = True
def __init__(self, db, ids, nmap): self.db, self.ids, self.nmap = db, dict(**ids), dict(**nmap) self.end = False self.critical = {} self.number_of_books_added = 0 self.duplicates = [] self.names, self.paths, self.infos = [], [], [] Thread.__init__(self) self.daemon = True self.input_queue = Queue() self.output_queue = ...
def run(self): while not self.end: try: id, opf, cover = self.input_queue.get(True, 0.2) except Empty: continue name = self.nmap.pop(id) title = None try: title = self.add(id, opf, cover, name) except: import traceback self.critical[name] = traceback.format_exc() title = name self.output_queue.put(title)
def end(self): self.input_queue.put((None, None, None)) def start(self): try: id, opf, cover = self.input_queue.get_nowait() except Empty: single_shot(self.start) return if id is None and opf is None and cover is None: return name = self.nmap.pop(id) title = None if DEBUG: st = time.time() try: title = self.add(id, op...
def run(self): while not self.end: try: id, opf, cover = self.input_queue.get(True, 0.2) except Empty: continue name = self.nmap.pop(id) title = None try: title = self.add(id, opf, cover, name) except: import traceback self.critical[name] = traceback.format_exc() title = name self.output_queue.put(title)
self.rfind = self.worker = self.timer = None
self.rfind = self.worker = None
def __init__(self, parent, db, callback, spare_server=None): QObject.__init__(self, parent) self.pd = ProgressDialog(_('Adding...'), parent=parent) self.spare_server = spare_server self.db = db self.pd.setModal(True) self.pd.show() self._parent = parent self.rfind = self.worker = self.timer = None self.callback = callb...
self.connect(self.pd, SIGNAL('canceled()'), self.canceled)
self.pd.canceled_signal.connect(self.canceled)
def __init__(self, parent, db, callback, spare_server=None): QObject.__init__(self, parent) self.pd = ProgressDialog(_('Adding...'), parent=parent) self.spare_server = spare_server self.db = db self.pd.setModal(True) self.pd.show() self._parent = parent self.rfind = self.worker = self.timer = None self.callback = callb...
self.connect(self.rfind, SIGNAL('update(PyQt_PyObject)'), self.pd.set_msg, Qt.QueuedConnection) self.connect(self.rfind, SIGNAL('found(PyQt_PyObject)'), self.add, Qt.QueuedConnection)
self.rfind.update.connect(self.pd.set_msg, type=Qt.QueuedConnection) self.rfind.found.connect(self.add, type=Qt.QueuedConnection)
def add_recursive(self, root, single=True): self.path = root self.pd.set_msg(_('Searching in all sub-directories...')) self.pd.set_min(0) self.pd.set_max(0) self.pd.value = 0 self.rfind = RecursiveFind(self, self.db, root, single) self.connect(self.rfind, SIGNAL('update(PyQt_PyObject)'), self.pd.set_msg, Qt.QueuedConne...
self.db_adder = DBAdder(self.db, self.ids, self.nmap)
self.db_adder = DBAdder(self, self.db, self.ids, self.nmap)
def add(self, books): if isinstance(books, basestring): error_dialog(self.pd, _('Path error'), _('The specified directory could not be processed.'), det_msg=books, show=True) return self.canceled() if not books: info_dialog(self.pd, _('No books'), _('No books found'), show=True) return self.canceled() books = [[b] if i...
QTimer.singleShot(200, self.update)
single_shot(self.update)
def add(self, books): if isinstance(books, basestring): error_dialog(self.pd, _('Path error'), _('The specified directory could not be processed.'), det_msg=books, show=True) return self.canceled() if not books: info_dialog(self.pd, _('No books'), _('No books found'), show=True) return self.canceled() books = [[b] if i...
self.db_adder.end = True
self.db_adder.end()
def canceled(self): self.continue_updating = False if self.rfind is not None: self.rfind.canceled = True if self.worker is not None: self.worker.canceled = True if hasattr(self, 'db_adder'): self.db_adder.end = True self.pd.hide() if not self.callback_called: self.callback(self.paths, self.names, self.infos) self.callb...
self.db_adder.end = True
self.db_adder.end()
def duplicates_processed(self): self.db_adder.end = True if not self.callback_called: self.callback(self.paths, self.names, self.infos) self.callback_called = True if hasattr(self, '__p_d'): self.__p_d.hide()
self.db_adder.end = True
self.db_adder.end()
def update(self): if self.entry_count <= 0: self.continue_updating = False self.pd.hide() self.process_duplicates() return
QTimer.singleShot(200, self.update)
single_shot(self.update)
def update(self): if self.entry_count <= 0: self.continue_updating = False self.pd.hide() self.process_duplicates() return
self.connect(self.__d_a, SIGNAL('added(PyQt_PyObject)'), pd.setValue) self.connect(self.__d_a, SIGNAL('adding_done()'), self.duplicates_processed) self.__d_a.start()
self.__d_a.added.connect(pd.setValue) self.__d_a.adding_done.connect(self.duplicates_processed)
def process_duplicates(self): duplicates = self.db_adder.duplicates if not duplicates: return self.duplicates_processed() self.pd.hide() files = [x[0].title for x in duplicates] if question_dialog(self._parent, _('Duplicates found!'), _('Books with the same title as the following already ' 'exist in the database. Add t...
self.timer = QTimer(self) self.connect(self.timer, SIGNAL('timeout()'), self.update) self.timer.start(200)
self.continue_updating = True single_shot(self.update)
def __init__(self, parent, db, callback, rows, path, opts, spare_server=None): QObject.__init__(self, parent) self.pd = ProgressDialog(_('Saving...'), parent=parent) self.spare_server = spare_server self.db = db self.opts = opts self.pd.setModal(True) self.pd.show() self.pd.set_min(0) self._parent = parent self.callbac...
if self.timer is not None: self.timer.stop()
self.continue_updating = False
def canceled(self): if self.timer is not None: self.timer.stop() if self.worker is not None: self.worker.canceled = True self.pd.hide() if not self.callback_called: self.callback(self.worker.path, self.failures, self.worker.error) self.callback_called = True
if not self.ids or not self.worker.is_alive(): self.timer.stop() self.pd.hide()
if not self.continue_updating: return if not self.worker.is_alive():
def update(self): if not self.ids or not self.worker.is_alive(): self.timer.stop() self.pd.hide() while self.ids: before = len(self.ids) self.get_result() if before == len(self.ids): for i in list(self.ids): self.failures.add(('id:%d'%i, 'Unknown error')) self.ids.remove(i) break if not self.callback_called: try: self....
break
if not self.ids: self.continue_updating = False self.pd.hide()
def update(self): if not self.ids or not self.worker.is_alive(): self.timer.stop() self.pd.hide() while self.ids: before = len(self.ids) self.get_result() if before == len(self.ids): for i in list(self.ids): self.failures.add(('id:%d'%i, 'Unknown error')) self.ids.remove(i) break if not self.callback_called: try: self....
self.worker.join(1.5)
self.worker.join(2)
def update(self): if not self.ids or not self.worker.is_alive(): self.timer.stop() self.pd.hide() while self.ids: before = len(self.ids) self.get_result() if before == len(self.ids): for i in list(self.ids): self.failures.add(('id:%d'%i, 'Unknown error')) self.ids.remove(i) break if not self.callback_called: try: self....
self.callback_called = True return self.get_result()
if self.continue_updating: self.get_result() single_shot(self.update)
def update(self): if not self.ids or not self.worker.is_alive(): self.timer.stop() self.pd.hide() while self.ids: before = len(self.ids) self.get_result() if before == len(self.ids): for i in list(self.ids): self.failures.add(('id:%d'%i, 'Unknown error')) self.ids.remove(i) break if not self.callback_called: try: self....
pml_img = os.path.basename(pmlfile)[0] + '_img' img_dir = pml_img if os.path.exists(pml_img) else 'images' if \ os.path.exists('images') else ''
pml_img = os.path.splitext(pmlfile)[0] + '_img' i_img = os.path.join(os.path.dirname(pmlfile),'images') img_dir = pml_img if os.path.isdir(pml_img) else i_img if \ os.path.isdir(i_img) else ''
def run(self, pmlfile): import zipfile
f.fileName = fileName
f.fileName = fileName.replace(os.sep, '/')
def AppendPlain(self, fileName, tdir): f = FileStream() f.attr = 0x41000000 f.fileSize = os.path.getsize(os.path.join(tdir,fileName)) f.fileBody = open(os.path.join(tdir,fileName), 'rb').read() f.fileName = fileName print f.fileSize self.files.append(f)
f.fileName = fileName
f.fileName = fileName.replace(os.sep, '/')
def AppendBinary(self, fileName, tdir): f = FileStream() f.attr = 0x01000000 f.fileSize = os.path.getsize(os.path.join(tdir,fileName)) f.fileBody = open(os.path.join(tdir,fileName), 'rb').read() f.fileName = fileName print f.fileSize self.files.append(f)
lb_added.artist.set(metadata.authors[0])
def _update_iTunes_metadata(self, metadata, db_added, lb_added, this_book): ''' ''' if DEBUG: self.log.info(" ITUNES._update_iTunes_metadata()")
db_added.artist.set(metadata.authors[0])
def _update_iTunes_metadata(self, metadata, db_added, lb_added, this_book): ''' ''' if DEBUG: self.log.info(" ITUNES._update_iTunes_metadata()")
lb_added.Artist = metadata.authors[0]
def _update_iTunes_metadata(self, metadata, db_added, lb_added, this_book): ''' ''' if DEBUG: self.log.info(" ITUNES._update_iTunes_metadata()")
db_added.Artist = metadata.authors[0]
def _update_iTunes_metadata(self, metadata, db_added, lb_added, this_book): ''' ''' if DEBUG: self.log.info(" ITUNES._update_iTunes_metadata()")
debug_print('Timezone votes: %d GMT, %d LTZ, use_tz_var='%
debug_print('Timezone votes: %d GMT, %d LTZ, use_tz_var= %d'%
def update(self, booklists, collections_attributes): debug_print('Starting update', collections_attributes) for i, booklist in booklists.items(): playlist_map = self.build_id_playlist_map(i) debug_print('Updating XML Cache:', i) root = self.record_roots[i] lpath_map = self.build_lpath_map(root) gtz_count = ltz_count = ...
set_metadata=False)
set_metadata=False, set_social_metadata=False)
def __init__(self, listener, opts, actions, parent=None): self.preferences_action, self.quit_action = actions self.spare_servers = [] MainWindow.__init__(self, opts, parent) # Initialize fontconfig in a separate thread as this can be a lengthy # process if run for the first time on this machine from calibre.utils.fonts...
elif datatype == 'float' and key.endswith('_index'): res = self.format_series_index(res)
def format_field_extended(self, key, series_with_index=True): from calibre.ebooks.metadata import authors_to_string ''' returns the tuple (field_name, formatted_value) ''' if key in self.custom_field_keys(): res = self.get(key, None) cmeta = self.get_user_metadata(key, make_copy=False) name = unicode(cmeta['name']) if ...
lpath = self.normalize_path(prefix + lpath)
def add_books_to_metadata(self, locations, metadata, booklists): metadata = iter(metadata) for i, location in enumerate(locations): self.report_progress((i+1) / float(len(locations)), _('Adding books to device metadata listing...')) info = metadata.next() blist = 2 if location[1] == 'cardb' else 1 if location[1] == 'ca...
outfile.write('%s\n' % ','.join(fields))
outfile.write(u'%s\n' % u','.join(fields))
def run(self, path_to_output, opts, db): from calibre.utils.logging import Log
outstr += '"%s",' % str(item).replace('"','""')
outstr += u'"%s",' % unicode(item).replace('"','""')
def run(self, path_to_output, opts, db): from calibre.utils.logging import Log
outstr += '"%s"\n' % str(item).replace('"','""')
outstr += u'"%s"\n' % unicode(item).replace('"','""')
def run(self, path_to_output, opts, db): from calibre.utils.logging import Log
outfile.write(outstr)
outfile.write(outstr.encode('utf-8'))
def run(self, path_to_output, opts, db): from calibre.utils.logging import Log
self.number_of_books_added += 1
def add(self, id, opf, cover, name): formats = self.ids.pop(id) if opf.endswith('.error'): mi = MetaInformation('', [_('Unknown')]) self.critical[name] = open(opf, 'rb').read().decode('utf-8', 'replace') else: try: mi = MetaInformation(OPF(opf)) except: import traceback mi = MetaInformation('', [_('Unknown')]) self.cri...
except TypeError:
except:
def add_book(self, mi, name, size, ctime): """ Add a node into DOM tree representing a book """ book = self.book_by_path(name) if book is not None: self.remove_book(name) node = self.document.createElement(self.prefix + "text") mime = MIME_MAP[name[name.rfind(".")+1:].lower()] cid = self.max_id()+1 sourceid = str(self[...
self.timer = QTimer(self)
def add(self, books): if isinstance(books, basestring): error_dialog(self.pd, _('Path error'), _('The specified directory could not be processed.'), det_msg=books, show=True) return self.canceled() if not books: info_dialog(self.pd, _('No books'), _('No books found'), show=True) return self.canceled() books = [[b] if i...
self.connect(self.timer, SIGNAL('timeout()'), self.update)
def add(self, books): if isinstance(books, basestring): error_dialog(self.pd, _('Path error'), _('The specified directory could not be processed.'), det_msg=books, show=True) return self.canceled() if not books: info_dialog(self.pd, _('No books'), _('No books found'), show=True) return self.canceled() books = [[b] if i...
self.timer.start(200)
self.continue_updating = True QTimer.singleShot(200, self.update)
def add(self, books): if isinstance(books, basestring): error_dialog(self.pd, _('Path error'), _('The specified directory could not be processed.'), det_msg=books, show=True) return self.canceled() if not books: info_dialog(self.pd, _('No books'), _('No books found'), show=True) return self.canceled() books = [[b] if i...
if self.timer is not None: self.timer.stop()
def canceled(self): if self.rfind is not None: self.rfind.canceled = True if self.timer is not None: self.timer.stop() if self.worker is not None: self.worker.canceled = True if hasattr(self, 'db_adder'): self.db_adder.end = True self.pd.hide() if not self.callback_called: self.callback(self.paths, self.names, self.inf...
self.timer.stop()
self.continue_updating = False
def update(self): if self.entry_count <= 0: self.timer.stop() self.pd.hide() self.process_duplicates() return
try: row = self.db.row(id) except: row = -1 if row > -1: self.beginRemoveRows(QModelIndex(), row, row)
def delete_books_by_id(self, ids): for id in ids: try: row = self.db.row(id) except: row = -1 if row > -1: self.beginRemoveRows(QModelIndex(), row, row) self.db.delete_book(id) if row > -1: self.endRemoveRows() self.count_changed() self.clear_caches()
if row > -1: self.endRemoveRows()
def delete_books_by_id(self, ids): for id in ids: try: row = self.db.row(id) except: row = -1 if row > -1: self.beginRemoveRows(QModelIndex(), row, row) self.db.delete_book(id) if row > -1: self.endRemoveRows() self.count_changed() self.clear_caches()
if self.revA3 != SNBFile.REVA3: return False
def IsValid(self): if self.magic != SNBFile.MAGIC: return False if self.rev80 != SNBFile.REV80: return False if self.revA3 != SNBFile.REVA3: return False if self.revZ1 != SNBFile.REVZ1: return False if self.revZ2 != SNBFile.REVZ2: return False if self.vfatSize != len(self.vfat): return False if self.fileCount != len(se...
json.dump(js, f, indent=2, encoding='utf-8')
f.write(json.dumps(js, indent=2, encoding='utf-8'))
def write_prefix(prefix, listid): if prefix is not None and isinstance(booklists[listid], self.booklist_class): if not os.path.exists(prefix): os.makedirs(self.normalize_path(prefix)) js = [item.to_json() for item in booklists[listid] if hasattr(item, 'to_json')] with open(self.normalize_path(os.path.join(prefix, self....
view.setCurrentIndex(ci) sm = view.selectionModel() sm.select(ci, sm.Select)
view.set_current_row(row)
def delete_books(self, *args): ''' Delete selected books from device or library. ''' view = self.current_view() rows = view.selectionModel().selectedRows() if not rows or len(rows) == 0: return if self.stack.currentIndex() == 0: if not confirm('<p>'+_('The selected books will be ' '<b>permanently deleted</b> and the fi...
Metadata.__init__(self, None, [])
Metadata.__init__(self, None)
def __init__(self, book): Metadata.__init__(self, None, [])
self.title = tostring(book.find('titlelong')) if not self.title: self.title = tostring(book.find('title')) if not self.title: self.title = _('Unknown')
title = tostring(book.find('titlelong')) if not title: title = tostring(book.find('title')) self.title = title
def tostring(e): if not hasattr(e, 'string'): return None ans = e.string if ans is not None: ans = unicode(ans).strip() if not ans: ans = None return ans
self.authors = []
authors = []
def tostring(e): if not hasattr(e, 'string'): return None ans = e.string if ans is not None: ans = unicode(ans).strip() if not ans: ans = None return ans
self.authors.extend([a.strip() for a in au.split('&amp;')])
authors.extend([a.strip() for a in au.split('&amp;')]) if authors: self.authors = authors
def tostring(e): if not hasattr(e, 'string'): return None ans = e.string if ans is not None: ans = unicode(ans).strip() if not ans: ans = None return ans
self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size,
self.fp.write(struct.pack("<LLL", zinfo.CRC, zinfo.compress_size,
def writestr(self, zinfo_or_arcname, bytes, permissions=0600, compression=ZIP_DEFLATED, raw_bytes=False): """Write a file into the archive. The contents is the string 'bytes'. 'zinfo_or_arcname' is either a ZipInfo instance or the name of the file in the archive.""" assert not raw_bytes or (raw_bytes and isinstance(z...
ans = self.javascript('document.body.offsetHeight', 'int') if ans == 0: ans = self.mainFrame().contentsSize().height() return ans
j = self.javascript('document.body.offsetHeight', 'int') q = self.mainFrame().contentsSize().height() if q == j: return j if min(j, q) <= 0: return max(j, q) window_height = self.window_height if j == window_height: return j if q < 1.2*j else q return j
def height(self): ans = self.javascript('document.body.offsetHeight', 'int') # contentsSize gives inaccurate results if ans == 0: ans = self.mainFrame().contentsSize().height() return ans
body = self.mainFrame().documentElement().findFirst('body') if body.isNull(): return old_padding = unicode(body.styleProperty('padding-bottom', body.ComputedStyle)).strip() padding = u'%dpx'%amount if old_padding != padding: body.setStyleProperty('padding-bottom', padding + ' !important')
s = QSize(-1, -1) if amount == 0 else QSize(self.width, self.height+amount) self.setPreferredContentsSize(s)
def set_bottom_padding(self, amount): body = self.mainFrame().documentElement().findFirst('body') if body.isNull(): return old_padding = unicode(body.styleProperty('padding-bottom', body.ComputedStyle)).strip() padding = u'%dpx'%amount if old_padding != padding: body.setStyleProperty('padding-bottom', padding + ' !impo...
if self.document.at_bottom:
if self.document.at_bottom or ddelta <= 0:
def next_page(self): window_height = self.document.window_height delta_y = window_height - 25 if self.document.at_bottom: if self.manager is not None: self.manager.next_document() else: oopos = self.document.ypos #print '\nOriginal position:', oopos self.document.set_bottom_padding(0) opos = self.document.ypos #print '...
self._is_case_sensitive = os.path.exists(path.lower()) \ and os.path.exists(path.upper())
self._is_case_sensitive = not (os.path.exists(path.lower()) \ and os.path.exists(path.upper()))
def is_case_sensitive(self, path): if getattr(self, '_is_case_sensitive', None) is not None: return self._is_case_sensitive if not path or not os.path.exists(path): return islinux or isfreebsd self._is_case_sensitive = os.path.exists(path.lower()) \ and os.path.exists(path.upper()) return self._is_case_sensitive
collections_lpaths = {}
def get_collections(self, collection_attributes): from calibre.devices.usbms.driver import debug_print debug_print('Starting get_collections:', prefs['manage_device_metadata']) debug_print('Renaming rules:', tweaks['sony_collection_renaming_rules'])
collections[cat_name] = [] collections_lpaths[cat_name] = set() if lpath in collections_lpaths[cat_name]: continue collections_lpaths[cat_name].add(lpath)
collections[cat_name] = {}
def get_collections(self, collection_attributes): from calibre.devices.usbms.driver import debug_print debug_print('Starting get_collections:', prefs['manage_device_metadata']) debug_print('Renaming rules:', tweaks['sony_collection_renaming_rules'])
collections[cat_name].append( (book, book.get(attr+'_index', sys.maxint)))
if doing_dc: collections[cat_name][lpath] = \ (book, book.get('series_index', sys.maxint)) else: collections[cat_name][lpath] = \ (book, book.get(attr+'_index', sys.maxint))
def get_collections(self, collection_attributes): from calibre.devices.usbms.driver import debug_print debug_print('Starting get_collections:', prefs['manage_device_metadata']) debug_print('Renaming rules:', tweaks['sony_collection_renaming_rules'])
collections[cat_name].append( (book, book.get('title_sort', 'zzzz')))
if lpath not in collections[cat_name]: collections[cat_name][lpath] = \ (book, book.get('title_sort', 'zzzz'))
def get_collections(self, collection_attributes): from calibre.devices.usbms.driver import debug_print debug_print('Starting get_collections:', prefs['manage_device_metadata']) debug_print('Renaming rules:', tweaks['sony_collection_renaming_rules'])
for category, books in collections.items():
for category, lpaths in collections.items(): books = lpaths.values()
def get_collections(self, collection_attributes): from calibre.devices.usbms.driver import debug_print debug_print('Starting get_collections:', prefs['manage_device_metadata']) debug_print('Renaming rules:', tweaks['sony_collection_renaming_rules'])
if ImageID != None:
if ImageID == None:
def delete_via_sql(self, ContentID, ContentType): # Delete Order: # 1) shortcover_page # 2) volume_shorcover # 2) content
f.write("<HTML><HEAD></HEAD><BODY>\r\n")
f.write('<html><head><meta http-equiv="Content-type"' ' content="text/html;charset=UTF-8" /></head><body>\n')
def _create_html_root(self, hhcpath, log): hhcdata = self._read_file(hhcpath) hhcroot = html.fromstring(hhcdata) chapters = self._process_nodes(hhcroot) #print "=============================" #print "Printing hhcroot" #print etree.tostring(hhcroot, pretty_print=True) #print "=============================" log.debug('Fo...
url = "<br /><a href=" + rsrcpath + ">" + title + " </a>\r\n"
url = "<br /><a href=" + rsrcpath + ">" + title + " </a>\n" if isinstance(url, unicode): url = url.encode('utf-8')
def _create_html_root(self, hhcpath, log): hhcdata = self._read_file(hhcpath) hhcroot = html.fromstring(hhcdata) chapters = self._process_nodes(hhcroot) #print "=============================" #print "Printing hhcroot" #print etree.tostring(hhcroot, pretty_print=True) #print "=============================" log.debug('Fo...
f.write("</BODY></HTML>")
f.write("</body></html>")
def _create_html_root(self, hhcpath, log): hhcdata = self._read_file(hhcpath) hhcroot = html.fromstring(hhcdata) chapters = self._process_nodes(hhcroot) #print "=============================" #print "Printing hhcroot" #print etree.tostring(hhcroot, pretty_print=True) #print "=============================" log.debug('Fo...
if not cls.SUPPORTS_USE_AUTHOR_SORT:
if cls.SUPPORTS_USE_AUTHOR_SORT:
def save_settings(cls, config_widget): proxy = cls._configProxy() proxy['format_map'] = config_widget.format_map() if cls.SUPPORTS_SUB_DIRS: proxy['use_subdirs'] = config_widget.use_subdirs() if not cls.MUST_READ_METADATA: proxy['read_metadata'] = config_widget.read_metadata() if not cls.SUPPORTS_USE_AUTHOR_SORT: proxy...
author = string_to_authors(unicode(self.authors.text()))[0]
try: author = string_to_authors(unicode(self.authors.text()))[0] except IndexError: author = ''
def fetch_metadata(self): isbn = re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text())) title = qstring_to_unicode(self.title.text()) author = string_to_authors(unicode(self.authors.text()))[0] publisher = qstring_to_unicode(self.publisher.currentText()) if isbn or title or author or publisher: d = FetchMetadata(sel...
self._formatted_date = self.localtime.strftime(" [%a, %d %b %H:%M]")
self._formatted_date = strftime(" [%a, %d %b %H:%M]", t=self.localtime.timetuple())
def fget(self): if self._formatted_date is None: self._formatted_date = self.localtime.strftime(" [%a, %d %b %H:%M]") return self._formatted_date
self.open_feedback_msg(dev.get_gui_name(), e.feedback_msg)
if dev not in self.ejected_devices: self.open_feedback_msg(dev.get_gui_name(), e.feedback_msg) self.ejected_devices.add(dev)
def do_connect(self, connected_devices, device_kind): for dev, detected_device in connected_devices: if dev.OPEN_FEEDBACK_MESSAGE is not None: self.open_feedback_slot(dev.OPEN_FEEDBACK_MESSAGE) try: dev.reset(detected_device=detected_device, report_progress=self.report_progress) dev.open() except OpenFeedback, e: self....
QItemDelegate.__init__(self, parent)
QStyledItemDelegate.__init__(self, parent)
def __init__(self, parent): QItemDelegate.__init__(self, parent) self._parent = parent self.star_path = QPainterPath() self.star_path.moveTo(90, 50) for i in range(1, 5): self.star_path.lineTo(50 + 40 * cos(0.8 * i * pi), \ 50 + 40 * sin(0.8 * i * pi)) self.star_path.closeSubpath() self.star_path.setFillRule(Qt.Winding...
QApplication.style().drawControl(QStyle.CE_ItemViewItem, option,
style.drawControl(QStyle.CE_ItemViewItem, option,
def draw_star(): painter.save() painter.scale(self.factor, self.factor) painter.translate(50.0, 50.0) painter.rotate(-20) painter.translate(-50.0, -50.0) painter.drawPath(self.star_path) painter.restore()
self.drawFocus(painter, option, option.rect)
def draw_star(): painter.save() painter.scale(self.factor, self.factor) painter.translate(50.0, 50.0) painter.rotate(-20) painter.translate(-50.0, -50.0) painter.drawPath(self.star_path) painter.restore()