Mostly code cleanup of PDF support code.

This commit is contained in:
Tomas Groth 2013-11-14 17:42:21 +01:00
parent a45dfd2d1b
commit 3acd18c102
5 changed files with 50 additions and 61 deletions

View File

@ -244,21 +244,17 @@ class PresentationMediaItem(MediaManagerItem):
items = self.list_view.selectedItems()
if len(items) > 1:
return False
filename = items[0].data(QtCore.Qt.UserRole)
file_type = os.path.splitext(filename)[1][1:]
if not self.display_type_combo_box.currentText():
return False
if context == ServiceItemContext.Live and (file_type == 'pdf' or file_type == 'xps'):
if (file_type == 'pdf' or file_type == 'xps') and context != ServiceItemContext.Service:
service_item.add_capability(ItemCapabilities.CanMaintain)
service_item.add_capability(ItemCapabilities.CanPreview)
service_item.add_capability(ItemCapabilities.CanLoop)
service_item.add_capability(ItemCapabilities.CanAppend)
# force a nonexistent theme
service_item.theme = -1
# Why the loop when we above return False if len(items) is > 1?
for bitem in items:
filename = bitem.data(QtCore.Qt.UserRole)
(path, name) = os.path.split(filename)
@ -270,16 +266,17 @@ class PresentationMediaItem(MediaManagerItem):
controller = self.controllers[processor]
service_item.processor = None
doc = controller.add_document(filename)
if doc.get_thumbnail_path(1, True) is None or not os.path.isfile(os.path.join(doc.get_temp_folder(), 'mainslide001.png')):
if doc.get_thumbnail_path(1, True) is None or not os.path.isfile(
os.path.join(doc.get_temp_folder(), 'mainslide001.png')):
doc.load_presentation()
i = 1
imagefile = 'mainslide%03d.png' % i
img = os.path.join(doc.get_temp_folder(), imagefile)
while os.path.isfile(img):
service_item.add_from_image(img, name)
image = os.path.join(doc.get_temp_folder(), imagefile)
while os.path.isfile(image):
service_item.add_from_image(image, name)
i += 1
imagefile = 'mainslide%03d.png' % i
img = os.path.join(doc.get_temp_folder(), imagefile)
image = os.path.join(doc.get_temp_folder(), imagefile)
doc.close_presentation()
return True
else:
@ -291,8 +288,6 @@ class PresentationMediaItem(MediaManagerItem):
else:
service_item.processor = self.display_type_combo_box.currentText()
service_item.add_capability(ItemCapabilities.ProvidesOwnDisplay)
# Why the loop when we above return False if len(items) is > 1?
for bitem in items:
filename = bitem.data(QtCore.Qt.UserRole)
(path, name) = os.path.split(filename)

View File

@ -33,6 +33,7 @@ from PyQt4 import QtCore
from openlp.core.lib import Registry
from openlp.core.ui import HideMode
from openlp.core.lib import ServiceItemContext
log = logging.getLogger(__name__)
@ -69,6 +70,7 @@ class Controller(object):
return
self.doc.slidenumber = slide_no
self.hide_mode = hide_mode
log.debug('add_handler, slidenumber: %d' % slide_no)
if self.is_live:
if hide_mode == HideMode.Screen:
Registry().execute('live_display_hide', HideMode.Screen)
@ -316,6 +318,14 @@ class MessageListener(object):
hide_mode = message[2]
file = item.get_frame_path()
self.handler = item.processor
#self.media_item.generate_slide_data(self, service_item, item=None, xml_version=False,remote=False, context=ServiceItemContext.Service)
if file.endswith('.pdf') or file.endswith('.xps'):
log.debug('Trying to convert from pdf to images for service-item')
if is_live:
self.media_item.generate_slide_data(self, item, None, False, False, ServiceItemContext.Live)
else:
self.media_item.generate_slide_data(self, item, None, False, False, ServiceItemContext.Preview)
if self.handler == self.media_item.Automatic:
self.handler = self.media_item.findControllerByType(file)
if not self.handler:
@ -326,9 +336,10 @@ class MessageListener(object):
controller = self.preview_handler
# when presenting PDF, we're using the image presentation code,
# so handler & processor is set to None, and we skip adding the handler.
log.debug('file: %s' % file)
if self.handler == None:
self.controller = controller
else:
else:
controller.add_handler(self.controllers[self.handler], file, hide_mode, message[3])
def slide(self, message):

View File

@ -58,14 +58,13 @@ class PdfController(PresentationController):
self.supports = ['pdf']
self.mudrawbin = ''
self.gsbin = ''
if self.check_installed() and self.mudrawbin != '':
if self.check_installed() and self.mudrawbin:
self.also_supports = ['xps']
def check_binary(program_path):
"""
Function that checks whether a binary is either ghostscript or mudraw or neither.
"""
program_type = None
runlog = ''
try:
@ -74,7 +73,6 @@ class PdfController(PresentationController):
runlog = e.output
except Exception:
runlog = ''
# Analyse the output to see it the program is mudraw, ghostscript or neither
for line in runlog.splitlines():
found_mudraw = re.search('usage: mudraw.*', line)
@ -88,8 +86,6 @@ class PdfController(PresentationController):
log.info('in check_binary, found: ' + program_type)
return program_type
def check_available(self):
"""
PdfController is able to run on this machine.
@ -103,44 +99,40 @@ class PdfController(PresentationController):
"""
log.debug('check_installed Pdf')
# Use the user defined program if given
if (Settings().value('presentations/enable_given_pdf_program')):
given_pdf_program = Settings().value('presentations/given_pdf_program')
type = self.check_binary(given_pdf_program)
if (Settings().value('presentations/enable_pdf_program')):
pdf_program = Settings().value('presentations/pdf_program')
type = self.check_binary(pdf_program)
if type == 'gs':
self.gsbin = given_pdf_program
self.gsbin = pdf_program
return True
elif type == 'mudraw':
self.mudrawbin = given_pdf_program
self.mudrawbin = pdf_program
return True
# Fallback to autodetection
application_path = AppLocation.get_directory(AppLocation.AppDir)
if os.name != 'nt':
if os.name == 'nt':
# for windows we only accept mudraw.exe in the base folder
application_path = AppLocation.get_directory(AppLocation.AppDir)
if os.path.isfile(application_path + '/../mudraw.exe'):
self.mudrawbin = application_path + '/../mudraw.exe'
else:
# First try to find mupdf
try:
self.mudrawbin = check_output(['which', 'mudraw']).decode(encoding='UTF-8').rstrip('\n')
except CalledProcessError:
self.mudrawbin = ''
# if mupdf isn't installed, fallback to ghostscript
if self.mudrawbin == '':
if not self.mudrawbin:
try:
self.gsbin = check_output(['which', 'gs']).rstrip('\n')
except CalledProcessError:
self.gsbin = ''
# Last option: check if mudraw is placed in OpenLP base folder
if self.mudrawbin == '' and self.gsbin == '':
if not self.mudrawbin and not self.gsbin:
application_path = AppLocation.get_directory(AppLocation.AppDir)
if os.path.isfile(application_path + '/../mudraw'):
self.mudrawbin = application_path + '/../mudraw'
else:
# for windows we only accept mudraw.exe in the base folder
application_path = AppLocation.get_directory(AppLocation.AppDir)
if os.path.isfile(application_path + '/../mudraw.exe'):
self.mudrawbin = application_path + '/../mudraw.exe'
if self.mudrawbin == '' and self.gsbin == '':
if not self.mudrawbin and not self.gsbin:
return False
else:
return True
@ -192,7 +184,6 @@ quit \n\
tmpfile = NamedTemporaryFile(delete=False)
tmpfile.write(postscript)
tmpfile.close()
# Run the script on the pdf to get the size
runlog = []
try:
@ -201,7 +192,6 @@ quit \n\
log.debug(' '.join(e.cmd))
log.debug(e.output)
os.unlink(tmpfile.name)
# Extract the pdf resolution from output, the format is " Size: x: <width>, y: <height>"
width = 0
height = 0
@ -212,12 +202,10 @@ quit \n\
break;
except AttributeError:
pass
# Calculate the ratio from pdf to screen
if width > 0 and height > 0:
width_ratio = size.right() / float(width)
height_ratio = size.bottom() / float(height)
# return the resolution that should be used. 72 is default.
if width_ratio > height_ratio:
return int(height_ratio * 72)
@ -231,7 +219,6 @@ quit \n\
Called when a presentation is added to the SlideController. It generates images from the PDF.
"""
log.debug('load_presentation pdf')
# Check if the images has already been created, and if yes load them
if os.path.isfile(os.path.join(self.get_temp_folder(), 'mainslide001.png')):
created_files = sorted(os.listdir(self.get_temp_folder()))
@ -240,16 +227,15 @@ quit \n\
self.image_files.append(os.path.join(self.get_temp_folder(), fn))
self.num_pages = len(self.image_files)
return True
size = ScreenList().current['size']
# Generate images from PDF that will fit the frame.
runlog = ''
try:
if not os.path.isdir(self.get_temp_folder()):
os.makedirs(self.get_temp_folder())
if self.controller.mudrawbin != '':
if self.controller.mudrawbin:
runlog = check_output([self.controller.mudrawbin, '-w', str(size.right()), '-h', str(size.bottom()), '-o', os.path.join(self.get_temp_folder(), 'mainslide%03d.png'), self.filepath])
elif self.controller.gsbin != '':
elif self.controller.gsbin:
resolution = self.gs_get_resolution(size)
runlog = check_output([self.controller.gsbin, '-dSAFER', '-dNOPAUSE', '-dBATCH', '-sDEVICE=png16m', '-r' + str(resolution), '-dTextAlphaBits=4', '-dGraphicsAlphaBits=4', '-sOutputFile=' + os.path.join(self.get_temp_folder(), 'mainslide%03d.png'), self.filepath])
created_files = sorted(os.listdir(self.get_temp_folder()))
@ -261,7 +247,6 @@ quit \n\
log.debug(runlog)
return False
self.num_pages = len(self.image_files)
# Create thumbnails
self.create_thumbnails()
return True
@ -273,8 +258,6 @@ quit \n\
log.debug('create_thumbnails pdf')
if self.check_thumbnails():
return
log.debug('create_thumbnails proceeding')
# use builtin function to create thumbnails from generated images
index = 1
for image in self.image_files:

View File

@ -137,12 +137,12 @@ class PresentationTab(SettingsTab):
checkbox.setChecked(Settings().value(self.settings_section + '/' + controller.name))
self.override_app_check_box.setChecked(Settings().value(self.settings_section + '/override app'))
# load pdf-program settings
enable_given_pdf_program = Settings().value(self.settings_section + '/enable_given_pdf_program')
self.pdf_program_check_box.setChecked(enable_given_pdf_program)
self.pdf_program_path.setReadOnly(not enable_given_pdf_program)
self.pdf_program_path.setPalette(self.get_grey_text_palette(not enable_given_pdf_program))
self.pdf_program_browse_button.setEnabled(enable_given_pdf_program)
pdf_program = Settings().value(self.settings_section + '/given_pdf_program')
enable_pdf_program = Settings().value(self.settings_section + '/enable_pdf_program')
self.pdf_program_check_box.setChecked(enable_pdf_program)
self.pdf_program_path.setReadOnly(not enable_pdf_program)
self.pdf_program_path.setPalette(self.get_grey_text_palette(not enable_pdf_program))
self.pdf_program_browse_button.setEnabled(enable_pdf_program)
pdf_program = Settings().value(self.settings_section + '/pdf_program')
if pdf_program:
self.pdf_program_path.setText(pdf_program)
@ -173,15 +173,15 @@ class PresentationTab(SettingsTab):
# Save pdf-settings
pdf_program = self.pdf_program_path.text()
enable_given_pdf_program = self.pdf_program_check_box.checkState()
enable_pdf_program = self.pdf_program_check_box.checkState()
# If the given program is blank disable using the program
if pdf_program == '':
enable_given_pdf_program = 0
if pdf_program != Settings().value(self.settings_section + '/given_pdf_program'):
Settings().setValue(self.settings_section + '/given_pdf_program', pdf_program)
enable_pdf_program = 0
if pdf_program != Settings().value(self.settings_section + '/pdf_program'):
Settings().setValue(self.settings_section + '/pdf_program', pdf_program)
changed = True
if enable_given_pdf_program != Settings().value(self.settings_section + '/enable_given_pdf_program'):
Settings().setValue(self.settings_section + '/enable_given_pdf_program', enable_given_pdf_program)
if enable_pdf_program != Settings().value(self.settings_section + '/enable_pdf_program'):
Settings().setValue(self.settings_section + '/enable_pdf_program', enable_pdf_program)
changed = True
if changed:

View File

@ -45,8 +45,8 @@ log = logging.getLogger(__name__)
__default_settings__ = {
'presentations/override app': QtCore.Qt.Unchecked,
'presentations/enable_given_pdf_program': QtCore.Qt.Unchecked,
'presentations/given_pdf_program': '',
'presentations/enable_pdf_program': QtCore.Qt.Unchecked,
'presentations/pdf_program': '',
'presentations/Impress': QtCore.Qt.Checked,
'presentations/Powerpoint': QtCore.Qt.Checked,
'presentations/Powerpoint Viewer': QtCore.Qt.Checked,