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() items = self.list_view.selectedItems()
if len(items) > 1: if len(items) > 1:
return False return False
filename = items[0].data(QtCore.Qt.UserRole) filename = items[0].data(QtCore.Qt.UserRole)
file_type = os.path.splitext(filename)[1][1:] file_type = os.path.splitext(filename)[1][1:]
if not self.display_type_combo_box.currentText(): if not self.display_type_combo_box.currentText():
return False return False
if (file_type == 'pdf' or file_type == 'xps') and context != ServiceItemContext.Service:
if context == ServiceItemContext.Live and (file_type == 'pdf' or file_type == 'xps'):
service_item.add_capability(ItemCapabilities.CanMaintain) service_item.add_capability(ItemCapabilities.CanMaintain)
service_item.add_capability(ItemCapabilities.CanPreview) service_item.add_capability(ItemCapabilities.CanPreview)
service_item.add_capability(ItemCapabilities.CanLoop) service_item.add_capability(ItemCapabilities.CanLoop)
service_item.add_capability(ItemCapabilities.CanAppend) service_item.add_capability(ItemCapabilities.CanAppend)
# force a nonexistent theme # force a nonexistent theme
service_item.theme = -1 service_item.theme = -1
# Why the loop when we above return False if len(items) is > 1?
for bitem in items: for bitem in items:
filename = bitem.data(QtCore.Qt.UserRole) filename = bitem.data(QtCore.Qt.UserRole)
(path, name) = os.path.split(filename) (path, name) = os.path.split(filename)
@ -270,16 +266,17 @@ class PresentationMediaItem(MediaManagerItem):
controller = self.controllers[processor] controller = self.controllers[processor]
service_item.processor = None service_item.processor = None
doc = controller.add_document(filename) 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() doc.load_presentation()
i = 1 i = 1
imagefile = 'mainslide%03d.png' % i imagefile = 'mainslide%03d.png' % i
img = os.path.join(doc.get_temp_folder(), imagefile) image = os.path.join(doc.get_temp_folder(), imagefile)
while os.path.isfile(img): while os.path.isfile(image):
service_item.add_from_image(img, name) service_item.add_from_image(image, name)
i += 1 i += 1
imagefile = 'mainslide%03d.png' % i 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() doc.close_presentation()
return True return True
else: else:
@ -291,8 +288,6 @@ class PresentationMediaItem(MediaManagerItem):
else: else:
service_item.processor = self.display_type_combo_box.currentText() service_item.processor = self.display_type_combo_box.currentText()
service_item.add_capability(ItemCapabilities.ProvidesOwnDisplay) service_item.add_capability(ItemCapabilities.ProvidesOwnDisplay)
# Why the loop when we above return False if len(items) is > 1?
for bitem in items: for bitem in items:
filename = bitem.data(QtCore.Qt.UserRole) filename = bitem.data(QtCore.Qt.UserRole)
(path, name) = os.path.split(filename) (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.lib import Registry
from openlp.core.ui import HideMode from openlp.core.ui import HideMode
from openlp.core.lib import ServiceItemContext
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -69,6 +70,7 @@ class Controller(object):
return return
self.doc.slidenumber = slide_no self.doc.slidenumber = slide_no
self.hide_mode = hide_mode self.hide_mode = hide_mode
log.debug('add_handler, slidenumber: %d' % slide_no)
if self.is_live: if self.is_live:
if hide_mode == HideMode.Screen: if hide_mode == HideMode.Screen:
Registry().execute('live_display_hide', HideMode.Screen) Registry().execute('live_display_hide', HideMode.Screen)
@ -316,6 +318,14 @@ class MessageListener(object):
hide_mode = message[2] hide_mode = message[2]
file = item.get_frame_path() file = item.get_frame_path()
self.handler = item.processor 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: if self.handler == self.media_item.Automatic:
self.handler = self.media_item.findControllerByType(file) self.handler = self.media_item.findControllerByType(file)
if not self.handler: if not self.handler:
@ -326,9 +336,10 @@ class MessageListener(object):
controller = self.preview_handler controller = self.preview_handler
# when presenting PDF, we're using the image presentation code, # when presenting PDF, we're using the image presentation code,
# so handler & processor is set to None, and we skip adding the handler. # so handler & processor is set to None, and we skip adding the handler.
log.debug('file: %s' % file)
if self.handler == None: if self.handler == None:
self.controller = controller self.controller = controller
else: else:
controller.add_handler(self.controllers[self.handler], file, hide_mode, message[3]) controller.add_handler(self.controllers[self.handler], file, hide_mode, message[3])
def slide(self, message): def slide(self, message):

View File

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

View File

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

View File

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