-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathimpressive.py
executable file
·4214 lines (3840 loc) · 157 KB
/
impressive.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#
# Impressive, a fancy presentation tool
# Copyright (C) 2005-2008 Martin J. Fiedler <[email protected]>
# portions Copyright (C) 2005 Rob Reid <[email protected]>
# portions Copyright (C) 2006 Ronan Le Hy <[email protected]>
# portions Copyright (C) 2007 Luke Campagnola <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
__title__ = "Impressive (dual head)"
__version__ = "0.10.2"
__author__ = "Martin J. Fiedler"
__email__ = "[email protected]"
__website__ = "http://impressive.sourceforge.net/"
import sys
def greet(): print >>sys.stderr, "Welcome to", __title__, "version", __version__
if __name__ == "__main__": greet()
TopLeft, BottomLeft, TopRight, BottomRight, TopCenter, BottomCenter = range(6)
NoCache, MemCache, FileCache, PersistentCache = range(4) # for CacheMode
Off, First, Last = range(3) # for AutoOverview
# You may change the following lines to modify the default settings
Fullscreen = True
Scaling = False
Supersample = None
BackgroundRendering = True
UseGhostScript = False
UseAutoScreenSize = True
ScreenWidth = 1024
ScreenHeight = 768
TransitionDuration = 1000
MouseHideDelay = 3000
BoxFadeDuration = 100
ZoomDuration = 250
BlankFadeDuration = 250
MeshResX = 48
MeshResY = 36
MarkColor = (1.0, 0.0, 0.0, 0.1)
BoxEdgeSize = 4
SpotRadius = 64
SpotDetail = 16
CacheMode = FileCache
OverviewBorder = 3
OverviewLogoBorder = 24
AutoOverview = Off
InitialPage = None
Wrap = False
AutoAdvance = None
RenderToDirectory = None
Rotation = 0
AllowExtensions = True
DAR = None
PAR = 1.0
PollInterval = 0
PageRangeStart = 0
PageRangeEnd = 999999
FontSize = 14
FontTextureWidth = 512
FontTextureHeight = 256
Gamma = 1.0
BlackLevel = 0
GammaStep = 1.1
BlackLevelStep = 8
EstimatedDuration = None
ProgressBarSize = 16
ProgressBarAlpha = 128
CursorImage = None
CursorHotspot = (0, 0)
MinutesOnly = False
OSDMargin = 16
OSDAlpha = 1.0
OSDTimePos = TopRight
OSDTitlePos = BottomLeft
OSDPagePos = BottomRight
OSDStatusPos = TopLeft
# import basic modules
import random, getopt, os, types, re, codecs, tempfile, glob, StringIO, md5, re
import traceback
from math import *
# initialize some platform-specific settings
if os.name == "nt":
root = os.path.split(sys.argv[0])[0] or "."
pdftoppmPath = os.path.join(root, "pdftoppm.exe")
GhostScriptPath = os.path.join(root, "gs\\gswin32c.exe")
GhostScriptPlatformOptions = ["-I" + os.path.join(root, "gs")]
try:
import win32api
MPlayerPath = os.path.join(root, "mplayer.exe")
def GetScreenSize():
dm = win32api.EnumDisplaySettings(None, -1) #ENUM_CURRENT_SETTINGS
return (int(dm.PelsWidth), int(dm.PelsHeight))
def RunURL(url):
win32api.ShellExecute(0, "open", url, "", "", 0)
except ImportError:
MPlayerPath = ""
def GetScreenSize():
if True: # DualHead is not set at this point
return ProjectionFrame.size()
else:
return pygame.display.list_modes()[0]
def RunURL(url): print "Error: cannot run URL `%s'" % url
MPlayerPlatformOptions = [ "-colorkey", "0x000000" ]
MPlayerColorKey = True
pdftkPath = os.path.join(root, "pdftk.exe")
FileNameEscape = '"'
spawn = os.spawnv
if getattr(sys, "frozen", None):
sys.path.append(root)
FontPath = []
FontList = ["Verdana.ttf", "Arial.ttf"]
else:
pdftoppmPath = "pdftoppm"
GhostScriptPath = "gs"
GhostScriptPlatformOptions = []
MPlayerPath = "mplayer"
MPlayerPlatformOptions = [ "-vo", "gl" ]
MPlayerColorKey = False
pdftkPath = "pdftk"
spawn = os.spawnvp
FileNameEscape = ""
FontPath = ["/usr/share/fonts", "/usr/local/share/fonts", "/usr/X11R6/lib/X11/fonts/TTF"]
FontList = ["DejaVuSans.ttf", "Vera.ttf", "Verdana.ttf"]
def RunURL(url):
try:
spawn(os.P_NOWAIT, "xdg-open", ["xdg-open", url])
except OSError:
print >>sys.stderr, "Error: cannot open URL `%s'" % url
def GetScreenSize():
if True: # HACK: DualHead is not set at this point
return ProjectionFrame.size()
res_re = re.compile(r'\s*(\d+)x(\d+)\s+\d+\.\d+\*')
# parse string like
# LVDS connected 1280x800+1920+0 (normal left inverted right x axis y axis) 287mm x 180mm
todo_res_re = re.compile(r"""([^\s]+) # monitor name, e.g. LVDS or VGA
\s+connected\s+
([^s]+) # geometry expression""", re.VERBOSE)
# use different regex, do not match for strings ending with asterisk,
# search for strings with 'connected' and parse the complete
# geometry expression 1280x800+1920+0 for **every** monitor,
# use LVDS as prompter monitor and prefer VGA as projection monitor
for path in os.getenv("PATH").split(':'):
fullpath = os.path.join(path, "xrandr")
if os.path.exists(fullpath):
res = None
try:
for line in os.popen(fullpath, "r"):
m = res_re.match(line)
if m:
# m.group(1) - monitor name
# m.group(2) - X geometry expression
print "xrandr found matching line " + line
res = tuple(map(int, m.groups()))
print "xrandr found match " + str(res)
except OSError:
pass
if res:
return res
return pygame.display.list_modes()[0]
# import special modules
try:
from OpenGL.GL import *
import pygame
from pygame.locals import *
import Image, ImageDraw, ImageFont, ImageFilter
from PIL import TiffImagePlugin, BmpImagePlugin, JpegImagePlugin, PngImagePlugin, PpmImagePlugin
except (ValueError, ImportError), err:
print >>sys.stderr, "Oops! Cannot load necessary modules:", err
print >>sys.stderr, """To use Impressive, you need to install the following Python modules:
- PyOpenGL [python-opengl] http://pyopengl.sourceforge.net/
- PyGame [python-pygame] http://www.pygame.org/
- PIL [python-imaging] http://www.pythonware.com/products/pil/
- PyWin32 (OPTIONAL, Win32) http://starship.python.net/crew/mhammond/win32/
Additionally, please be sure to have pdftoppm or GhostScript installed if you
intend to use PDF input."""
sys.exit(1)
try:
import thread
EnableBackgroundRendering = True
def create_lock(): return thread.allocate_lock()
except ImportError:
EnableBackgroundRendering = False
class pseudolock:
def __init__(self): self.state = False
def acquire(self, dummy=0): self.state = True
def release(self): self.state = False
def locked(self): return self.state
def create_lock(): return pseudolock()
##### TOOL CODE ################################################################
# initialize private variables
FileName = ""
FileList = []
InfoScriptPath = None
Marking = False
Tracing = False
Panning = False
FileProps = {}
PageProps = {}
PageCache = {}
CacheFile = None
CacheFileName = None
CacheFilePos = 0
CacheMagic = ""
MPlayerPID = 0
VideoPlaying = False
MouseDownX = 0
MouseDownY = 0
MarkUL = (0, 0)
MarkLR = (0, 0)
ZoomX0 = 0.0
ZoomY0 = 0.0
ZoomArea = 1.0
ZoomMode = False
IsZoomed = False
ZoomWarningIssued = False
TransitionRunning = False
CurrentCaption = 0
OverviewNeedUpdate = False
FileStats = None
OSDFont = None
CurrentOSDCaption = ""
CurrentOSDPage = ""
CurrentOSDStatus = ""
CurrentOSDComment = ""
Lrender = create_lock()
Lcache = create_lock()
Loverview = create_lock()
RTrunning = False
RTrestart = False
StartTime = 0
CurrentTime = 0
PageEnterTime = 0
TimeDisplay = False
TimeTracking = False
FirstPage = True
ProgressBarPos = 0
CursorVisible = True
OverviewMode = False
LastPage = 0
WantStatus = False
# tool constants (used in info scripts)
FirstTimeOnly = 2
# event constants
USEREVENT_HIDE_MOUSE = USEREVENT
USEREVENT_PAGE_TIMEOUT = USEREVENT + 1
USEREVENT_POLL_FILE = USEREVENT + 2
USEREVENT_TIMER_UPDATE = USEREVENT + 3
# read and write the PageProps and FileProps meta-dictionaries
def GetProp(prop_dict, key, prop, default=None):
if not key in prop_dict: return default
if type(prop) == types.StringType:
return prop_dict[key].get(prop, default)
for subprop in prop:
try:
return prop_dict[key][subprop]
except KeyError:
pass
return default
def SetProp(prop_dict, key, prop, value):
if not key in prop_dict:
prop_dict[key] = {prop: value}
else:
prop_dict[key][prop] = value
def GetPageProp(page, prop, default=None):
global PageProps
return GetProp(PageProps, page, prop, default)
def SetPageProp(page, prop, value):
global PageProps
SetProp(PageProps, page, prop, value)
def GetTristatePageProp(page, prop, default=0):
res = GetPageProp(page, prop, default)
if res != FirstTimeOnly: return res
return (GetPageProp(page, '_shown', 0) == 1)
def GetFileProp(page, prop, default=None):
global FileProps
return GetProp(FileProps, page, prop, default)
def SetFileProp(page, prop, value):
global FileProps
SetProp(FileProps, page, prop, value)
# the Impressive logo (256x64 pixels grayscale PNG)
LOGO = '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01\x00\x00\x00\x00@\x08\x00\x00\x00\x00\xd06\xf6b\x00\x00\x0b\xf1IDATx\xda\xed[y|OW\x16\x7f\xbf\xfc\x12\x12K\x13\xb1\xc4R\x11\xbbN,c\xadHF\xa8\xd6RK\xa7Cf\x08>\xaa\xed\xa0\xa5\x8a\xd8\xe9Hc\x9dRK\x19'+\
'\xb4b\xd4V{\x8d}\xcd\xa0\x944\xb6PF\xc6RU\x82\xa4\x96HD\xf6\xbc\xfe\xee9\xf7\xdew\xee{?Lc>\x9fL\xe6\xe7\xfe\x11\xf7\x9c\xbb\x9c{\xcf\xbb\xf7\x9c\xef9\xf7G\xd3\x9e\x97\xe7\xa5\xa8\x97\x12#7\xdfN:2\xbc\x98\xab\xee\xbf\xd2\t\x1dJB\t\xd7\xdc\x7f\xe9\xeb:/'+\
'\x13\x9fa\x96\xe0O"\xeb\x16Q\x05\xf4\x12\xfb\xd7\xbf)\xf8$C\xf3u=\xa3C\xd1T\xc0F\xa9\x80\x1b\x05\x9e\xc3\'\x93\x8d\xbfZ4-`\xbaT\xc0\x99\x02O\xd2\n\'(U\x14\x15\xd0X\xee__W\xe0I*\xe6\xb3\xf1?\x17\xc9\x13\xd0\xd5P\xc0\xc7\x05\x9fe\xa6cx~\xbf\x82\x8e\x8e'+\
'\\\xeb(S\x0bI\x01\xef\x19\n\xe8\xf5\x0c\xd3\xbc\xb5u\xedk\x05\x1e|\x8dI\xdfTH\n\x98j(\xa0q!-\xa1x\x1e\x93>\xa3\x90\xa4/\x97\x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9\x8b\xb1\x03\xc7\xa6d'+\
'\x0b2SRR\x92\xce\x1f\xda8\xb9\x95\xdd|\xd6\xd5\xdeJi0~g\xfc\xads\x1b\xa2\xc2\x1b\xab\x98\xc8V3l\xda\xee\xeb\xdfE\x0f3\xa3\xe0\xae\x93\xb6\xfcxj\xc5\xe8\xe6J\xa6\xa8\xd9\xe0\t\xed\xad[\rZ\xbc\xf81\xbf\x98\xaa>l\xcb\x89\x1b\x17\xb7\xcc\xe8\xd7'+\
'\xc2\xe3\xbf\xf1\xd3\x00\xcc\xb3L\xd0\\\xb64\x03\x05\xf4t]\x05\xf4\xfc\x95?\xcd\xf8\xbf+\xe8\xb8}\\W\x01\xf0Fr\xc7u\xf7\x8fAv\xac\x0b+\x00~\xce\xb2\xcau\xf7_\x9a&\x7f\\\xb14\xb6\xbcz\xb8X\t\xb3<J\xb8X\x19gy\xf5p\xb1\xb2\xd4\xf2\xea\xe1b\xe5'+\
'\x90\xe5\xd5\xc3\xc5J\xe2\xb3\xfdW\xa5\xe7\xe5y\xf9\x1f(\xbf\x00\x8e\xf2\xeb\x86\xaa\xb6u\xc1\x00\x00\x00\x00IEND\xaeB`\x82'
# determine the next power of two
def npot(x):
res = 1
while res < x: res <<= 1
return res
# convert boolean value to string
def b2s(b):
if b: return "Y"
return "N"
# extract a number at the beginning of a string
def num(s):
s = s.strip()
r = ""
while s[0] in "0123456789":
r += s[0]
s = s[1:]
try:
return int(r)
except ValueError:
return -1
# get a representative subset of file statistics
def my_stat(filename):
try:
s = os.stat(filename)
except OSError:
return None
return (s.st_size, s.st_mtime, s.st_ctime, s.st_mode)
# determine (pagecount,width,height) of a PDF file
def analyze_pdf(filename):
f = file(filename,"rb")
pdf = f.read()
f.close()
box = map(float, pdf.split("/MediaBox",1)[1].split("]",1)[0].split("[",1)[1].strip().split())
return (max(map(num, pdf.split("/Count")[1:])), box[2]-box[0], box[3]-box[1])
# unescape { literals in PDF files
re_unescape = re.compile(r'&#[0-9]+;')
def decode_literal(m):
try:
return chr(int(m.group(0)[2:-1]))
except ValueError:
return '?'
def unescape_pdf(s):
return re_unescape.sub(decode_literal, s)
# parse pdftk output
def pdftkParse(filename, page_offset=0):
f = file(filename, "r")
InfoKey = None
BookmarkTitle = None
Title = None
Pages = 0
for line in f.xreadlines():
try:
key, value = [item.strip() for item in line.split(':', 1)]
except IndexError:
continue
key = key.lower()
if key == "numberofpages":
Pages = int(value)
elif key == "infokey":
InfoKey = value.lower()
elif (key == "infovalue") and (InfoKey == "title"):
Title = unescape_pdf(value)
InfoKey = None
elif key == "bookmarktitle":
BookmarkTitle = unescape_pdf(value)
elif key == "bookmarkpagenumber" and BookmarkTitle:
try:
page = int(value)
if not GetPageProp(page + page_offset, '_title'):
SetPageProp(page + page_offset, '_title', BookmarkTitle)
except ValueError:
pass
BookmarkTitle = None
f.close()
if AutoOverview:
SetPageProp(page_offset + 1, '_overview', True)
for page in xrange(page_offset + 2, page_offset + Pages):
SetPageProp(page, '_overview', \
not(not(GetPageProp(page + AutoOverview - 1, '_title'))))
SetPageProp(page_offset + Pages, '_overview', True)
return (Title, Pages)
# translate pixel coordinates to normalized screen coordinates
def MouseToScreen(mousepos):
return (ZoomX0 + mousepos[0] * ZoomArea / ScreenWidth,
ZoomY0 + mousepos[1] * ZoomArea / ScreenHeight)
# normalize rectangle coordinates so that the upper-left point comes first
def NormalizeRect(X0, Y0, X1, Y1):
return (min(X0, X1), min(Y0, Y1), max(X0, X1), max(Y0, Y1))
# check if a point is inside a box (or a list of boxes)
def InsideBox(x, y, box):
return (x >= box[0]) and (y >= box[1]) and (x < box[2]) and (y < box[3])
def FindBox(x, y, boxes):
for i in xrange(len(boxes)):
if InsideBox(x, y, boxes[i]):
return i
raise ValueError
# zoom an image size to a destination size, preserving the aspect ratio
def ZoomToFit(size, dest=None):
if not dest:
dest = (ScreenWidth, ScreenHeight)
newx = dest[0]
newy = size[1] * newx / size[0]
if newy > dest[1]:
newy = dest[1]
newx = size[0] * newy / size[1]
return (newx, newy)
# get the overlay grid screen coordinates for a specific page
def OverviewPos(page):
return ( \
int(page % OverviewGridSize) * OverviewCellX + OverviewOfsX, \
int(page / OverviewGridSize) * OverviewCellY + OverviewOfsY \
)
def StopMPlayer():
global MPlayerPID, VideoPlaying
if not MPlayerPID: return
try:
if os.name == 'nt':
win32api.TerminateProcess(MPlayerPID, 0)
else:
os.kill(MPlayerPID, 2)
MPlayerPID = 0
except:
pass
VideoPlaying = False
def FormatTime(t, minutes=False):
if minutes and (t < 3600):
return "%d min" % (t / 60)
elif minutes:
return "%d:%02d" % (t / 3600, (t / 60) % 60)
elif t < 3600:
return "%d:%02d" % (t / 60, t % 60)
else:
ms = t % 3600
return "%d:%02d:%02d" % (t / 3600, ms / 60, ms % 60)
def SafeCall(func, args=[], kwargs={}):
if not func: return None
try:
return func(*args, **kwargs)
except:
print >>sys.stderr, "----- Exception in user function ----"
traceback.print_exc(file=sys.stderr)
print >>sys.stderr, "----- End of traceback -----"
def Quit(code=0):
print >>sys.stderr, "Total presentation time: %s." % \
FormatTime((pygame.time.get_ticks() - StartTime) / 1000)
sys.exit(code)
##### RENDERING TOOL CODE ######################################################
class FrameCoordinates:
RESOLUTION_REGEX = re.compile(
r"(\d+)x(\d+)")
GEOMETRY_REGEX = re.compile(
r"""(\d+)x(\d+) # resolution
\+(\d+)\+(\d+) # offset""", re.VERBOSE)
# offset_x, offset_y, width, height
def __init__(self, width=None, height=None, offset_x=0, offset_y=0, size_tuple=None, full_tuple=None):
if full_tuple:
self.__init__(full_tuple[0], full_tuple[1], full_tuple[2], full_tuple[3])
elif size_tuple:
self.__init__(size_tuple[0], size_tuple[1], offset_x, offset_y)
elif width and height:
self.width = width
self.height = height
self.offset_x = offset_x
self.offset_y = offset_y
else:
raise ValueError, "no size given"
@classmethod
def parse(cls, geometry):
"""Creates new FrameCoordinates object by parsing a X11 like geometry string.
Example: 1024x768+1280+0"""
parsed = FrameCoordinates.GEOMETRY_REGEX.match(geometry)
if parsed:
return cls(full_tuple=[int(elem) for elem in parsed.groups()])
else:
parsed = FrameCoordinates.RESOLUTION_REGEX.match(geometry)
if parsed:
return cls(size_tuple=[int(elem) for elem in parsed.groups()])
else:
raise ValueError, "Geometry string '%s' could not be parsed" % geometry
def __repr__(self):
return "size %d,%d offset %d,%d" % (self.width, self.height, self.offset_x, self.offset_y)
def as_tuple(self):
return (self.width, self.height, self.offset_x, self.offset_y)
def size(self):
return (self.width, self.height)
def offset(self):
return (self.offset_x, self.offset_y)
def divide_padding(self, amount, ratio):
sum = ratio[0] + ratio[1]
if sum > 0:
return amount * ratio[0] / sum
else:
return 0
def adjust_to_aspect_ratio(self, aspect_ratio, vertical_padding_ratio=(1,1), horizontal_padding_ratio=(1,1)):
"""The new box will completely fit into the old one, have desired aspect ratio,
and will be padded with white space in required proportion.
Ratio parameters are two-element-tuples
(1,1) for padding means 'center!'
(1,2) for horizontal_padding means one third left and two thirds right
vertical ratio is bottom to top (upside down), horizontal is left to right """
new_width = self.height * aspect_ratio[0] / aspect_ratio[1]
new_height = self.width * aspect_ratio[1] / aspect_ratio[0]
if new_width <= self.width:
self.offset_x += self.divide_padding(self.width-new_width, horizontal_padding_ratio)
self.width = new_width
else:
self.offset_y += self.divide_padding(self.height-new_height, vertical_padding_ratio)
self.height = new_height
def glViewport(self):
glViewport(self.offset_x, self.offset_y, self.width, self.height)
# draw a fullscreen quad
def DrawFullQuad():
glBegin(GL_QUADS)
glTexCoord2d( 0.0, 0.0); glVertex2i(0, 0)
glTexCoord2d(TexMaxS, 0.0); glVertex2i(1, 0)
glTexCoord2d(TexMaxS, TexMaxT); glVertex2i(1, 1)
glTexCoord2d( 0.0, TexMaxT); glVertex2i(0, 1)
glEnd()
def DrawFullQuadProbe(): # TODO: probe for rendering twice
glBegin(GL_QUADS)
glTexCoord2d( 0.0, 0.0); glVertex2d(0, 0)
glTexCoord2d(TexMaxS, 0.0); glVertex2d(0.5, 0)
glTexCoord2d(TexMaxS, TexMaxT); glVertex2d(0.5, 0.5)
glTexCoord2d( 0.0, TexMaxT); glVertex2d(0, 0.5)
glTexCoord2d( 0.0, 0.0); glVertex2d(0.5, 0)
glTexCoord2d(TexMaxS, 0.0); glVertex2d(1, 0)
glTexCoord2d(TexMaxS, TexMaxT); glVertex2d(1, 0.5)
glTexCoord2d( 0.0, TexMaxT); glVertex2d(0.5, 0.5)
glEnd()
# draw a generic 2D quad
def DrawQuad(x0=0.0, y0=0.0, x1=1.0, y1=1.0):
glBegin(GL_QUADS)
glTexCoord2d( 0.0, 0.0); glVertex2d(x0, y0)
glTexCoord2d(TexMaxS, 0.0); glVertex2d(x1, y0)
glTexCoord2d(TexMaxS, TexMaxT); glVertex2d(x1, y1)
glTexCoord2d( 0.0, TexMaxT); glVertex2d(x0, y1)
glEnd()
# helper function: draw a translated fullscreen quad
def DrawTranslatedFullQuad(dx, dy, i, a):
glColor4d(i, i, i, a)
glPushMatrix()
glTranslated(dx, dy, 0.0)
DrawFullQuad()
glPopMatrix()
# draw a vertex in normalized screen coordinates,
# setting texture coordinates appropriately
def DrawPoint(x, y):
glTexCoord2d(x *TexMaxS, y * TexMaxT)
glVertex2d(x, y)
def DrawPointEx(x, y, a):
glColor4d(1.0, 1.0, 1.0, a)
glTexCoord2d(x * TexMaxS, y * TexMaxT)
glVertex2d(x, y)
# a mesh transformation function: it gets the relative transition time (in the
# [0.0,0.1) interval) and the normalized 2D screen coordinates, and returns a
# 7-tuple containing the desired 3D screen coordinates, 2D texture coordinates,
# and intensity/alpha color values.
def meshtrans_null(t, u, v):
return (u, v, 0.0, u, v, 1.0, t)
# (x, y, z, s, t, i, a)
# draw a quad, applying a mesh transformation function
def DrawMeshQuad(time=0.0, f=meshtrans_null):
line0 = [f(time, u * MeshStepX, 0.0) for u in xrange(MeshResX + 1)]
for v in xrange(1, MeshResY + 1):
line1 = [f(time, u * MeshStepX, v * MeshStepY) for u in xrange(MeshResX + 1)]
glBegin(GL_QUAD_STRIP)
for col in zip(line0, line1):
for x, y, z, s, t, i, a in col:
glColor4d(i, i, i, a)
glTexCoord2d(s * TexMaxS, t * TexMaxT)
glVertex3d(x, y, z)
glEnd()
line0 = line1
def GenerateSpotMesh():
global SpotMesh
rx0 = SpotRadius * PixelX
ry0 = SpotRadius * PixelY
rx1 = (SpotRadius + BoxEdgeSize) * PixelX
ry1 = (SpotRadius + BoxEdgeSize) * PixelY
steps = max(6, int(2.0 * pi * SpotRadius / SpotDetail / ZoomArea))
SpotMesh=[(rx0 * sin(a), ry0 * cos(a), rx1 * sin(a), ry1 * cos(a)) for a in \
[i * 2.0 * pi / steps for i in range(steps + 1)]]
##### TRANSITIONS ##############################################################
# Each transition is represented by a class derived from impressive.Transition
# The interface consists of only two methods: the __init__ method may perform
# some transition-specific initialization, and render() finally renders a frame
# of the transition, using the global texture identifiers Tcurrent and Tnext.
# Transition itself is an abstract class
class AbstractError(StandardError):
pass
class Transition:
def __init__(self):
pass
def render(self, t):
raise AbstractError
# an array containing all possible transition classes
AllTransitions=[]
# a helper function doing the common task of directly blitting a background page
def DrawPageDirect(tex):
glDisable(GL_BLEND)
glBindTexture(TextureTarget, tex)
glColor3d(1, 1, 1)
DrawFullQuad()
# a helper function that enables alpha blending
def EnableAlphaBlend():
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
# Crossfade: one of the simplest transition you can think of :)
class Crossfade(Transition):
"""simple crossfade"""
def render(self,t):
DrawPageDirect(Tcurrent)
EnableAlphaBlend()
glBindTexture(TextureTarget, Tnext)
glColor4d(1, 1, 1, t)
DrawFullQuad()
AllTransitions.append(Crossfade)
# Slide: a class of transitions that simply slide the new page in from one side
# after an idea from Joachim B Haga
class Slide(Transition):
def origin(self, t):
raise AbstractError
def render(self, t):
cx, cy, nx, ny = self.origin(t)
glBindTexture(TextureTarget, Tcurrent)
DrawQuad(cx, cy, cx+1.0, cy+1.0)
glBindTexture(TextureTarget, Tnext)
DrawQuad(nx, ny, nx+1.0, ny+1.0)
class SlideLeft(Slide):
"""Slide to the left"""
def origin(self, t): return (-t, 0.0, 1.0-t, 0.0)
class SlideRight(Slide):
"""Slide to the right"""
def origin(self, t): return (t, 0.0, t-1.0, 0.0)
class SlideUp(Slide):
"""Slide upwards"""
def origin(self, t): return (0.0, -t, 0.0, 1.0-t)
class SlideDown(Slide):
"""Slide downwards"""
def origin(self, t): return (0.0, t, 0.0, t-1.0)
AllTransitions.extend([SlideLeft, SlideRight, SlideUp, SlideDown])
# Squeeze: a class of transitions that squeeze the new page in from one size
class Squeeze(Transition):
def params(self, t):
raise AbstractError
def inv(self): return 0
def render(self, t):
cx1, cy1, nx0, ny0 = self.params(t)
if self.inv():
t1, t2 = (Tnext, Tcurrent)
else:
t1, t2 = (Tcurrent, Tnext)
glBindTexture(TextureTarget, t1)
DrawQuad(0.0, 0.0, cx1, cy1)
glBindTexture(TextureTarget, t2)
DrawQuad(nx0, ny0, 1.0, 1.0)
class SqueezeHorizontal(Squeeze):
def split(self, t): raise AbstractError
def params(self, t):
t = self.split(t)
return (t, 1.0, t, 0.0)
class SqueezeVertical(Squeeze):
def split(self, t): raise AbstractError
def params(self, t):
t = self.split(t)
return (1.0, t, 0.0, t)
class SqueezeLeft(SqueezeHorizontal):
"""Squeeze to the left"""
def split(self, t): return 1.0 - t
class SqueezeRight(SqueezeHorizontal):
"""Squeeze to the right"""
def split(self, t): return t
def inv(self): return 1
class SqueezeUp(SqueezeVertical):
"""Squeeze upwards"""
def split(self, t): return 1.0 - t
class SqueezeDown(SqueezeVertical):
"""Squeeze downwards"""
def split(self, t): return t
def inv(self): return 1
AllTransitions.extend([SqueezeLeft, SqueezeRight, SqueezeUp, SqueezeDown])
# Wipe: a class of transitions that softly "wipe" the new image over the old
# one along a path specified by a gradient function that maps normalized screen
# coordinates to a number in the range [0.0,1.0]
WipeWidth = 0.25
class Wipe(Transition):
def grad(self, u, v):
raise AbstractError
def afunc(self, g):
pos = (g - self.Wipe_start) / WipeWidth
return max(min(pos, 1.0), 0.0)
def render(self, t):
DrawPageDirect(Tnext)
EnableAlphaBlend()
glBindTexture(TextureTarget, Tcurrent)
self.Wipe_start = t * (1.0 + WipeWidth) - WipeWidth
DrawMeshQuad(t, lambda t, u, v: \
(u, v, 0.0, u,v, 1.0, self.afunc(self.grad(u, v))))
class WipeDown(Wipe):
"""wipe downwards"""
def grad(self, u, v): return v
class WipeUp(Wipe):
"""wipe upwards"""
def grad(self, u, v): return 1.0 - v
class WipeRight(Wipe):
"""wipe from left to right"""
def grad(self, u, v): return u
class WipeLeft(Wipe):
"""wipe from right to left"""
def grad(self, u, v): return 1.0 - u
class WipeDownRight(Wipe):
"""wipe from the upper-left to the lower-right corner"""
def grad(self, u, v): return 0.5 * (u + v)
class WipeUpLeft(Wipe):
"""wipe from the lower-right to the upper-left corner"""
def grad(self, u, v): return 1.0 - 0.5 * (u + v)
class WipeCenterOut(Wipe):
"""wipe from the center outwards"""
def grad(self, u, v):
u -= 0.5
v -= 0.5
return sqrt(u * u * 1.777 + v * v) / 0.833
class WipeCenterIn(Wipe):
"""wipe from the edges inwards"""
def grad(self, u, v):
u -= 0.5
v -= 0.5
return 1.0 - sqrt(u * u * 1.777 + v * v) / 0.833
AllTransitions.extend([WipeDown, WipeUp, WipeRight, WipeLeft, \
WipeDownRight, WipeUpLeft, WipeCenterOut, WipeCenterIn])
class WipeBlobs(Wipe):
"""wipe using nice \"blob\"-like patterns"""
def __init__(self):
self.uscale = (5.0 + random.random() * 15.0) * 1.333
self.vscale = 5.0 + random.random() * 15.0
self.uofs = random.random() * 6.2
self.vofs = random.random() * 6.2
def grad(self,u,v):
return 0.5 + 0.25 * (cos(self.uofs + u * self.uscale) \
+ cos(self.vofs + v * self.vscale))
AllTransitions.append(WipeBlobs)
class PagePeel(Transition):
"""an unrealistic, but nice page peel effect"""
def render(self,t):
glDisable(GL_BLEND)
glBindTexture(TextureTarget, Tnext)
DrawMeshQuad(t, lambda t, u, v: \
(u, v, 0.0, u, v, 1.0 - 0.5 * (1.0 - u) * (1.0 - t), 1.0))
EnableAlphaBlend()
glBindTexture(TextureTarget, Tcurrent)
DrawMeshQuad(t, lambda t, u, v: \
(u * (1.0 - t), 0.5 + (v - 0.5) * (1.0 + u * t) * (1.0 + u * t), 0.0,
u, v, 1.0 - u * t * t, 1.0))
AllTransitions.append(PagePeel)
### additional transition by Ronan Le Hy <[email protected]> ###
class PageTurn(Transition):
"""another page peel effect, slower but more realistic than PagePeel"""
alpha = 2.
alpha_square = alpha * alpha
sqrt_two = sqrt(2.)
inv_sqrt_two = 1. / sqrt(2.)
def warp(self, t, u, v):
# distance from the 2d origin to the folding line
dpt = PageTurn.sqrt_two * (1.0 - t)
# distance from the 2d origin to the projection of (u,v) on the folding line
d = PageTurn.inv_sqrt_two * (u + v)
dmdpt = d - dpt
# the smaller rho is, the closer to asymptotes are the x(u) and y(v) curves
# ie, smaller rho => neater fold
rho = 0.001
common_sq = sqrt(4. - 8 * t - 4.*(u+v) + 4.*t*(t + v + u) + (u+v)*(u+v) + 4 * rho) / 2.
x = 1. - t + 0.5 * (u - v) - common_sq
y = 1. - t + 0.5 * (v - u) - common_sq
z = - 0.5 * (PageTurn.alpha * dmdpt + sqrt(PageTurn.alpha_square * dmdpt*dmdpt + 4))
if dmdpt < 0:
# part of the sheet still flat on the screen: lit and opaque
i = 1.0
alpha = 1.0
else:
# part of the sheet in the air, after the fold: shadowed and transparent
# z goes from -0.8 to -2 approximately
i = -0.5 * z
alpha = 0.5 * z + 1.5
# the corner of the page that you hold between your fingers
dthumb = 0.6 * u + 1.4 * v - 2 * 0.95
if dthumb > 0:
z -= dthumb
x += dthumb
y += dthumb
i = 1.0
alpha = 1.0
return (x,y,z, u,v, i, alpha)
def render(self, t):
glDisable(GL_BLEND)
glBindTexture(TextureTarget, Tnext)
DrawMeshQuad(t,lambda t, u, v: \
(u, v, 0.0, u, v, 1.0 - 0.5 * (1.0 - u) * (1.0 - t), 1.0))
EnableAlphaBlend()
glBindTexture(TextureTarget, Tcurrent)
DrawMeshQuad(t, self.warp)
AllTransitions.append(PageTurn)
##### some additional transitions by Rob Reid <[email protected]> #####
class ZoomOutIn(Transition):
"""zooms the current page out, and the next one in."""
def render(self, t):
glColor3d(0.0, 0.0, 0.0)
DrawFullQuad()
if t < 0.5:
glBindTexture(TextureTarget, Tcurrent)
scalfact = 1.0 - 2.0 * t
DrawMeshQuad(t, lambda t, u, v: (0.5 + scalfact * (u - 0.5), \
0.5 + scalfact * (v - 0.5), 0.0, \
u, v, 1.0, 1.0))
else:
glBindTexture(TextureTarget, Tnext)
scalfact = 2.0 * t - 1.0
EnableAlphaBlend()
DrawMeshQuad(t, lambda t, u, v: (0.5 + scalfact * (u - 0.5), \
0.5 + scalfact * (v - 0.5), 0.0, \
u, v, 1.0, 1.0))
AllTransitions.append(ZoomOutIn)
class SpinOutIn(Transition):
"""spins the current page out, and the next one in."""
def render(self, t):
glColor3d(0.0, 0.0, 0.0)
DrawFullQuad()
if t < 0.5:
glBindTexture(TextureTarget, Tcurrent)
scalfact = 1.0 - 2.0 * t
else:
glBindTexture(TextureTarget, Tnext)
scalfact = 2.0 * t - 1.0
sa = scalfact * sin(16.0 * t)
ca = scalfact * cos(16.0 * t)
DrawMeshQuad(t,lambda t, u, v: (0.5 + ca * (u - 0.5) - 0.75 * sa * (v - 0.5),\
0.5 + 1.333 * sa * (u - 0.5) + ca * (v - 0.5),\
0.0, u, v, 1.0, 1.0))
AllTransitions.append(SpinOutIn)
class SpiralOutIn(Transition):
"""flushes the current page away to have the next one overflow"""
def render(self, t):
glColor3d(0.0, 0.0, 0.0)
DrawFullQuad()
if t < 0.5:
glBindTexture(TextureTarget,Tcurrent)
scalfact = 1.0 - 2.0 * t
else:
glBindTexture(TextureTarget,Tnext)
scalfact = 2.0 * t - 1.0
sa = scalfact * sin(16.0 * t)
ca = scalfact * cos(16.0 * t)
DrawMeshQuad(t, lambda t, u, v: (0.5 + sa + ca * (u - 0.5) - 0.75 * sa * (v - 0.5),\
0.5 + ca + 1.333 * sa * (u - 0.5) + ca * (v - 0.5),\
0.0, u, v, 1.0, 1.0))
AllTransitions.append(SpiralOutIn)
# the AvailableTransitions array contains a list of all transition classes that
# can be randomly assigned to pages
AvailableTransitions=[ # from coolest to lamest
# PagePeel, # deactivated: too intrusive
# WipeBlobs,
# WipeCenterOut,WipeCenterIn,
# WipeDownRight,WipeUpLeft,WipeDown,WipeUp,WipeRight,WipeLeft,
Crossfade
]
##### OSD FONT RENDERER ########################################################
# force a string or sequence of ordinals into a unicode string
def ForceUnicode(s, charset='iso8859-15'):
if type(s) == types.UnicodeType:
return s
if type(s) == types.StringType:
return unicode(s, charset, 'ignore')
if type(s) in (types.TupleType, types.ListType):
return u''.join(map(unichr, s))
raise TypeError, "string argument not convertible to Unicode"
# search a system font path for a font file
def SearchFont(root, name):
if not os.path.isdir(root):
return None
infix = ""
fontfile = []
while (len(infix) < 10) and (len(fontfile) != 1):
fontfile = filter(os.path.isfile, glob.glob(root + infix + name))
infix += "*/"
if len(fontfile) != 1: