Skip to content

Commit

Permalink
Cleaning, changes in README
Browse files Browse the repository at this point in the history
  • Loading branch information
pirtim committed Mar 27, 2017
1 parent 5c0b026 commit 582dfb9
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 46 deletions.
32 changes: 23 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,37 @@ Installation
---
1. Right click the preferences button in calibre, select get new plugins, scroll down the list and choose the DjVuMaker plugin to install
* Or clone this repo and install from source

````bash
git clone https://github.com/kfix/calibre_plugin_djvumaker
cd calibre_plugin_djvumaker
calibre-customize -b ./
````
2. [Required] Build the conversion programs (**fixme: works only on OSX**)
```calibre-debug -R djvumaker install_deps```
```bash
git clone https://github.com/kfix/calibre_plugin_djvumaker
cd calibre_plugin_djvumaker
calibre-customize -b ./
```
2. [Required] Build the conversion programs (**fixme: works only on macOS**, check next section for solution)
```calibre-debug -R djvumaker -- backend install djvudigital```
3. (Re)start Calibre and start converting your PDF books!

4. [Optional] go to Preferences -> Interface::Toolbars so you can place the DJVU menu where you see fit.

Installation of secondary backend
---
For all having troubles with building GsDjvu there is possibility to install secondary backend - [pdf2djvu](http://jwilk.net/software/pdf2djvu).
The "pdf2djvu" is a pdf to djvu converter developed by Jakub Wilk ([GitHub](https://github.com/jwilk/pdf2djvu)).
Although slower than djvudigital it's installation is much simplier. There is also a posibility to install it through *this* plugin:
```bash
calibre-debug -R djvumaker -- backend install pdf2djvu #(should work for any OS)
calibre-debug -R djvumaker -- backend set pdf2djvu
```
Also you can just add pdf2djvu to your path and:
```calibre-debug -R djvumaker -- backend set pdf2djvu```
The main diferences betwent pdf2djvu and djvudigital are listed [here](https://github.com/jwilk/pdf2djvu/blob/master/doc/djvudigital.txt).
Under the Hood
---
There are a few implementations of DjVU tools in the wild, but the fastest and most robust free one is the DjVuLibre suite and its Ghostscript plugin "GsDjvu".
GsDjvu was witlessly licensed by AT&T with a "free" but GPL-incompatible license which makes pre-compiled packages impossible to publically distribute.
Therefore both packages must be built by the user in a complicated procedure, which the plugin tries to facilitate when installed into Calibre.
Therefore both packages must be built by the user in a complicated procedure, which the plugin tries to facilitate when installed into Calibre.
Q: Why not write a "standard" Conversion Plugin for DjVU?
Expand Down
39 changes: 14 additions & 25 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
def empty_function(*args, **kwargs):
pass
if DEBUG:
printsd = partial(prints, '{}:'.format('DEBUG')) # for DEBUG msg
printsd = partial(prints, '{}:'.format('DEBUG')) # for DEBUG msgs
else:
printsd = empty_function

Expand All @@ -60,10 +60,14 @@ class DJVUmaker(FileTypePlugin, InterfaceActionBase): #multiple inheritance for
minimum_calibre_version = (2, 22, 0) #needs the new db api w/id() bugfix, and podofo.image_count()
actual_plugin = 'calibre_plugins.djvumaker.gui:ConvertToDJVUAction' #InterfaceAction plugin location
REGISTERED_BACKENDS = collections.OrderedDict()

@classmethod
def register_backend(cls, fun):
cls.REGISTERED_BACKENDS[fun.__name__] = fun
return fun

def __init__(self, *args, **kwargs):
super(DJVUmaker, self).__init__(*args, **kwargs)
# REGISTERED_BACKENDS = ['pdf2djvu', 'djvudigital']
# Set default preferences
DEFAULT_STORE_VALUES = {}
DEFAULT_STORE_VALUES['plugin_version'] = PLUGINVER
Expand All @@ -89,19 +93,9 @@ def __init__(self, *args, **kwargs):

def run_backend(self, *args, **kwargs):
use_backend = self.plugin_prefs['use_backend']

# DEBUG DEL
use_backend = 'pdf2djvu'
prints(subprocess.check_output(['pwd']))
kwargs['preferences'] = self.plugin_prefs

return self.REGISTERED_BACKENDS[use_backend](*args, **kwargs)

@classmethod
def register_backend(cls, fun):
cls.REGISTERED_BACKENDS[fun.__name__] = fun
return fun

def customization_help(self, gui=False):
return 'Enter additional `djvudigital --help` command-flags here:'
# os.system('MANPAGER=cat djvudigital --help')
Expand All @@ -113,7 +107,6 @@ def cli_main(self, args):
'''Handles plugin cli interface'''
args = args[1:] # args[0] = PLUGINNAME
printsd('cli_main enter: args: ', args) # DEBUG
# from calibre_plugins.djvumaker.utils import create_cli_parser
parser = create_cli_parser(self, PLUGINNAME, PLUGINVER_DOT,
self.REGISTERED_BACKENDS.keys())
if len(args) == 0:
Expand Down Expand Up @@ -165,8 +158,6 @@ def cli_install_backend(self, args):
self.plugin_prefs.commit() # always use commit if uses nested dict
# TODO: inherit from JSONConfig and make better implementation for defaults
elif args.backend == 'pdf2djvu':
# raise NotImplementedError
# from calibre_plugins.djvumaker.utils import install_pdf2djvu
success, version = install_pdf2djvu(PLUGINNAME, self.plugin_prefs, log=prints)
# path?
# TODO: give flag where to installed_backend
Expand Down Expand Up @@ -197,9 +188,8 @@ def cli_set_backend(self, args):
def cli_convert(self, args):
printsd(args)
if args.all:
printsd('in all')
# return NotImplemented
'`calibre-debug -r djvumaker convert_all`'
printsd('in cli convert_all')
# `calibre-debug -r djvumaker convert_all`
prints("Press Enter to copy-convert all PDFs to DJVU, or CTRL+C to abort...")
raw_input('')
from calibre.library import db
Expand All @@ -214,7 +204,7 @@ def cli_convert(self, args):
printsd('path')
return NotImplemented
if is_rasterbook(args.path):
'`calibre-debug -r djvumaker test.pdf` -> tempfile(test.djvu)'
# `calibre-debug -r djvumaker test.pdf` -> tempfile(test.djvu)
djvu = self.run_backend(args.path)

if djvu:
Expand All @@ -228,9 +218,8 @@ def cli_convert(self, args):
os.system("djvused -e dump '%s'" % djvu)
os.system("djvused -v '%s'" % djvu)
elif args.id is not None:
printsd('in id')
# return NotImplemented
'`calibre-debug -r djvumaker 123 #id(123).pdf` -> tempfile(id(123).djvu)'
printsd('in convert by id')
# `calibre-debug -r djvumaker 123 #id(123).pdf` -> tempfile(id(123).djvu)
self.postimport(args.id, 'pdf') # bookid and book_format, can go really wrong

# -- calibre filetype plugin mandatory methods --
Expand Down Expand Up @@ -470,11 +459,11 @@ def raise_if_not_supported(srcdoc, supported_extensions):
def pdf2djvu(srcdoc, cmdflags, djvu, preferences):
'''pdf2djvu backend shell command generation'''
raise_if_not_supported(srcdoc, ['pdf'])
pdf2djvu_path, _, __, ___ = discover_backend('pdf2djvu', preferences, PLUGINNAME)
prints(pdf2djvu_path)
pdf2djvu_path, _, _, _ = discover_backend('pdf2djvu', preferences, PLUGINNAME)
if pdf2djvu_path is None:
raise OSError('pdf2djvu not found')
# command passed to subprocess
return [pdf2djvu_path, '-o', djvu.name, srcdoc]
# return [create_backend_link('pdf2djvu', backend_version), '-o', djvu.name, srcdoc]

@DJVUmaker.register_backend
@job_handler
Expand Down
23 changes: 11 additions & 12 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ def version_intlist_to_str(verintlist):
return '.'.join(map(str,verintlist))

def version_from_output(output):
'''Extracts version number from typical pdf2djvu --version output.'''
return output.splitlines()[0].split()[1]
def check_version_executable(executable_path):
return version_from_output(subprocess.check_output([executable_path, '--version'],
Expand Down Expand Up @@ -130,8 +131,8 @@ def create_backend_link(backend_name, version):
return os.path.join(os.path.join('djvumaker', '{}-{}'.format(backend_name, version), backend_name))

# DEBUG TODO:
class Installer_pdf2djvu(object):
pass
# class Installer_pdf2djvu(Installer):
# pass

def install_pdf2djvu(PLUGINNAME, preferences, log=print):
backend_path, saved_version, installed_version, path_version = discover_backend('pdf2djvu',
Expand Down Expand Up @@ -230,18 +231,14 @@ def gen_zip_url(code):
def gen_tar_url(code):
return r'https://github.com/jwilk/pdf2djvu/releases/download/{}/pdf2djvu-{}.tar.xz'.format(code, code)

# TODO: what with fallback!?! new argument
fallback_version = '0.9.5'
if iswindows:
fallback_arch_url = gen_zip_url(fallback_version)
arch_url = gen_zip_url(web_version)
else:
fallback_arch_url = gen_tar_url(fallback_version)
arch_url = gen_tar_url(web_version)

# DEBUG DEL
# arch_url = 'http://pkowalczyk.pl/almost-empty.zip'
# arch_url = 'http://pkowalczyk.pl/almost-empty.tar.xz'

arch_url = gen_tar_url(web_version)

def download_progress_bar(i, chunk, full):
''''args: a count of blocks transferred so far,
Expand All @@ -264,15 +261,15 @@ def check_msg(fpath, msg):
os.mkdir('djvumaker')
fpath, msg = urllib.urlretrieve(arch_url, os.path.join('.', 'djvumaker', get_url_basename(arch_url)),
download_progress_bar)
print()
# print() # should progess bar function handle this TODO:
if not check_msg(fpath, msg):
log('Cannot download current version {} from GitHub.'.format(web_version))
if web_version != fallback_version:
log('Trying download version {}...'.format(fallback_version), download_progress_bar)
fpath, msg_fallback = urllib.urlretrieve(fallback_arch_url, os.path.join('.','djvumaker',
get_url_basename(fallback_arch_url)),
download_progress_bar)
print()
# print() # should progess bar function handle this TODO:
if not check_msg(fpath, msg_fallback):
raise Exception('Cannot download pdf2djvu.')
else:
Expand All @@ -288,8 +285,9 @@ def unpack_zip_or_tar(PLUGINNAME, fpath, log):
with ZipFile(fpath, 'r') as myzip:
myzip.extractall(os.path.dirname(fpath))
else:
# Python 2.7 Standard Library cannot unpack tar.xz archive, do this manually or through shell
# it can not work on macOS
subprocess.call(['tar', 'xf', fpath, '-C', os.path.dirname(fpath)])
# raise Exception('Python 2.7 Standard Library cannot unpack tar.xz archive, do this manually')
log('Extracted downloaded archive')
os.remove(fpath)
log('Removed downloaded archive')
Expand All @@ -313,10 +311,11 @@ def printProgressBar(iteration, total, prefix = '', suffix = '', decimals = 1, l
bar = fill * filledLength + '-' * (length - filledLength)
prints('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r')
# Print New Line on Complete
if iteration == total:
if iteration >= total:
prints()

def ask_yesno_input(question, prints=print):
'''Ask user for yes/no input. Loops if other answer.'''
while True:
prints(question + ' (y/n)')
user_input = raw_input().lower()
Expand Down

0 comments on commit 582dfb9

Please sign in to comment.