Note: This action is now available as part of the builtin Single Field Edit Action. (by choosing the template option and typing the pre-defined format in the template editor).
Code:
import subprocess
import os
from qt.core import (QApplication, Qt, QWidget, QHBoxLayout, QVBoxLayout,
QGroupBox, QToolButton)
from calibre import prints
from calibre.constants import DEBUG, iswindows
from calibre.gui2 import error_dialog, choose_files
from calibre_plugins.action_chains.actions.base import ChainAction
from calibre_plugins.action_chains.common_utils import DragDropComboBox, get_icon
class ConfigWidget(QWidget):
def __init__(self, plugin_action):
QWidget.__init__(self)
self.plugin_action = plugin_action
self.gui = plugin_action.gui
self.db = self.gui.current_db
self.template = ''
self._init_controls()
def _init_controls(self):
l = QVBoxLayout()
self.setLayout(l)
self.format_box = QGroupBox(_('&Choose format:'))
l.addWidget(self.format_box)
format_layout = QVBoxLayout()
self.format_box.setLayout(format_layout)
self.format_combo = DragDropComboBox(self, drop_mode='file')
format_layout.addWidget(self.format_combo)
hl1 = QHBoxLayout()
format_layout.addLayout(hl1)
hl1.addWidget(self.format_combo, 1)
self.choose_format_button = QToolButton(self)
self.choose_format_button.setToolTip(_('Choose format'))
self.choose_format_button.setIcon(get_icon('document_open.png'))
self.choose_format_button.clicked.connect(self._choose_file)
hl1.addWidget(self.choose_format_button)
def _choose_file(self):
files = choose_files(None, _('Select format dialog'), _('Select a format'),
all_files=True, select_only_single_file=True)
if not files:
return
format_path = files[0]
if iswindows:
format_path = os.path.normpath(format_path)
self.block_events = True
existing_index = self.format_combo.findText(format_path, Qt.MatchExactly)
if existing_index >= 0:
self.format_combo.setCurrentIndex(existing_index)
else:
self.format_combo.insertItem(0, format_path)
self.format_combo.setCurrentIndex(0)
self.block_events = False
def load_settings(self, settings):
if settings:
self.format_combo.setCurrentText(settings['path_to_format'])
def save_settings(self):
settings = {}
settings['path_to_format'] = self.format_combo.currentText().strip()
return settings
class AddFormatAction(ChainAction):
name = 'Add Format'
support_scopes = True
def run(self, gui, settings, chain):
book_ids = chain.scope().get_book_ids()
db = gui.current_db
path = settings['path_to_format']
try:
fmt = os.path.splitext(path)[-1].lower().replace('.', '').upper()
except:
fmt = ''
for book_id in book_ids:
db.new_api.add_format(book_id, fmt, path)
def validate(self, settings):
if not settings:
return (_('Settings Error'), _('You must configure this action before running it'))
if not settings['path_to_format']:
return (_('No Format'), _('You must specify a path to valid format'))
return True
def config_widget(self):
return ConfigWidget