Merge lp:~tomasgroth/openlp/mupdf into lp:openlp

Proposed by Tomas Groth
Status: Superseded
Proposed branch: lp:~tomasgroth/openlp/mupdf
Merge into: lp:openlp
Diff against target: 926 lines (+661/-41)
10 files modified
openlp/core/ui/slidecontroller.py (+2/-2)
openlp/plugins/presentations/lib/ghostscript_get_resolution.ps (+10/-0)
openlp/plugins/presentations/lib/mediaitem.py (+86/-35)
openlp/plugins/presentations/lib/messagelistener.py (+31/-1)
openlp/plugins/presentations/lib/pdfcontroller.py (+315/-0)
openlp/plugins/presentations/lib/presentationtab.py (+93/-1)
openlp/plugins/presentations/presentationplugin.py (+3/-0)
resources/pyinstaller/hook-openlp.plugins.presentations.presentationplugin.py (+2/-1)
tests/functional/openlp_plugins/presentations/test_mediaitem.py (+10/-1)
tests/functional/openlp_plugins/presentations/test_pdfcontroller.py (+109/-0)
To merge this branch: bzr merge lp:~tomasgroth/openlp/mupdf
Reviewer Review Type Date Requested Status
Raoul Snyman Needs Fixing
Tim Bentley Approve
Review via email: mp+201684@code.launchpad.net

This proposal supersedes a proposal from 2013-12-31.

This proposal has been superseded by a proposal from 2014-02-21.

Description of the change

Support for presenting PDF using mupdf or ghostscript.

To post a comment you must log in.
Revision history for this message
Dmitriy Marmyshev (marmyshev) wrote : Posted in a previous version of this proposal

Looks good!
Really expecting function for us! Keep develop it!

1Q: Does it works on OS X?
2Q: I didnt get the point with PdfViewer class. Dont you use slide's system in OpenLP? Do I correctly understand that you just convert PDF to images and then show them like images? May be it will be easier to use image plugin for showing images after conversion.

And 1 more suggestion: may be it is better to use this:

os.path.isfile(os.path.join(self.get_temp_folder(), u'mainslide001.png'))

instead of this:

os.path.isfile(self.get_temp_folder() + u'/mainslide001.png')

Revision history for this message
Raoul Snyman (raoul-snyman) wrote : Posted in a previous version of this proposal

>And 1 more suggestion: may be it is better to use this:
>
>os.path.isfile(os.path.join(self.get_temp_folder(),
>u'mainslide001.png'))
>
>instead of this:
>
>os.path.isfile(self.get_temp_folder() + u'/mainslide001.png')

Good catch Dmitriy!

--
Sent from my Android phone with K-9 Mail. Please excuse my brevity.

Revision history for this message
Tomas Groth (tomasgroth) wrote : Posted in a previous version of this proposal

> 1Q: Does it works on OS X?
Yea, provided that either ghostscript or mupdf is available.

> 2Q: I didnt get the point with PdfViewer class. Dont you use slide's system in
> OpenLP? Do I correctly understand that you just convert PDF to images and then
> show them like images? May be it will be easier to use image plugin for
> showing images after conversion.
I've thought of the same thing, but I have to admit that I'm yet to find a way to bend the system to my need. I'd like the service-item to be a pdf-presentation, but presenting that using the same aproach as the image plugin isn't easy. But maybe I just don't understand the structure of OpenLP yet.

> And 1 more suggestion: may be it is better to use this:
> os.path.isfile(os.path.join(self.get_temp_folder(), u'mainslide001.png'))
> instead of this:
> os.path.isfile(self.get_temp_folder() + u'/mainslide001.png')
I'll change this in the next push.

Revision history for this message
Tim Bentley (trb143) wrote : Posted in a previous version of this proposal

Hum
The conversion to images is done on importing the PDF so all the images are
in the file system.
You could then add the images as image items to the service instead of
presentation file.

That would be a clean cross over Services would work as images but added as
a PDF.

On 21 July 2013 15:16, Tomas Groth <email address hidden> wrote:

> > 1Q: Does it works on OS X?
> Yea, provided that either ghostscript or mupdf is available.
>
> > 2Q: I didnt get the point with PdfViewer class. Dont you use slide's
> system in
> > OpenLP? Do I correctly understand that you just convert PDF to images
> and then
> > show them like images? May be it will be easier to use image plugin for
> > showing images after conversion.
> I've thought of the same thing, but I have to admit that I'm yet to find a
> way to bend the system to my need. I'd like the service-item to be a
> pdf-presentation, but presenting that using the same aproach as the image
> plugin isn't easy. But maybe I just don't understand the structure of
> OpenLP yet.
>
> > And 1 more suggestion: may be it is better to use this:
> > os.path.isfile(os.path.join(self.get_temp_folder(), u'mainslide001.png'))
> > instead of this:
> > os.path.isfile(self.get_temp_folder() + u'/mainslide001.png')
> I'll change this in the next push.
> --
> https://code.launchpad.net/~tomasgroth/openlp/mupdf/+merge/174849
> Your team OpenLP Core is requested to review the proposed merge of
> lp:~tomasgroth/openlp/mupdf into lp:openlp.
>
> _______________________________________________
> Mailing list: https://launchpad.net/~openlp-core
> Post to : <email address hidden>
> Unsubscribe : https://launchpad.net/~openlp-core
> More help : https://help.launchpad.net/ListHelp
>

--
Tim and Alison Bentley
<email address hidden>

Revision history for this message
Andreas Preikschat (googol-deactivatedaccount) wrote : Posted in a previous version of this proposal

And please add docstrings to *all* methods/functions

Revision history for this message
Dmitriy Marmyshev (marmyshev) wrote : Posted in a previous version of this proposal

> Hum
> The conversion to images is done on importing the PDF so all the images are
> in the file system.
> You could then add the images as image items to the service instead of
> presentation file.
>
> That would be a clean cross over Services would work as images but added as
> a PDF.
>

Let me not to agree with this. We should not to make life of OpenLP operator (user) harder by changing visually a "PDF file" to a "group of imageses". If I (as user) add PDF presentation to OpenLP - i'd like to see PDF in the list.
Upper, I mean that create new class (PdfViewer) just to show images may be is not the easiest way, may be it is better simply to use classes from ImagePlugin to show images from PDF controller.

Revision history for this message
Jonathan Corwin (j-corwin) wrote : Posted in a previous version of this proposal

(Note comment only, I've not looked at the code)

I too think it is nice to keep it in the Presentation plugin. The user is dealing with a PDF file as far as they are concerned and transporting the PDF in the service file rather than lots of images is in my view the correct way of doing this. Importing a PDF in Presentations and having to look for it in the image plugin would confuse many. Also by moving the PDF around it protects us from adding it on one computer with a 640x480 resolution moving to a 1900x1080 system and ending up having to deal with images in an resolution that don't scale nicely.

In the future some other app (e.g. Impress) might support the opening of PDF files and in this case the user would then be able to choose between mupdf or something else. If we're only storing the images then that wouldn't be so easy.

Yes it would be nice if we could just hook into the already existing image handling functionality of OpenLP for the display, but I wouldn't want us to tear the code base to pieces to get this to work. (I don't know the difficulties of this). I don't see any harm in making it a two phase task anyway and to do this later if we find a nice way to do it.

Finally an idea has just come to mind that in the future we could also support an "Export to Images" function on the presentation whereby we could copy the thumbnail images (created at output resolution) to the an Image Plugin group, to at least cater for those situations where the user knows the presentation application isn't installed at the destination system. However this would be outside the scope of this particular branch and would be a whole new feature.

Revision history for this message
Dave Warnock (dave-warnock) wrote : Posted in a previous version of this proposal

Just wanted to add my support to what Jonathon suggests.

On 22 July 2013 10:18, Jonathan Corwin <email address hidden> wrote:

> (Note comment only, I've not looked at the code)
>
> I too think it is nice to keep it in the Presentation plugin. The user is
> dealing with a PDF file as far as they are concerned and transporting the
> PDF in the service file rather than lots of images is in my view the
> correct way of doing this. Importing a PDF in Presentations and having to
> look for it in the image plugin would confuse many. Also by moving the PDF
> around it protects us from adding it on one computer with a 640x480
> resolution moving to a 1900x1080 system and ending up having to deal with
> images in an resolution that don't scale nicely.
>
> In the future some other app (e.g. Impress) might support the opening of
> PDF files and in this case the user would then be able to choose between
> mupdf or something else. If we're only storing the images then that
> wouldn't be so easy.
>
> Yes it would be nice if we could just hook into the already existing image
> handling functionality of OpenLP for the display, but I wouldn't want us to
> tear the code base to pieces to get this to work. (I don't know the
> difficulties of this). I don't see any harm in making it a two phase task
> anyway and to do this later if we find a nice way to do it.
>
> Finally an idea has just come to mind that in the future we could also
> support an "Export to Images" function on the presentation whereby we could
> copy the thumbnail images (created at output resolution) to the an Image
> Plugin group, to at least cater for those situations where the user knows
> the presentation application isn't installed at the destination system.
> However this would be outside the scope of this particular branch and would
> be a whole new feature.
> --
> https://code.launchpad.net/~tomasgroth/openlp/mupdf/+merge/174849
> You are subscribed to branch lp:openlp.
>

--
Dave Warnock: http://42.blogs.warnock.me.uk
Cycling Blog: http://42bikes.warnock.me.uk

Revision history for this message
Tim Bentley (trb143) wrote : Posted in a previous version of this proposal
Download full text (3.5 KiB)

Ok so I worded it in a clumsy manner.

PDF gets added to the presentation plugin no problems. It generates images
of the pages like the presentation plugins do.

The difference suggested and echoed by Jonathan is we use the image
processing part of the serviceitem to do the displays instead of writing
and managing an 8th player within the architecture.

It will look like a PDF, quack like a PDF display like a set of images.

The changes suggested will be constrained to the Presentations plugin so
easier to implement and test with less disruption.

Adding a new player is not a small job and with the issues we have had in
the past (4 months to sort out media after 5 months getting it in) and the
migrations going on it will be a challenge.

BTW are the PDF libraries fully python3 compliant and have versions
available for all the distros we support. That would also be a merge
requirement.

Tim

On 22 July 2013 11:35, Dave Warnock <email address hidden> wrote:

> Just wanted to add my support to what Jonathon suggests.
>
> On 22 July 2013 10:18, Jonathan Corwin <email address hidden> wrote:
>
> > (Note comment only, I've not looked at the code)
> >
> > I too think it is nice to keep it in the Presentation plugin. The user is
> > dealing with a PDF file as far as they are concerned and transporting the
> > PDF in the service file rather than lots of images is in my view the
> > correct way of doing this. Importing a PDF in Presentations and having to
> > look for it in the image plugin would confuse many. Also by moving the
> PDF
> > around it protects us from adding it on one computer with a 640x480
> > resolution moving to a 1900x1080 system and ending up having to deal with
> > images in an resolution that don't scale nicely.
> >
> > In the future some other app (e.g. Impress) might support the opening of
> > PDF files and in this case the user would then be able to choose between
> > mupdf or something else. If we're only storing the images then that
> > wouldn't be so easy.
> >
> > Yes it would be nice if we could just hook into the already existing
> image
> > handling functionality of OpenLP for the display, but I wouldn't want us
> to
> > tear the code base to pieces to get this to work. (I don't know the
> > difficulties of this). I don't see any harm in making it a two phase task
> > anyway and to do this later if we find a nice way to do it.
> >
> > Finally an idea has just come to mind that in the future we could also
> > support an "Export to Images" function on the presentation whereby we
> could
> > copy the thumbnail images (created at output resolution) to the an Image
> > Plugin group, to at least cater for those situations where the user knows
> > the presentation application isn't installed at the destination system.
> > However this would be outside the scope of this particular branch and
> would
> > be a whole new feature.
> > --
> > https://code.launchpad.net/~tomasgroth/openlp/mupdf/+merge/174849
> > You are subscribed to branch lp:openlp.
> >
>
>
>
> --
> Dave Warnock: http://42.blogs.warnock.me.uk
> Cycling Blog: http://42bikes.warnock.me.uk
>
> https://code.launchpad.net/~tomasgroth/openlp/mupdf/+merge/174849
> Your team OpenL...

Read more...

Revision history for this message
Tomas Groth (tomasgroth) wrote : Posted in a previous version of this proposal

Ok, here is some more thoughts...
The challenge as I see it is that the presentation plugin has been build around the fact the PowerPoint, PowerPoint Viewer and Impress all have their own "players", which means that since this pdf-presentation extensions is inside the presentation plugin, it is expected to provide a player, which is what I implemented in this first revision by adding the simple PdfViewer class. As some of you noted it might not be a great idea to add another "player", but the problem then is how to bend OpenLP into presenting images, even though it is a presentation...
I've looked around a bit and for now my best idea is to remove my PdfViewer class, and instead use my own instance of the MainDisplay class, which can present images. This way I reuse a "player", and avoid having to hack various parts too much. I haven't tried it yet, but I think it could work.
About python3, that shouldn't be an issue since I call the ghostscript or mupdf programs directly, not via python libs.

Revision history for this message
Jonathan Corwin (j-corwin) wrote : Posted in a previous version of this proposal

Tim, I don't understand why adding a new player /here/ will be a big problem. Yes it was a problem for media because that was all integrated with songs, the toolbar, etc and there was a lot of overlap across plugins.

However the Presentations plugin is completely designed to deal with third party apps. All they need to be able to do is blank, and the plugin will deal with the rest. Having a simple Window that can go full screen is not going to have the problems that we had with media. In fact I personally think trying to tie this in to use the existing display would make the code more complicated and error prone that keeping it standalone.

Revision history for this message
Tomas Groth (tomasgroth) wrote : Posted in a previous version of this proposal

Hi guys,
I've now also made a version which uses the approach Tim mentioned. It works quite well, but I haven't pushed it yet.
So how do we figure out which version should be used?

Revision history for this message
Jonathan Corwin (j-corwin) wrote : Posted in a previous version of this proposal

Push it and get it reviewed :)

Revision history for this message
Tomas Groth (tomasgroth) wrote : Posted in a previous version of this proposal

Ok, so I've just pushed the player-less version, where the image-presentation functionality is used instead. There is still a few issues. For example it tries to load the first image added to the serviceitem as a pdf-presentation when going live/preview. Haven't figured out why.

Revision history for this message
Tim Bentley (trb143) wrote : Posted in a previous version of this proposal

That is because you have set the ServiceItem.processor.
You have code in the pdf route which is not needed.

On 27 July 2013 10:52, Tomas Groth <email address hidden> wrote:

> Ok, so I've just pushed the player-less version, where the
> image-presentation functionality is used instead. There is still a few
> issues. For example it tries to load the first image added to the
> serviceitem as a pdf-presentation when going live/preview. Haven't figured
> out why.
> --
> https://code.launchpad.net/~tomasgroth/openlp/mupdf/+merge/174849
> Your team OpenLP Core is requested to review the proposed merge of
> lp:~tomasgroth/openlp/mupdf into lp:openlp.
>
> _______________________________________________
> Mailing list: https://launchpad.net/~openlp-core
> Post to : <email address hidden>
> Unsubscribe : https://launchpad.net/~openlp-core
> More help : https://help.launchpad.net/ListHelp
>

--
Tim and Alison Bentley
<email address hidden>

Revision history for this message
Tomas Groth (tomasgroth) wrote : Posted in a previous version of this proposal

I've now added the possibility for pointing to ghostscript or mudraw if autodetection isn't working. Also minor fixes for the pdf-presentation code.

Revision history for this message
Tomas Groth (tomasgroth) wrote : Posted in a previous version of this proposal

Hi guys, I was wondering if you think something more should be added before this is ready to be merged into trunk? Does it make sense to make tests for presentation plugins?

Revision history for this message
Tim Bentley (trb143) wrote : Posted in a previous version of this proposal

Looks good but these need to be fixed.

* settings screen the grouping has moved from the left side to the middle.
* settings screen "binary" has the "y" half chopped off.
* showing an image live / preview does not work when loaded from the service manager. Fine from the media manager. Have not tried to save / reload but guess that is broken.
* blank lines in functions please remove (general)
* questions in comments please removed.
* check_binary why is this outside the class as a standalone function?
* if os.name != u'nt': swap logic round so is positive and less chance of a miss read.
* 320 would this be better to have in the code a file instead of writing to a file each run?
* if self.pdf_program_path.text() != u'': should be if not self.pdf_program_path.text(): - General point.
* setting do not need "given" in the string.
* img should be image (old bad code copied!
* no tests.
* line 53 far too long.
* lines 52-64 do we need all this. if the images are generated then it would be a case of just loading them not processing them again?

review: Needs Fixing
Revision history for this message
Tim Bentley (trb143) wrote : Posted in a previous version of this proposal

Please resubmit due to the age of this request and additionally it will need converting to Python 3 as on 1/9/2013 truck will be converted.

review: Needs Resubmitting
Revision history for this message
Tomas Groth (tomasgroth) wrote : Posted in a previous version of this proposal

I need some feedback/guidance/help to finish this implementation...
The basic idea is to use mupdf or ghostscript to create a picture for each page in the PDF, and when going to live/preview mode, then replace the service_item with an image-based service_item. I've made it work when going to live/preview from the mediamanager, but I can't figure out how/where to do it from the servicemanager - any hints would be appreciated! As an alternative it can be implemented as the other presentation-backends, with a "player".

I'd also like some directions as to what tests to include? I couldn't find any tests for the other presentation backends...

And finally, I've added some extra fields to the presentation-settings-tab, and for some reason now all fields has moved a bit to the right instead for being to the far left - any hints as to why?

Revision history for this message
Raoul Snyman (raoul-snyman) wrote : Posted in a previous version of this proposal

Hi Tomas, in it's current state your merge proposal has some conflicts. Can you merge from trunk and fix those please?

review: Needs Fixing
Revision history for this message
Tomas Groth (tomasgroth) wrote : Posted in a previous version of this proposal

Merged with trunk to resolve conflicts. Last set of questions still applies.

Revision history for this message
Tomas Groth (tomasgroth) wrote : Posted in a previous version of this proposal

I think I've resolved most problems now and even added some simple tests.
The basic idea is to (still) use mupdf or ghostscript to create a picture for each page in the PDF, and when going to live/preview mode the service_item is replaced with an image-based service_item on the fly.

Revision history for this message
Tim Bentley (trb143) wrote : Posted in a previous version of this proposal

Conflicts with head.

lines 8-13 why. This needs a good explanation as it looks like a botch.
lines 52-53 - fix for PEP8 - have a look at other places as well.
line 77 - why not service?

Linn 200+ Confused. If generated from plugin we have a image service item. Good. If started from Service Manager we need to convert. Why? How did it get to the service manager cos the plugin would have created an image service item not a presentation one. Also not sure about exposing the innards of the serviceitem in this could. could it be a new method on the service item?

tmpFile = tmp_file

484 - 498 Line lengths.
611, 668, 675 etc tabbing
650 space

review: Needs Fixing
Revision history for this message
Tomas Groth (tomasgroth) wrote : Posted in a previous version of this proposal

Fixed for PEP8 compliance and trunk-conflicts.
Changed the way the serviceitem was copied/converted in messengerlistener.startup() to make it simpler and removed changes from service_item.
The serviceitem of PDF is a presentation-serviceitem containing a PDF file (in the same way a presentation-serviceitem contains ppt-file), and it remains like this when in the mediamanager or the servicemanager. When going to preview/live-mode the serviceitem is converted to a image-serviceitem and displayed as such. Where in the code the serviceitem-conversion should be done is open for debate. Since it (at the moment) is tied to the Pdf-presentation, maybe it should be a method in the PdfDocument class

Revision history for this message
Tim Bentley (trb143) wrote : Posted in a previous version of this proposal

Looks good but not sure about the postscript.
We hard code it (looks complex and messey) and then write it to a temp file.
Could we not have it as a file and just load it?

Revision history for this message
Tomas Groth (tomasgroth) wrote : Posted in a previous version of this proposal

> Looks good but not sure about the postscript.
> We hard code it (looks complex and messey) and then write it to a temp file.
> Could we not have it as a file and just load it?
I see your point about the postscript. The reason I kept it 'hardcoded' was that I couldn't (and still can't) figure out how to reliable get the path to the file if I placed it in resources/misc/ghostscript_get_resolution.ps.

Revision history for this message
Tim Bentley (trb143) wrote : Posted in a previous version of this proposal

It needs to be in the same directory as the python code or a resources dir under the plugin.

The main resources directories are not in the builds

Revision history for this message
Tomas Groth (tomasgroth) wrote : Posted in a previous version of this proposal

Ok, moved the postscript into a separate file.

Revision history for this message
Tim Bentley (trb143) wrote : Posted in a previous version of this proposal

Looks great but in final testing came up with a problem

Settings dialog - the tick box seems to use all three states.

Tick box and type rubbish in to the file box.
Press cancel and you get an error message - Not Correct.
When the dialog reappears the light grey tick is present - Not correct.

review: Needs Fixing
Revision history for this message
Tomas Groth (tomasgroth) wrote : Posted in a previous version of this proposal

> Looks great but in final testing came up with a problem
>
> Settings dialog - the tick box seems to use all three states.
>
> Tick box and type rubbish in to the file box.
> Press cancel and you get an error message - Not Correct.
> When the dialog reappears the light grey tick is present - Not correct.

I can't see any easy way around this if I want to validate input in the settingstab, and display an error without saving.
As I see it we need to add a "validate" method to the SettingsTab class, which would then be called before "save" is called. That way my onchange-validation isn't needed.

Revision history for this message
Tim Bentley (trb143) wrote : Posted in a previous version of this proposal

Have a look at the Advanced Tab how it handles the data directory. This is read only and can only be accessed from the button.

Revision history for this message
Tomas Groth (tomasgroth) wrote :

Changed to only allow pdf-program selection using filedialog as suggested.

Revision history for this message
Tim Bentley (trb143) wrote :

Looks good to go.

review: Approve
Revision history for this message
Raoul Snyman (raoul-snyman) wrote :

Traceback (most recent call last):
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/core/common/registry.py", line 164, in execute
    result = function(*args, **kwargs)
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/core/common/openlpmixin.py", line 66, in wrapped
    raise e
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/core/common/openlpmixin.py", line 62, in wrapped
    return func(*args, **kwargs)
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/core/lib/pluginmanager.py", line 61, in bootstrap_initialise
    self.find_plugins()
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/core/common/openlpmixin.py", line 66, in wrapped
    raise e
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/core/common/openlpmixin.py", line 62, in wrapped
    return func(*args, **kwargs)
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/core/lib/pluginmanager.py", line 121, in find_plugins
    if plugin.check_pre_conditions():
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/plugins/presentations/presentationplugin.py", line 141, in check_pre_conditions
    controller = controller_class(self)
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/plugins/presentations/lib/pdfcontroller.py", line 62, in __init__
    self.check_installed()
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/plugins/presentations/lib/pdfcontroller.py", line 140, in check_installed
    self.gsbin = check_output(['which', 'gs']).rstrip('\n')
TypeError: Type str doesn't support the buffer API

review: Needs Fixing
Revision history for this message
Raoul Snyman (raoul-snyman) wrote :

Also, if I start up without a configuration, I get the following exception (which I don't get in trunk):

Traceback (most recent call last):
  File "openlp.py", line 45, in <module>
    main()
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/core/__init__.py", line 329, in main
    sys.exit(application.run(qt_args))
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/core/__init__.py", line 150, in run
    self.main_window.first_time()
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/core/ui/mainwindow.py", line 636, in first_time
    plugin.first_time()
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/plugins/songs/songsplugin.py", line 264, in first_time
    self.on_tools_reindex_item_triggered()
  File "/home/raoul/Projects/OpenLP/mupdf/openlp/plugins/songs/songsplugin.py", line 180, in on_tools_reindex_item_triggered
    self.media_item.on_search_text_button_clicked()
AttributeError: 'NoneType' object has no attribute 'on_search_text_button_clicked'

review: Needs Fixing
lp:~tomasgroth/openlp/mupdf updated
2297. By Tomas Groth

merged with trunk

2298. By Tomas Groth

fixed an exception

2299. By Tomas Groth

merged with head

Unmerged revisions

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'openlp/core/ui/slidecontroller.py'
2--- openlp/core/ui/slidecontroller.py 2014-01-04 11:50:27 +0000
3+++ openlp/core/ui/slidecontroller.py 2014-02-21 21:48:55 +0000
4@@ -444,7 +444,7 @@
5 # "V1" was the slide we wanted to go.
6 self.preview_widget.change_slide(self.slide_list[self.current_shortcut])
7 self.slide_selected()
8- # Reset the shortcut.
9+ # Reset the shortcut.
10 self.current_shortcut = ''
11
12 def set_live_hot_keys(self, parent=None):
13@@ -763,7 +763,7 @@
14 if old_item and self.is_live and old_item.is_capable(ItemCapabilities.ProvidesOwnDisplay):
15 self._reset_blank()
16 Registry().execute(
17- '%s_start' % service_item.name.lower(), [service_item, self.is_live, self.hide_mode(), slide_no])
18+ '%s_start' % service_item.name.lower(), [self.service_item, self.is_live, self.hide_mode(), slide_no])
19 self.slide_list = {}
20 if self.is_live:
21 self.song_menu.menu().clear()
22
23=== added file 'openlp/plugins/presentations/lib/ghostscript_get_resolution.ps'
24--- openlp/plugins/presentations/lib/ghostscript_get_resolution.ps 1970-01-01 00:00:00 +0000
25+++ openlp/plugins/presentations/lib/ghostscript_get_resolution.ps 2014-02-21 21:48:55 +0000
26@@ -0,0 +1,10 @@
27+%!PS
28+() =
29+File dup (r) file runpdfbegin
30+1 pdfgetpage dup
31+/MediaBox pget {
32+aload pop exch 4 1 roll exch sub 3 1 roll sub
33+( Size: x: ) print =print (, y: ) print =print (\n) print
34+} if
35+flush
36+quit
37
38=== modified file 'openlp/plugins/presentations/lib/mediaitem.py'
39--- openlp/plugins/presentations/lib/mediaitem.py 2013-12-28 21:33:38 +0000
40+++ openlp/plugins/presentations/lib/mediaitem.py 2014-02-21 21:48:55 +0000
41@@ -116,7 +116,7 @@
42 self.display_type_label = QtGui.QLabel(self.presentation_widget)
43 self.display_type_label.setObjectName('display_type_label')
44 self.display_type_combo_box = create_horizontal_adjusting_combo_box(self.presentation_widget,
45- 'display_type_combo_box')
46+ 'display_type_combo_box')
47 self.display_type_label.setBuddy(self.display_type_combo_box)
48 self.display_layout.addRow(self.display_type_label, self.display_type_combo_box)
49 # Add the Presentation widget to the page layout.
50@@ -138,6 +138,9 @@
51 """
52 self.display_type_combo_box.clear()
53 for item in self.controllers:
54+ # For PDF reload backend, since it can have changed
55+ if self.controllers[item].name == 'Pdf':
56+ self.controllers[item].check_available()
57 # load the drop down selection
58 if self.controllers[item].enabled():
59 self.display_type_combo_box.addItem(item)
60@@ -177,9 +180,8 @@
61 if titles.count(filename) > 0:
62 if not initial_load:
63 critical_error_message_box(translate('PresentationPlugin.MediaItem', 'File Exists'),
64- translate('PresentationPlugin.MediaItem',
65- 'A presentation with that filename already exists.')
66- )
67+ translate('PresentationPlugin.MediaItem',
68+ 'A presentation with that filename already exists.'))
69 continue
70 controller_name = self.findControllerByType(filename)
71 if controller_name:
72@@ -203,7 +205,8 @@
73 icon = build_icon(':/general/general_delete.png')
74 else:
75 critical_error_message_box(UiStrings().UnsupportedFile,
76- translate('PresentationPlugin.MediaItem', 'This type of presentation is not supported.'))
77+ translate('PresentationPlugin.MediaItem',
78+ 'This type of presentation is not supported.'))
79 continue
80 item_name = QtGui.QListWidgetItem(filename)
81 item_name.setData(QtCore.Qt.UserRole, file)
82@@ -238,7 +241,7 @@
83 Settings().setValue(self.settings_section + '/presentations files', self.get_file_list())
84
85 def generate_slide_data(self, service_item, item=None, xml_version=False,
86- remote=False, context=ServiceItemContext.Service):
87+ remote=False, context=ServiceItemContext.Service, presentation_file=None):
88 """
89 Load the relevant information for displaying the presentation in the slidecontroller. In the case of
90 powerpoints, an image for each slide.
91@@ -249,45 +252,93 @@
92 items = self.list_view.selectedItems()
93 if len(items) > 1:
94 return False
95- service_item.processor = self.display_type_combo_box.currentText()
96- service_item.add_capability(ItemCapabilities.ProvidesOwnDisplay)
97+ filename = presentation_file
98+ if filename is None:
99+ filename = items[0].data(QtCore.Qt.UserRole)
100+ file_type = os.path.splitext(filename)[1][1:]
101 if not self.display_type_combo_box.currentText():
102 return False
103- for bitem in items:
104- filename = bitem.data(QtCore.Qt.UserRole)
105- (path, name) = os.path.split(filename)
106- service_item.title = name
107- if os.path.exists(filename):
108- if service_item.processor == self.automatic:
109- service_item.processor = self.findControllerByType(filename)
110- if not service_item.processor:
111+ if (file_type == 'pdf' or file_type == 'xps') and context != ServiceItemContext.Service:
112+ service_item.add_capability(ItemCapabilities.CanMaintain)
113+ service_item.add_capability(ItemCapabilities.CanPreview)
114+ service_item.add_capability(ItemCapabilities.CanLoop)
115+ service_item.add_capability(ItemCapabilities.CanAppend)
116+ # force a nonexistent theme
117+ service_item.theme = -1
118+ for bitem in items:
119+ filename = presentation_file
120+ if filename is None:
121+ filename = bitem.data(QtCore.Qt.UserRole)
122+ (path, name) = os.path.split(filename)
123+ service_item.title = name
124+ if os.path.exists(filename):
125+ processor = self.findControllerByType(filename)
126+ if not processor:
127 return False
128- controller = self.controllers[service_item.processor]
129- doc = controller.add_document(filename)
130- if doc.get_thumbnail_path(1, True) is None:
131- doc.load_presentation()
132- i = 1
133- img = doc.get_thumbnail_path(i, True)
134- if img:
135- while img:
136- service_item.add_from_command(path, name, img)
137+ controller = self.controllers[processor]
138+ service_item.processor = None
139+ doc = controller.add_document(filename)
140+ if doc.get_thumbnail_path(1, True) is None or not os.path.isfile(
141+ os.path.join(doc.get_temp_folder(), 'mainslide001.png')):
142+ doc.load_presentation()
143+ i = 1
144+ imagefile = 'mainslide%03d.png' % i
145+ image = os.path.join(doc.get_temp_folder(), imagefile)
146+ while os.path.isfile(image):
147+ service_item.add_from_image(image, name)
148 i += 1
149- img = doc.get_thumbnail_path(i, True)
150+ imagefile = 'mainslide%03d.png' % i
151+ image = os.path.join(doc.get_temp_folder(), imagefile)
152 doc.close_presentation()
153 return True
154 else:
155 # File is no longer present
156 if not remote:
157 critical_error_message_box(translate('PresentationPlugin.MediaItem', 'Missing Presentation'),
158- translate('PresentationPlugin.MediaItem',
159- 'The presentation %s is incomplete, please reload.') % filename)
160- return False
161- else:
162- # File is no longer present
163- if not remote:
164- critical_error_message_box(translate('PresentationPlugin.MediaItem', 'Missing Presentation'),
165- translate('PresentationPlugin.MediaItem', 'The presentation %s no longer exists.') % filename)
166- return False
167+ translate('PresentationPlugin.MediaItem',
168+ 'The presentation %s no longer exists.') % filename)
169+ return False
170+ else:
171+ service_item.processor = self.display_type_combo_box.currentText()
172+ service_item.add_capability(ItemCapabilities.ProvidesOwnDisplay)
173+ for bitem in items:
174+ filename = bitem.data(QtCore.Qt.UserRole)
175+ (path, name) = os.path.split(filename)
176+ service_item.title = name
177+ if os.path.exists(filename):
178+ if service_item.processor == self.automatic:
179+ service_item.processor = self.findControllerByType(filename)
180+ if not service_item.processor:
181+ return False
182+ controller = self.controllers[service_item.processor]
183+ doc = controller.add_document(filename)
184+ if doc.get_thumbnail_path(1, True) is None:
185+ doc.load_presentation()
186+ i = 1
187+ img = doc.get_thumbnail_path(i, True)
188+ if img:
189+ while img:
190+ service_item.add_from_command(path, name, img)
191+ i += 1
192+ img = doc.get_thumbnail_path(i, True)
193+ doc.close_presentation()
194+ return True
195+ else:
196+ # File is no longer present
197+ if not remote:
198+ critical_error_message_box(translate('PresentationPlugin.MediaItem',
199+ 'Missing Presentation'),
200+ translate('PresentationPlugin.MediaItem',
201+ 'The presentation %s is incomplete, please reload.')
202+ % filename)
203+ return False
204+ else:
205+ # File is no longer present
206+ if not remote:
207+ critical_error_message_box(translate('PresentationPlugin.MediaItem', 'Missing Presentation'),
208+ translate('PresentationPlugin.MediaItem',
209+ 'The presentation %s no longer exists.') % filename)
210+ return False
211
212 def findControllerByType(self, filename):
213 """
214
215=== modified file 'openlp/plugins/presentations/lib/messagelistener.py'
216--- openlp/plugins/presentations/lib/messagelistener.py 2013-12-28 21:33:38 +0000
217+++ openlp/plugins/presentations/lib/messagelistener.py 2014-02-21 21:48:55 +0000
218@@ -28,11 +28,13 @@
219 ###############################################################################
220
221 import logging
222+import copy
223
224 from PyQt4 import QtCore
225
226 from openlp.core.common import Registry
227 from openlp.core.ui import HideMode
228+from openlp.core.lib import ServiceItemContext, ServiceItem
229
230 log = logging.getLogger(__name__)
231
232@@ -69,6 +71,7 @@
233 return
234 self.doc.slidenumber = slide_no
235 self.hide_mode = hide_mode
236+ log.debug('add_handler, slidenumber: %d' % slide_no)
237 if self.is_live:
238 if hide_mode == HideMode.Screen:
239 Registry().execute('live_display_hide', HideMode.Screen)
240@@ -316,6 +319,28 @@
241 hide_mode = message[2]
242 file = item.get_frame_path()
243 self.handler = item.processor
244+ # When starting presentation from the servicemanager we convert
245+ # PDF/XPS-serviceitems into image-serviceitems. When started from the mediamanager
246+ # the conversion has already been done at this point.
247+ if file.endswith('.pdf') or file.endswith('.xps'):
248+ log.debug('Converting from pdf/xps to images for serviceitem with file %s', file)
249+ # Create a copy of the original item, and then clear the original item so it can be filled with images
250+ item_cpy = copy.copy(item)
251+ item.__init__(None)
252+ if is_live:
253+ self.media_item.generate_slide_data(item, item_cpy, False, False, ServiceItemContext.Live, file)
254+ else:
255+ self.media_item.generate_slide_data(item, item_cpy, False, False, ServiceItemContext.Preview, file)
256+ # Some of the original serviceitem attributes is needed in the new serviceitem
257+ item.footer = item_cpy.footer
258+ item.from_service = item_cpy.from_service
259+ item.iconic_representation = item_cpy.iconic_representation
260+ item.image_border = item_cpy.image_border
261+ item.main = item_cpy.main
262+ item.theme_data = item_cpy.theme_data
263+ # When presenting PDF or XPS, we are using the image presentation code,
264+ # so handler & processor is set to None, and we skip adding the handler.
265+ self.handler = None
266 if self.handler == self.media_item.automatic:
267 self.handler = self.media_item.findControllerByType(file)
268 if not self.handler:
269@@ -324,7 +349,12 @@
270 controller = self.live_handler
271 else:
272 controller = self.preview_handler
273- controller.add_handler(self.controllers[self.handler], file, hide_mode, message[3])
274+ # When presenting PDF or XPS, we are using the image presentation code,
275+ # so handler & processor is set to None, and we skip adding the handler.
276+ if self.handler is None:
277+ self.controller = controller
278+ else:
279+ controller.add_handler(self.controllers[self.handler], file, hide_mode, message[3])
280
281 def slide(self, message):
282 """
283
284=== added file 'openlp/plugins/presentations/lib/pdfcontroller.py'
285--- openlp/plugins/presentations/lib/pdfcontroller.py 1970-01-01 00:00:00 +0000
286+++ openlp/plugins/presentations/lib/pdfcontroller.py 2014-02-21 21:48:55 +0000
287@@ -0,0 +1,315 @@
288+# -*- coding: utf-8 -*-
289+# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
290+
291+###############################################################################
292+# OpenLP - Open Source Lyrics Projection #
293+# --------------------------------------------------------------------------- #
294+# Copyright (c) 2008-2014 Raoul Snyman #
295+# Portions copyright (c) 2008-2014 Tim Bentley, Gerald Britton, Jonathan #
296+# Corwin, Samuel Findlay, Michael Gorven, Scott Guerrieri, Matthias Hub, #
297+# Meinert Jordan, Armin Köhler, Erik Lundin, Edwin Lunando, Brian T. Meyer. #
298+# Joshua Miller, Stevan Pettit, Andreas Preikschat, Mattias Põldaru, #
299+# Christian Richter, Philip Ridout, Simon Scudder, Jeffrey Smith, #
300+# Maikel Stuivenberg, Martin Thompson, Jon Tibble, Dave Warnock, #
301+# Frode Woldsund, Martin Zibricky, Patrick Zimmermann #
302+# --------------------------------------------------------------------------- #
303+# This program is free software; you can redistribute it and/or modify it #
304+# under the terms of the GNU General Public License as published by the Free #
305+# Software Foundation; version 2 of the License. #
306+# #
307+# This program is distributed in the hope that it will be useful, but WITHOUT #
308+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
309+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
310+# more details. #
311+# #
312+# You should have received a copy of the GNU General Public License along #
313+# with this program; if not, write to the Free Software Foundation, Inc., 59 #
314+# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
315+###############################################################################
316+
317+import os
318+import logging
319+from tempfile import NamedTemporaryFile
320+import re
321+from subprocess import check_output, CalledProcessError, STDOUT
322+
323+from openlp.core.utils import AppLocation
324+from openlp.core.common import Settings
325+from openlp.core.lib import ScreenList
326+from .presentationcontroller import PresentationController, PresentationDocument
327+
328+log = logging.getLogger(__name__)
329+
330+
331+class PdfController(PresentationController):
332+ """
333+ Class to control PDF presentations
334+ """
335+ log.info('PdfController loaded')
336+
337+ def __init__(self, plugin):
338+ """
339+ Initialise the class
340+
341+ :param plugin: The plugin that creates the controller.
342+ """
343+ log.debug('Initialising')
344+ self.process = None
345+ PresentationController.__init__(self, plugin, 'Pdf', PdfDocument)
346+ self.supports = ['pdf']
347+ self.also_supports = []
348+ # Determine whether mudraw or ghostscript is used
349+ self.check_installed()
350+
351+ @staticmethod
352+ def check_binary(program_path):
353+ """
354+ Function that checks whether a binary is either ghostscript or mudraw or neither.
355+ Is also used from presentationtab.py
356+
357+ :param program_path:The full path to the binary to check.
358+ :return: Type of the binary, 'gs' if ghostscript, 'mudraw' if mudraw, None if invalid.
359+ """
360+ program_type = None
361+ runlog = ''
362+ log.debug('testing program_path: %s', program_path)
363+ try:
364+ runlog = check_output([program_path, '--help'], stderr=STDOUT)
365+ except CalledProcessError as e:
366+ runlog = e.output
367+ except Exception:
368+ runlog = ''
369+ # Analyse the output to see it the program is mudraw, ghostscript or neither
370+ for line in runlog.splitlines():
371+ decoded_line = line.decode()
372+ found_mudraw = re.search('usage: mudraw.*', decoded_line)
373+ if found_mudraw:
374+ program_type = 'mudraw'
375+ break
376+ found_gs = re.search('GPL Ghostscript.*', decoded_line)
377+ if found_gs:
378+ program_type = 'gs'
379+ break
380+ log.debug('in check_binary, found: %s', program_type)
381+ return program_type
382+
383+ def check_available(self):
384+ """
385+ PdfController is able to run on this machine.
386+
387+ :return: True if program to open PDF-files was found, otherwise False.
388+ """
389+ log.debug('check_available Pdf')
390+ return self.check_installed()
391+
392+ def check_installed(self):
393+ """
394+ Check the viewer is installed.
395+
396+ :return: True if program to open PDF-files was found, otherwise False.
397+ """
398+ log.debug('check_installed Pdf')
399+ self.mudrawbin = ''
400+ self.gsbin = ''
401+ self.also_supports = []
402+ # Use the user defined program if given
403+ if (Settings().value('presentations/enable_pdf_program')):
404+ pdf_program = Settings().value('presentations/pdf_program')
405+ program_type = self.check_binary(pdf_program)
406+ if program_type == 'gs':
407+ self.gsbin = pdf_program
408+ elif program_type == 'mudraw':
409+ self.mudrawbin = pdf_program
410+ else:
411+ # Fallback to autodetection
412+ application_path = AppLocation.get_directory(AppLocation.AppDir)
413+ if os.name == 'nt':
414+ # for windows we only accept mudraw.exe in the base folder
415+ application_path = AppLocation.get_directory(AppLocation.AppDir)
416+ if os.path.isfile(application_path + '/../mudraw.exe'):
417+ self.mudrawbin = application_path + '/../mudraw.exe'
418+ else:
419+ # First try to find mupdf
420+ try:
421+ self.mudrawbin = check_output(['which', 'mudraw']).decode(encoding='UTF-8').rstrip('\n')
422+ except CalledProcessError:
423+ self.mudrawbin = ''
424+ # if mupdf isn't installed, fallback to ghostscript
425+ if not self.mudrawbin:
426+ try:
427+ self.gsbin = check_output(['which', 'gs']).rstrip('\n')
428+ except CalledProcessError:
429+ self.gsbin = ''
430+ # Last option: check if mudraw is placed in OpenLP base folder
431+ if not self.mudrawbin and not self.gsbin:
432+ application_path = AppLocation.get_directory(AppLocation.AppDir)
433+ if os.path.isfile(application_path + '/../mudraw'):
434+ self.mudrawbin = application_path + '/../mudraw'
435+ if self.mudrawbin:
436+ self.also_supports = ['xps']
437+ return True
438+ elif self.gsbin:
439+ return True
440+ else:
441+ return False
442+
443+ def kill(self):
444+ """
445+ Called at system exit to clean up any running presentations
446+ """
447+ log.debug('Kill pdfviewer')
448+ while self.docs:
449+ self.docs[0].close_presentation()
450+
451+
452+class PdfDocument(PresentationDocument):
453+ """
454+ Class which holds information of a single presentation.
455+ This class is not actually used to present the PDF, instead we convert to
456+ image-serviceitem on the fly and present as such. Therefore some of the 'playback'
457+ functions is not implemented.
458+ """
459+ def __init__(self, controller, presentation):
460+ """
461+ Constructor, store information about the file and initialise.
462+ """
463+ log.debug('Init Presentation Pdf')
464+ PresentationDocument.__init__(self, controller, presentation)
465+ self.presentation = None
466+ self.blanked = False
467+ self.hidden = False
468+ self.image_files = []
469+ self.num_pages = -1
470+
471+ def gs_get_resolution(self, size):
472+ """
473+ Only used when using ghostscript
474+ Ghostscript can't scale automatically while keeping aspect like mupdf, so we need
475+ to get the ratio between the screen size and the PDF to scale
476+
477+ :param size: Size struct containing the screen size.
478+ :return: The resolution dpi to be used.
479+ """
480+ # Use a postscript script to get size of the pdf. It is assumed that all pages have same size
481+ gs_resolution_script = AppLocation.get_directory(AppLocation.PluginsDir) + '/presentations/lib/ghostscript_get_resolution.ps'
482+ # Run the script on the pdf to get the size
483+ runlog = []
484+ try:
485+ runlog = check_output([self.controller.gsbin, '-dNOPAUSE', '-dNODISPLAY', '-dBATCH',
486+ '-sFile=' + self.filepath, gs_resolution_script])
487+ except CalledProcessError as e:
488+ log.debug(' '.join(e.cmd))
489+ log.debug(e.output)
490+ # Extract the pdf resolution from output, the format is " Size: x: <width>, y: <height>"
491+ width = 0
492+ height = 0
493+ for line in runlog.splitlines():
494+ try:
495+ width = int(re.search('.*Size: x: (\d+\.?\d*), y: \d+.*', line.decode()).group(1))
496+ height = int(re.search('.*Size: x: \d+\.?\d*, y: (\d+\.?\d*).*', line.decode()).group(1))
497+ break
498+ except AttributeError:
499+ pass
500+ # Calculate the ratio from pdf to screen
501+ if width > 0 and height > 0:
502+ width_ratio = size.right() / float(width)
503+ height_ratio = size.bottom() / float(height)
504+ # return the resolution that should be used. 72 is default.
505+ if width_ratio > height_ratio:
506+ return int(height_ratio * 72)
507+ else:
508+ return int(width_ratio * 72)
509+ else:
510+ return 72
511+
512+ def load_presentation(self):
513+ """
514+ Called when a presentation is added to the SlideController. It generates images from the PDF.
515+
516+ :return: True is loading succeeded, otherwise False.
517+ """
518+ log.debug('load_presentation pdf')
519+ # Check if the images has already been created, and if yes load them
520+ if os.path.isfile(os.path.join(self.get_temp_folder(), 'mainslide001.png')):
521+ created_files = sorted(os.listdir(self.get_temp_folder()))
522+ for fn in created_files:
523+ if os.path.isfile(os.path.join(self.get_temp_folder(), fn)):
524+ self.image_files.append(os.path.join(self.get_temp_folder(), fn))
525+ self.num_pages = len(self.image_files)
526+ return True
527+ size = ScreenList().current['size']
528+ # Generate images from PDF that will fit the frame.
529+ runlog = ''
530+ try:
531+ if not os.path.isdir(self.get_temp_folder()):
532+ os.makedirs(self.get_temp_folder())
533+ if self.controller.mudrawbin:
534+ runlog = check_output([self.controller.mudrawbin, '-w', str(size.right()), '-h', str(size.bottom()),
535+ '-o', os.path.join(self.get_temp_folder(), 'mainslide%03d.png'), self.filepath])
536+ elif self.controller.gsbin:
537+ resolution = self.gs_get_resolution(size)
538+ runlog = check_output([self.controller.gsbin, '-dSAFER', '-dNOPAUSE', '-dBATCH', '-sDEVICE=png16m',
539+ '-r' + str(resolution), '-dTextAlphaBits=4', '-dGraphicsAlphaBits=4',
540+ '-sOutputFile=' + os.path.join(self.get_temp_folder(), 'mainslide%03d.png'),
541+ self.filepath])
542+ created_files = sorted(os.listdir(self.get_temp_folder()))
543+ for fn in created_files:
544+ if os.path.isfile(os.path.join(self.get_temp_folder(), fn)):
545+ self.image_files.append(os.path.join(self.get_temp_folder(), fn))
546+ except Exception as e:
547+ log.debug(e)
548+ log.debug(runlog)
549+ return False
550+ self.num_pages = len(self.image_files)
551+ # Create thumbnails
552+ self.create_thumbnails()
553+ return True
554+
555+ def create_thumbnails(self):
556+ """
557+ Generates thumbnails
558+ """
559+ log.debug('create_thumbnails pdf')
560+ if self.check_thumbnails():
561+ return
562+ # use builtin function to create thumbnails from generated images
563+ index = 1
564+ for image in self.image_files:
565+ self.convert_thumbnail(image, index)
566+ index += 1
567+
568+ def close_presentation(self):
569+ """
570+ Close presentation and clean up objects. Triggered by new object being added to SlideController or OpenLP being
571+ shut down.
572+ """
573+ log.debug('close_presentation pdf')
574+ self.controller.remove_doc(self)
575+
576+ def is_loaded(self):
577+ """
578+ Returns true if a presentation is loaded.
579+
580+ :return: True if loaded, False if not.
581+ """
582+ log.debug('is_loaded pdf')
583+ if self.num_pages < 0:
584+ return False
585+ return True
586+
587+ def is_active(self):
588+ """
589+ Returns true if a presentation is currently active.
590+
591+ :return: True if active, False if not.
592+ """
593+ log.debug('is_active pdf')
594+ return self.is_loaded() and not self.hidden
595+
596+ def get_slide_count(self):
597+ """
598+ Returns total number of slides
599+
600+ :return: The number of pages in the presentation..
601+ """
602+ return self.num_pages
603
604=== modified file 'openlp/plugins/presentations/lib/presentationtab.py'
605--- openlp/plugins/presentations/lib/presentationtab.py 2013-12-24 08:56:50 +0000
606+++ openlp/plugins/presentations/lib/presentationtab.py 2014-02-21 21:48:55 +0000
607@@ -30,7 +30,9 @@
608 from PyQt4 import QtGui
609
610 from openlp.core.common import Settings, UiStrings, translate
611-from openlp.core.lib import SettingsTab
612+from openlp.core.lib import SettingsTab, build_icon
613+from openlp.core.lib.ui import critical_error_message_box
614+from .pdfcontroller import PdfController
615
616
617 class PresentationTab(SettingsTab):
618@@ -64,6 +66,7 @@
619 self.presenter_check_boxes[controller.name] = checkbox
620 self.controllers_layout.addWidget(checkbox)
621 self.left_layout.addWidget(self.controllers_group_box)
622+ # Advanced
623 self.advanced_group_box = QtGui.QGroupBox(self.left_column)
624 self.advanced_group_box.setObjectName('advanced_group_box')
625 self.advanced_layout = QtGui.QVBoxLayout(self.advanced_group_box)
626@@ -72,8 +75,34 @@
627 self.override_app_check_box.setObjectName('override_app_check_box')
628 self.advanced_layout.addWidget(self.override_app_check_box)
629 self.left_layout.addWidget(self.advanced_group_box)
630+ # Pdf options
631+ self.pdf_group_box = QtGui.QGroupBox(self.left_column)
632+ self.pdf_group_box.setObjectName('pdf_group_box')
633+ self.pdf_layout = QtGui.QFormLayout(self.pdf_group_box)
634+ self.pdf_layout.setObjectName('pdf_layout')
635+ self.pdf_program_check_box = QtGui.QCheckBox(self.pdf_group_box)
636+ self.pdf_program_check_box.setObjectName('pdf_program_check_box')
637+ self.pdf_layout.addRow(self.pdf_program_check_box)
638+ self.pdf_program_path_layout = QtGui.QHBoxLayout()
639+ self.pdf_program_path_layout.setObjectName('pdf_program_path_layout')
640+ self.pdf_program_path = QtGui.QLineEdit(self.pdf_group_box)
641+ self.pdf_program_path.setObjectName('pdf_program_path')
642+ self.pdf_program_path.setReadOnly(True)
643+ self.pdf_program_path.setPalette(self.get_grey_text_palette(True))
644+ self.pdf_program_path_layout.addWidget(self.pdf_program_path)
645+ self.pdf_program_browse_button = QtGui.QToolButton(self.pdf_group_box)
646+ self.pdf_program_browse_button.setObjectName('pdf_program_browse_button')
647+ self.pdf_program_browse_button.setIcon(build_icon(':/general/general_open.png'))
648+ self.pdf_program_browse_button.setEnabled(False)
649+ self.pdf_program_path_layout.addWidget(self.pdf_program_browse_button)
650+ self.pdf_layout.addRow(self.pdf_program_path_layout)
651+ self.left_layout.addWidget(self.pdf_group_box)
652 self.left_layout.addStretch()
653+ self.right_column.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
654 self.right_layout.addStretch()
655+ # Signals and slots
656+ self.pdf_program_browse_button.clicked.connect(self.on_pdf_program_browse_button_clicked)
657+ self.pdf_program_check_box.clicked.connect(self.on_pdf_program_check_box_clicked)
658
659 def retranslateUi(self):
660 """
661@@ -85,8 +114,11 @@
662 checkbox = self.presenter_check_boxes[controller.name]
663 self.set_controller_text(checkbox, controller)
664 self.advanced_group_box.setTitle(UiStrings().Advanced)
665+ self.pdf_group_box.setTitle(translate('PresentationPlugin.PresentationTab', 'PDF options'))
666 self.override_app_check_box.setText(
667 translate('PresentationPlugin.PresentationTab', 'Allow presentation application to be overridden'))
668+ self.pdf_program_check_box.setText(
669+ translate('PresentationPlugin.PresentationTab', 'Use given full path for mudraw or ghostscript binary:'))
670
671 def set_controller_text(self, checkbox, controller):
672 if checkbox.isEnabled():
673@@ -103,6 +135,14 @@
674 checkbox = self.presenter_check_boxes[controller.name]
675 checkbox.setChecked(Settings().value(self.settings_section + '/' + controller.name))
676 self.override_app_check_box.setChecked(Settings().value(self.settings_section + '/override app'))
677+ # load pdf-program settings
678+ enable_pdf_program = Settings().value(self.settings_section + '/enable_pdf_program')
679+ self.pdf_program_check_box.setChecked(enable_pdf_program)
680+ self.pdf_program_path.setPalette(self.get_grey_text_palette(not enable_pdf_program))
681+ self.pdf_program_browse_button.setEnabled(enable_pdf_program)
682+ pdf_program = Settings().value(self.settings_section + '/pdf_program')
683+ if pdf_program:
684+ self.pdf_program_path.setText(pdf_program)
685
686 def save(self):
687 """
688@@ -128,6 +168,18 @@
689 if Settings().value(setting_key) != self.override_app_check_box.checkState():
690 Settings().setValue(setting_key, self.override_app_check_box.checkState())
691 changed = True
692+ # Save pdf-settings
693+ pdf_program = self.pdf_program_path.text()
694+ enable_pdf_program = self.pdf_program_check_box.checkState()
695+ # If the given program is blank disable using the program
696+ if pdf_program == '':
697+ enable_pdf_program = 0
698+ if pdf_program != Settings().value(self.settings_section + '/pdf_program'):
699+ Settings().setValue(self.settings_section + '/pdf_program', pdf_program)
700+ changed = True
701+ if enable_pdf_program != Settings().value(self.settings_section + '/enable_pdf_program'):
702+ Settings().setValue(self.settings_section + '/enable_pdf_program', enable_pdf_program)
703+ changed = True
704 if changed:
705 self.settings_form.register_post_process('mediaitem_suffix_reset')
706 self.settings_form.register_post_process('mediaitem_presentation_rebuild')
707@@ -143,3 +195,43 @@
708 checkbox = self.presenter_check_boxes[controller.name]
709 checkbox.setEnabled(controller.is_available())
710 self.set_controller_text(checkbox, controller)
711+
712+ def on_pdf_program_browse_button_clicked(self):
713+ """
714+ Select the mudraw or ghostscript binary that should be used.
715+ """
716+ filename = QtGui.QFileDialog.getOpenFileName(self, translate('PresentationPlugin.PresentationTab',
717+ 'Select mudraw or ghostscript binary.'),
718+ self.pdf_program_path.text())
719+ if filename:
720+ program_type = PdfController.check_binary(filename)
721+ if not program_type:
722+ critical_error_message_box(UiStrings().Error,
723+ translate('PresentationPlugin.PresentationTab',
724+ 'The program is not ghostscript or mudraw which is required.'))
725+ else:
726+ self.pdf_program_path.setText(filename)
727+
728+ def on_pdf_program_check_box_clicked(self, checked):
729+ """
730+ When checkbox for manual entering pdf-program is clicked,
731+ enable or disable the textbox for the programpath and the browse-button.
732+
733+ :param checked: If the box is checked or not.
734+ """
735+ self.pdf_program_path.setPalette(self.get_grey_text_palette(not checked))
736+ self.pdf_program_browse_button.setEnabled(checked)
737+
738+ def get_grey_text_palette(self, greyed):
739+ """
740+ Returns a QPalette with greyed out text as used for placeholderText.
741+
742+ :param greyed: Determines whether the palette should be grayed.
743+ :return: The created palette.
744+ """
745+ palette = QtGui.QPalette()
746+ color = self.palette().color(QtGui.QPalette.Active, QtGui.QPalette.Text)
747+ if greyed:
748+ color.setAlpha(128)
749+ palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Text, color)
750+ return palette
751
752=== modified file 'openlp/plugins/presentations/presentationplugin.py'
753--- openlp/plugins/presentations/presentationplugin.py 2013-12-24 08:56:50 +0000
754+++ openlp/plugins/presentations/presentationplugin.py 2014-02-21 21:48:55 +0000
755@@ -45,9 +45,12 @@
756
757 __default_settings__ = {
758 'presentations/override app': QtCore.Qt.Unchecked,
759+ 'presentations/enable_pdf_program': QtCore.Qt.Unchecked,
760+ 'presentations/pdf_program': '',
761 'presentations/Impress': QtCore.Qt.Checked,
762 'presentations/Powerpoint': QtCore.Qt.Checked,
763 'presentations/Powerpoint Viewer': QtCore.Qt.Checked,
764+ 'presentations/Pdf': QtCore.Qt.Checked,
765 'presentations/presentations files': []
766 }
767
768
769=== modified file 'resources/pyinstaller/hook-openlp.plugins.presentations.presentationplugin.py'
770--- resources/pyinstaller/hook-openlp.plugins.presentations.presentationplugin.py 2013-12-24 08:56:50 +0000
771+++ resources/pyinstaller/hook-openlp.plugins.presentations.presentationplugin.py 2014-02-21 21:48:55 +0000
772@@ -29,4 +29,5 @@
773
774 hiddenimports = ['openlp.plugins.presentations.lib.impresscontroller',
775 'openlp.plugins.presentations.lib.powerpointcontroller',
776- 'openlp.plugins.presentations.lib.pptviewcontroller']
777+ 'openlp.plugins.presentations.lib.pptviewcontroller',
778+ 'openlp.plugins.presentations.lib.pdfcontroller']
779
780=== modified file 'tests/functional/openlp_plugins/presentations/test_mediaitem.py'
781--- tests/functional/openlp_plugins/presentations/test_mediaitem.py 2013-12-28 21:33:38 +0000
782+++ tests/functional/openlp_plugins/presentations/test_mediaitem.py 2014-02-21 21:48:55 +0000
783@@ -75,11 +75,16 @@
784 presentation_controller.also_supports = []
785 presentation_viewer_controller = MagicMock()
786 presentation_viewer_controller.enabled.return_value = False
787+ pdf_controller = MagicMock()
788+ pdf_controller.enabled.return_value = True
789+ pdf_controller.supports = ['pdf']
790+ pdf_controller.also_supports = ['xps']
791 # Mock the controllers.
792 self.media_item.controllers = {
793 'Impress': impress_controller,
794 'Powerpoint': presentation_controller,
795- 'Powerpoint Viewer': presentation_viewer_controller
796+ 'Powerpoint Viewer': presentation_viewer_controller,
797+ 'Pdf': pdf_controller
798 }
799
800 # WHEN: Build the file mask.
801@@ -92,3 +97,7 @@
802 'The file mask should contain the odp extension')
803 self.assertIn('*.ppt', self.media_item.on_new_file_masks,
804 'The file mask should contain the ppt extension')
805+ self.assertIn('*.pdf', self.media_item.on_new_file_masks,
806+ 'The file mask should contain the pdf extension')
807+ self.assertIn('*.xps', self.media_item.on_new_file_masks,
808+ 'The file mask should contain the xps extension')
809
810=== added file 'tests/functional/openlp_plugins/presentations/test_pdfcontroller.py'
811--- tests/functional/openlp_plugins/presentations/test_pdfcontroller.py 1970-01-01 00:00:00 +0000
812+++ tests/functional/openlp_plugins/presentations/test_pdfcontroller.py 2014-02-21 21:48:55 +0000
813@@ -0,0 +1,109 @@
814+# -*- coding: utf-8 -*-
815+# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
816+
817+###############################################################################
818+# OpenLP - Open Source Lyrics Projection #
819+# --------------------------------------------------------------------------- #
820+# Copyright (c) 2008-2014 Raoul Snyman #
821+# Portions copyright (c) 2008-2014 Tim Bentley, Gerald Britton, Jonathan #
822+# Corwin, Samuel Findlay, Michael Gorven, Scott Guerrieri, Matthias Hub, #
823+# Meinert Jordan, Armin Köhler, Erik Lundin, Edwin Lunando, Brian T. Meyer. #
824+# Joshua Miller, Stevan Pettit, Andreas Preikschat, Mattias Põldaru, #
825+# Christian Richter, Philip Ridout, Simon Scudder, Jeffrey Smith, #
826+# Maikel Stuivenberg, Martin Thompson, Jon Tibble, Dave Warnock, #
827+# Frode Woldsund, Martin Zibricky, Patrick Zimmermann #
828+# --------------------------------------------------------------------------- #
829+# This program is free software; you can redistribute it and/or modify it #
830+# under the terms of the GNU General Public License as published by the Free #
831+# Software Foundation; version 2 of the License. #
832+# #
833+# This program is distributed in the hope that it will be useful, but WITHOUT #
834+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
835+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
836+# more details. #
837+# #
838+# You should have received a copy of the GNU General Public License along #
839+# with this program; if not, write to the Free Software Foundation, Inc., 59 #
840+# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
841+###############################################################################
842+"""
843+This module contains tests for the PdfController
844+"""
845+import os
846+import shutil
847+from unittest import TestCase, SkipTest
848+from tempfile import mkstemp, mkdtemp
849+
850+from PyQt4 import QtGui
851+
852+from openlp.plugins.presentations.lib.pdfcontroller import PdfController, PdfDocument
853+from tests.functional import MagicMock
854+from openlp.core.common import Settings
855+from openlp.core.lib import ScreenList
856+from tests.utils.constants import TEST_RESOURCES_PATH
857+
858+__default_settings__ = {
859+ 'presentations/enable_pdf_program': False
860+}
861+
862+
863+class TestPdfController(TestCase):
864+ """
865+ Test the PdfController.
866+ """
867+ def setUp(self):
868+ """
869+ Set up the components need for all tests.
870+ """
871+ self.fd, self.ini_file = mkstemp('.ini')
872+ Settings().set_filename(self.ini_file)
873+ self.application = QtGui.QApplication.instance()
874+ ScreenList.create(self.application.desktop())
875+ Settings().extend_default_settings(__default_settings__)
876+ self.temp_folder = mkdtemp()
877+ self.thumbnail_folder = mkdtemp()
878+
879+ def tearDown(self):
880+ """
881+ Delete all the C++ objects at the end so that we don't have a segfault
882+ """
883+ del self.application
884+ try:
885+ os.unlink(self.ini_file)
886+ shutil.rmtree(self.thumbnail_folder)
887+ shutil.rmtree(self.temp_folder)
888+ except OSError:
889+ pass
890+
891+ def constructor_test(self):
892+ """
893+ Test the Constructor
894+ """
895+ # GIVEN: No presentation controller
896+ controller = None
897+
898+ # WHEN: The presentation controller object is created
899+ controller = PdfController(plugin=MagicMock())
900+
901+ # THEN: The name of the presentation controller should be correct
902+ self.assertEqual('Pdf', controller.name, 'The name of the presentation controller should be correct')
903+
904+ def load_pdf_test(self):
905+ """
906+ Test loading of a Pdf
907+ """
908+ # GIVEN: A Pdf-file
909+ test_file = os.path.join(TEST_RESOURCES_PATH, 'presentations', 'pdf_test1.pdf')
910+
911+ # WHEN: The Pdf is loaded
912+ controller = PdfController(plugin=MagicMock())
913+ if not controller.check_available():
914+ raise SkipTest('Could not detect mudraw or ghostscript, so skipping PDF test')
915+ controller.temp_folder = self.temp_folder
916+ controller.thumbnail_folder = self.thumbnail_folder
917+ document = PdfDocument(controller, test_file)
918+ loaded = document.load_presentation()
919+
920+ # THEN: The load should succeed and we should be able to get a pagecount
921+ self.assertTrue(loaded, 'The loading of the PDF should succeed.')
922+ self.assertEqual(3, document.get_slide_count(), 'The pagecount of the PDF should be 3.')
923
924=== added directory 'tests/resources/presentations'
925=== added file 'tests/resources/presentations/pdf_test1.pdf'
926Binary files tests/resources/presentations/pdf_test1.pdf 1970-01-01 00:00:00 +0000 and tests/resources/presentations/pdf_test1.pdf 2014-02-21 21:48:55 +0000 differ