forked from tonioo/rst2pdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·1249 lines (1048 loc) · 43.1 KB
/
main.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: utf-8 -*-
"""The user interface for our app"""
import os,sys,tempfile,re,functools,time,types,glob,codecs
from pprint import pprint
from copy import copy
from multiprocessing import Process, Queue
from Queue import Empty
from hashlib import md5
from StringIO import StringIO
from rst2pdf.createpdf import RstToPdf
from rst2pdf.styles import StyleSheet
from rst2pdf.log import log
import logging
import reportlab.lib.pagesizes as pagesizes
log.setLevel(logging.INFO)
import docutils
# Import Qt modules
from PyQt4 import QtCore,QtGui
from pypoppler import QtPoppler
# Syntax HL
from highlighter import Highlighter
# Import the compiled UI module
from Ui_main import Ui_MainWindow
from Ui_pdf import Ui_Form
try:
import json
except ImportError:
import simplejson as json
try:
from lxml import etree
print("running with lxml.etree")
except ImportError:
try:
# Python 2.5
import xml.etree.cElementTree as etree
print("running with cElementTree on Python 2.5+")
except ImportError:
try:
# Python 2.5
import xml.etree.ElementTree as etree
print("running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree
print("running with cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree
print("running with ElementTree")
except ImportError:
print("Failed to import ElementTree from any known place")
from pygments import highlight
from pygments.lexers import *
from pygments.formatters import HtmlFormatter
StringTypes=types.StringTypes+(QtCore.QString,)
def renderQueue(render_queue, pdf_queue, doctree_queue):
_renderer = RstToPdf(splittables=True)
def render(doctree, preview=True):
'''Render text to PDF via rst2pdf'''
# FIXME: get parameters for this from somewhere
sio=StringIO()
_renderer.createPdf(doctree=doctree, output=sio, debugLinesPdf=preview)
return sio.getvalue()
while True:
try:
style_file, text, preview = render_queue.get(10)
style_file, text, preview = render_queue.get(False)
except Empty: # no more things to render, so do it
try:
if style_file:
_renderer.loadStyles([style_file])
flag = True
#os.unlink(style_file)
warnings=StringIO()
doctree = docutils.core.publish_doctree(text,
settings_overrides={'warning_stream':warnings})
doctree_queue.put([doctree,warnings.getvalue()])
pdf_queue.put(render(doctree, preview))
except Exception, e:
# Don't crash ever ;-)
print e
pass
if os.getppid()==1: # Parent died
sys.exit(0)
class Main(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.doctree=None
self.lineMarks={}
# We put things we want rendered here
self.render_queue = Queue()
# We get things rendered back
self.pdf_queue = Queue()
# We get doctrees for the outline viewer
self.doctree_queue = Queue()
print 'Starting background renderer...',
self.renderProcess=Process(target = renderQueue,
args=(self.render_queue, self.pdf_queue, self.doctree_queue))
self.renderProcess.daemon=True
self.renderProcess.start()
print 'DONE'
# This is always the same
self.ui=Ui_MainWindow()
self.ui.setupUi(self)
# Adjust column widths in the structure tree
self.ui.tree.header().setStretchLastSection(False)
self.ui.tree.header().setResizeMode(0, QtGui.QHeaderView.Stretch)
self.ui.tree.header().setResizeMode(1, QtGui.QHeaderView.ResizeToContents)
self.pdf=PDFWidget()
self.ui.pageNum = QtGui.QSpinBox()
self.ui.pageNum.setMinimum(1)
self.ui.pageNum.setValue(1)
self.connect(self.pdf,QtCore.SIGNAL('pageCount'),
self.ui.pageNum.setMaximum)
self.connect(self.pdf,QtCore.SIGNAL('pageChanged'),
self.ui.pageNum.setValue)
self.connect(self.ui.pageNum,QtCore.SIGNAL('valueChanged(int)'),
self.pdf.gotoPage)
self.ui.actionShow_ToolBar=self.ui.toolBar.toggleViewAction()
self.ui.actionShow_ToolBar.setText("Show Main Toolbar")
self.ui.menuView.addAction(self.ui.actionShow_ToolBar)
self.ui.pdfbar.addAction(self.pdf.ui.previous)
self.ui.pdfbar.addWidget(self.ui.pageNum)
self.ui.pdfbar.addAction(self.pdf.ui.next)
self.ui.pdfbar.addSeparator()
self.ui.pdfbar.addAction(self.pdf.ui.zoomin)
self.ui.pdfbar.addAction(self.pdf.ui.zoomout)
self.ui.actionShow_PDFBar=self.ui.pdfbar.toggleViewAction()
self.ui.actionShow_PDFBar.setText("Show PDF Toolbar")
self.ui.menuView.addAction(self.ui.actionShow_PDFBar)
self.ui.dockLayout.addWidget(self.ui.pdfbar)
self.ui.dockLayout.addWidget(self.pdf)
self.ui.dock.hide()
self.ui.actionShow_PDF=self.ui.dock.toggleViewAction()
self.ui.actionShow_PDF.setText('Show Preview')
self.ui.menuView.addAction(self.ui.actionShow_PDF)
self.ui.actionShow_Structure=self.ui.structure.toggleViewAction()
self.ui.actionShow_Structure.setText('Show Document Outline')
self.ui.menuView.addAction(self.ui.actionShow_Structure)
self.text_md5=''
self.style_md5=''
self.hl1 = Highlighter(self.ui.text.document(),'rest')
self.hl2 = Highlighter(self.ui.style.document(),'javascript')
self.editorPos=QtGui.QLabel()
self.ui.statusBar.addWidget(self.editorPos)
self.editorPos.show()
self.statusMessage=QtGui.QLabel()
self.ui.statusBar.addWidget(self.statusMessage)
self.statusMessage.show()
self.on_text_cursorPositionChanged()
self.on_actionRender_triggered()
# Connect editing actions to the editors
self.ui.text.undoAvailable.connect(self.ui.actionUndo1.setEnabled)
self.ui.actionUndo1.triggered.connect(self.ui.text.undo)
self.ui.text.redoAvailable.connect(self.ui.actionRedo1.setEnabled)
self.ui.actionRedo1.triggered.connect(self.ui.text.redo)
self.ui.text.copyAvailable.connect(self.ui.actionCopy1.setEnabled)
self.ui.actionCopy1.triggered.connect(self.ui.text.copy)
self.ui.text.copyAvailable.connect(self.ui.actionCut1.setEnabled)
self.ui.actionCut1.triggered.connect(self.ui.text.cut)
self.ui.actionPaste1.triggered.connect(self.ui.text.paste)
self.ui.style.undoAvailable.connect(self.ui.actionUndo2.setEnabled)
self.ui.actionUndo2.triggered.connect(self.ui.style.undo)
self.ui.style.redoAvailable.connect(self.ui.actionRedo2.setEnabled)
self.ui.actionRedo2.triggered.connect(self.ui.style.redo)
self.ui.style.copyAvailable.connect(self.ui.actionCopy2.setEnabled)
self.ui.actionCopy2.triggered.connect(self.ui.style.copy)
self.ui.style.copyAvailable.connect(self.ui.actionCut2.setEnabled)
self.ui.actionCut2.triggered.connect(self.ui.style.cut)
self.ui.actionPaste2.triggered.connect(self.ui.style.paste)
self.clipBoard=QtGui.QApplication.clipboard()
self.clipBoard.changed.connect(self.clipChanged)
self.hookEditToolbar(self.ui.text)
self.clipChanged(QtGui.QClipboard.Clipboard)
self.text_fname=None
self.style_fname=None
self.pdf_fname=None
self.ui.searchbar.setVisible(False)
self.ui.searchWidget=SearchWidget()
self.ui.searchbar.addWidget(self.ui.searchWidget)
self.ui.actionFind.triggered.connect(self.ui.searchbar.show)
self.ui.actionFind.triggered.connect(self.ui.searchWidget.ui.text.setFocus)
self.ui.searchWidget.ui.close.clicked.connect(self.ui.searchbar.hide)
self.ui.searchWidget.ui.close.clicked.connect(self.returnFocus)
self.ui.searchWidget.ui.next.clicked.connect(self.doFind)
self.ui.searchWidget.ui.previous.clicked.connect(self.doFindBackwards)
self.updatePdf()
self.renderTimer=QtCore.QTimer()
self.renderTimer.timeout.connect(self.on_actionRender_triggered)
self.renderTimer.start(5000)
def returnFocus(self):
"""after the search bar closes, focus on the editing widget"""
print 'RF:', self.ui.tabs.currentIndex()
if self.ui.tabs.currentIndex()==0:
self.ui.text.setFocus()
else:
self.ui.style.setFocus()
def doFindBackwards (self):
return self.doFind(backwards=True)
def doFind(self, backwards=False):
flags=QtGui.QTextDocument.FindFlags()
print flags
if backwards:
flags=QtGui.QTextDocument.FindBackward
if self.ui.searchWidget.ui.matchCase.isChecked():
flags=flags|QtGui.QTextDocument.FindCaseSensitively
text=unicode(self.ui.searchWidget.ui.text.text())
print 'Serching for:',text
if self.ui.tabs.currentIndex()==0:
r=self.ui.text.find(text,flags)
else:
r=self.ui.style.find(text,flags)
if r:
self.statusMessage.setText('')
else:
self.statusMessage.setText('%s not found'%text)
def clipChanged(self, mode=None):
if mode is None: return
if mode == QtGui.QClipboard.Clipboard:
if unicode(self.clipBoard.text()):
self.ui.actionPaste1.setEnabled(True)
self.ui.actionPaste2.setEnabled(True)
else:
self.ui.actionPaste1.setEnabled(False)
self.ui.actionPaste2.setEnabled(False)
def hookEditToolbar(self, editor):
if editor == self.ui.text:
self.ui.actionUndo2.setVisible(False)
self.ui.actionRedo2.setVisible(False)
self.ui.actionCut2.setVisible(False)
self.ui.actionPaste2.setVisible(False)
self.ui.actionCopy2.setVisible(False)
self.ui.actionUndo1.setVisible(True)
self.ui.actionRedo1.setVisible(True)
self.ui.actionCut1.setVisible(True)
self.ui.actionPaste1.setVisible(True)
self.ui.actionCopy1.setVisible(True)
else:
self.ui.actionUndo1.setVisible(False)
self.ui.actionRedo1.setVisible(False)
self.ui.actionCut1.setVisible(False)
self.ui.actionPaste1.setVisible(False)
self.ui.actionCopy1.setVisible(False)
self.ui.actionUndo2.setVisible(True)
self.ui.actionRedo2.setVisible(True)
self.ui.actionCut2.setVisible(True)
self.ui.actionPaste2.setVisible(True)
self.ui.actionCopy2.setVisible(True)
def createPopupMenu(self):
self.popup=QtGui.QMenu()
self.popup.addAction(self.ui.actionShow_ToolBar)
self.popup.addAction(self.ui.actionShow_PDFBar)
self.popup.addAction(self.ui.actionShow_PDF)
return self.popup
def enableHL(self):
self.hl1.enabled=True
self.hl2.enabled=True
self.hl1.rehighlight()
self.hl2.rehighlight()
def disableHL(self):
self.hl1.enabled=False
self.hl2.enabled=False
def on_actionSettings_triggered(self, b=None):
if b is not None: return
# I need to create a stylesheet object so I can parse and merge
# the current stylesheet
try:
data=json.loads(unicode(self.ui.style.toPlainText()))
except: # TODO: fail if sheet doesn't validate
data={}
config=ConfigDialog(data=copy(data))
config.exec_()
# merge the edited stylesheet with current one because the editor
# is not complete yet. When it is, just replace it.
data.update(config.data)
self.ui.style.setPlainText(json.dumps(data, indent=2))
def on_actionTest_Action_triggered(self, b=None):
if b is not None: return
self.testwidget=PageTemplates(self.styles)
self.testwidget.show()
def on_tree_itemClicked(self, item=None, column=None):
if item is None: return
destline=int(item.text(1))-1
destblock=self.ui.text.document().findBlockByLineNumber(destline)
cursor=self.ui.text.textCursor()
cursor.setPosition(destblock.position())
self.ui.text.setTextCursor(cursor)
self.ui.text.ensureCursorVisible()
def on_actionAbout_Bookrest_triggered(self, b=None):
if b is None: return
dlg=AboutDialog()
dlg.exec_()
def on_actionSave_Text_triggered(self, b=None):
if b is not None: return
if self.text_fname is not None:
f=codecs.open(self.text_fname,'w+','utf-8')
f.seek(0)
f.write(unicode(self.ui.text.toPlainText()))
f.close()
else:
self.on_actionSaveAs_Text_triggered()
def on_actionSaveAs_Text_triggered(self, b=None):
if b is not None: return
fname=unicode(QtGui.QFileDialog.getSaveFileName(self,
'Save As',
os.getcwd(),
'reSt files (*.txt *.rst)'
))
if fname:
self.text_fname=fname
self.on_actionSave_Text_triggered()
def on_actionLoad_Text_triggered(self, b=None):
if b is None: return
fname=QtGui.QFileDialog.getOpenFileName(self,
'Open File',
os.getcwd(),
'reSt files (*.txt *.rst)'
)
self.text_fname=fname
self.disableHL()
self.ui.text.setPlainText(codecs.open(self.text_fname,'r','utf-8').read())
self.enableHL()
def on_actionSave_Style_triggered(self, b=None):
if b is not None: return
if self.style_fname is not None:
f=codecs.open(self.style_fname,'w+','utf-8')
f.seek(0)
f.write(unicode(self.ui.style.toPlainText()))
f.close()
else:
self.on_actionSaveAs_Style_triggered()
def on_actionSaveAs_Style_triggered(self, b=None):
if b is not None: return
fname=unicode(QtGui.QFileDialog.getSaveFileName(self,
'Save As',
os.getcwd(),
'style files (*.json *.style)'
))
if fname:
self.style_fname=fname
self.on_actionSave_Style_triggered()
def on_actionLoad_Style_triggered(self, b=None):
if b is None: return
fname=QtGui.QFileDialog.getOpenFileName(self,
'Open File',
os.getcwd(),
'style files (*.json *.style)'
)
self.style_fname=fname
self.disableHL()
self.ui.style.setPlainText(codecs.open(self.style_fname,'rb', 'utf-8').read())
self.enableHL()
def on_actionSave_PDF_triggered(self, b=None):
if b is not None: return
# render it without line numbers in the toc
self.on_actionRender_triggered(preview=False)
if self.pdf_fname is not None:
f=open(self.pdf_fname,'wb+')
f.seek(0)
f.write(self.goodPDF)
f.close()
else:
self.on_actionSaveAs_PDF_triggered()
def on_actionSaveAs_PDF_triggered(self, b=None):
if b is not None: return
fname=unicode(QtGui.QFileDialog.getSaveFileName(self,
'Save As',
os.getcwd(),
'PDF files (*.pdf)'
))
if fname:
self.pdf_fname=fname
self.on_actionSave_PDF_triggered()
def on_tabs_currentChanged(self, i=None):
print 'IDX:',self.ui.tabs.currentIndex()
if self.ui.tabs.currentIndex() == 0:
self.on_text_cursorPositionChanged()
print 'hooking text editor'
self.hookEditToolbar(self.ui.text)
else:
self.on_style_cursorPositionChanged()
print 'hooking style editor'
self.hookEditToolbar(self.ui.style)
def on_style_cursorPositionChanged(self):
cursor=self.ui.style.textCursor()
self.editorPos.setText('Line: %d Col: %d'%(cursor.blockNumber(),cursor.columnNumber()))
def on_text_cursorPositionChanged(self):
cursor=self.ui.text.textCursor()
row=cursor.blockNumber()
column=cursor.columnNumber()
self.editorPos.setText('Line: %d Col: %d'%(row,column))
l='line-%s'%(row+1)
m=self.lineMarks.get(l,None)
if m:
self.pdf.gotoPosition(*m)
def validateStyle(self):
style=unicode(self.ui.style.toPlainText())
if not style.strip(): #no point in validating an empty string
self.statusMessage.setText('')
return
pos=None
try:
json.loads(style)
self.statusMessage.setText('')
except ValueError, e:
s=str(e)
if s == 'No JSON object could be decoded':
pos=0
elif s.startswith('Expecting '):
pos=int(s.split(' ')[-1][:-1])
elif s.startswith('Extra data'):
pos=int(s.split(' ')[-3])
else:
pass
self.statusMessage.setText('Stylesheet error: %s'%s)
# This makes a red bar appear in the line
# containing position pos
self.ui.style.highlightError(pos)
on_style_textChanged = validateStyle
def on_actionRender_triggered(self, b=None, preview=True):
if b is not None: return
text=unicode(self.ui.text.toPlainText())
style=unicode(self.ui.style.toPlainText())
self.hl1.rehighlight()
m1=md5()
m1.update(text.encode('utf-8'))
m1=m1.digest()
m2=md5()
m2.update(style.encode('utf-8'))
m2=m2.digest()
flag = m1 != self.text_md5
style_file=None
if m2 != self.style_md5 and style:
fd, style_file=tempfile.mkstemp()
os.write(fd,style)
os.close(fd)
print 'Loading styles from style_file'
flag = True
if flag:
if not preview:
pass
# Send text to the renderer in foreground
# FIXME: render is no longer accessible from the parent
# process
#doctree = docutils.core.publish_doctree(text)
#self.goodPDF=render(doctree, preview=False)
else:
# Que to render in background
self.render_queue.put([style_file, text, preview])
self.text_md5=m1
self.style_md5=m2
def updatePdf(self):
# See if there is something in the doctree Queue
try:
self.doctree, self.warnings = self.doctree_queue.get(False)
self.doctree.reporter=log
class Visitor(docutils.nodes.SparseNodeVisitor):
def __init__(self, document, treeWidget):
self.treeWidget=treeWidget
self.treeWidget.clear()
self.doctree=document
self.nodeDict={}
docutils.nodes.SparseNodeVisitor.__init__(self, document)
def visit_section(self, node):
print 'SECTION:',node.line,
item=QtGui.QTreeWidgetItem(["",str(node.line)])
if node.parent==self.doctree:
# Top level section
self.treeWidget.addTopLevelItem(item)
self.nodeDict[id(node)]=item
else:
self.nodeDict[id(node.parent)].addChild(item)
self.nodeDict[id(node)]=item
def visit_title(self, node):
if id(node.parent) in self.nodeDict:
self.nodeDict[id(node.parent)].setText(0,node.astext())
def visit_document(self,node):
print 'DOC:',node.line
print self.doctree.__class__
self.visitor=Visitor(self.doctree, self.ui.tree)
self.doctree.walkabout(self.visitor)
print self.visitor.nodeDict
except Empty:
pass
# See if there is something in the PDF Queue
try:
self.lastPDF=self.pdf_queue.get(False)
self.pdf.loadDocument(self.lastPDF)
toc=self.pdf.document.toc()
if toc:
tempMarks=[]
def traverse(node):
children=node.childNodes()
for i in range(children.length()):
n=children.item(i)
e=n.toElement()
if e:
tag=str(e.tagName())
if tag.startswith('LINE'):
dest=str(e.attribute('Destination'))
dest=QtPoppler.Poppler.LinkDestination(dest)
tempMarks.append([int(tag.split('-')[1]),
[dest.pageNumber(), dest.top(), dest.left(),1.]])
traverse(n)
traverse(toc)
tempMarks.sort()
self.lineMarks={}
lastMark=None
lastKey=0
for key,dest in tempMarks:
# Fix height of the previous mark, unless we changed pages
if lastMark and self.lineMarks[lastMark][0]==dest[0]:
self.lineMarks[lastMark][3]=dest[1]
# Fill missing lines
if lastMark:
ldest=self.lineMarks[lastMark]
else:
ldest=[1,0,0,0]
for n in range(lastKey,key):
self.lineMarks['line-%s'%n]=ldest
k='line-%s'%key
self.lineMarks[k]=dest
lastMark = k
lastKey = key
self.on_text_cursorPositionChanged()
except Empty: #Nothing there
pass
# Schedule to run again
QtCore.QTimer.singleShot(500,self.updatePdf)
def main():
# Again, this is boilerplate, it's going to be the same on
# almost every app you write
app = QtGui.QApplication(sys.argv)
window=Main()
window.show()
# It's exec_ because exec is a reserved word in Python
sys.exit(app.exec_())
class PDFWidget(QtGui.QWidget):
def __init__(self,parent=None):
QtGui.QWidget.__init__(self,parent)
self.ui=Ui_Form()
self.ui.setupUi(self)
self.pdfd = None
def loadDocument(self,data):
self.document = QtPoppler.Poppler.Document.loadFromData(data)
self.emit(QtCore.SIGNAL('pageCount'),self.document.numPages())
self.document.setRenderHint(QtPoppler.Poppler.Document.Antialiasing and QtPoppler.Poppler.Document.TextAntialiasing)
# When rerendering, keep state as much as possible in
# the viewer
if self.pdfd:
res = self.pdfd.res
xpos = self.ui.scroll.horizontalScrollBar().value()
ypos = self.ui.scroll.verticalScrollBar().value()
currentPage = self.pdfd.currentPage
else:
res=72.
xpos=0
ypos=0
currentPage = 0
self.pdfd=PDFDisplay(self.document)
self.connect(self.pdfd,QtCore.SIGNAL('pageChanged'),
self,QtCore.SIGNAL('pageChanged'))
self.pdfd.currentPage = currentPage
self.checkActions()
self.pdfd.res = res
self.ui.scroll.setWidget(self.pdfd)
self.ui.scroll.horizontalScrollBar().setValue(xpos)
self.ui.scroll.verticalScrollBar().setValue(ypos)
def checkActions(self):
if not self.pdfd or \
self.pdfd.currentPage == self.document.numPages():
self.ui.next.setEnabled(False)
else:
self.ui.next.setEnabled(True)
if not self.pdfd or \
self.pdfd.currentPage == 1:
self.ui.previous.setEnabled(False)
else:
self.ui.previous.setEnabled(True)
def gotoPosition(self, page, top, left, bottom):
"""The position is defined in terms of poppler's linkdestinations,
top is in the range 0-1, page is one-based."""
if not self.pdfd:
return
self.gotoPage(page)
# Draw a mark to see if we are calculating correctly
pixmap=QtGui.QPixmap(self.pdfd.pdfImage)
p=QtGui.QPainter(pixmap)
c=QtGui.QColor(QtCore.Qt.yellow).lighter(160)
c.setAlpha(150)
p.setBrush(c)
p.setPen(c)
# FIXME, move the highlighting outside
y1=self.pdfd.pdfImage.height()*top
y2=self.pdfd.pdfImage.height()*(bottom-top)
w=self.pdfd.pdfImage.width()
p.drawRect(0,y1,w,y2)
self.pdfd.setPixmap(pixmap)
p.end()
def gotoPage(self,n):
if self.pdfd:
self.pdfd.currentPage = n
self.checkActions()
def on_next_triggered(self, b=None):
if b is None: return
self.pdfd.nextPage()
self.checkActions()
def on_previous_triggered(self, b=None):
if b is None: return
self.pdfd.prevPage()
self.checkActions()
def on_zoomin_triggered(self, b=None):
if b is None: return
self.pdfd.zoomin()
def on_zoomout_triggered(self, b=None):
if b is None: return
self.pdfd.zoomout()
class PDFDisplay(QtGui.QLabel):
def __init__(self, doc):
QtGui.QLabel.__init__(self, None)
self.doc = doc
self.pdfImage = None
self._res = self.physicalDpiX()
self._currentPage = 1
self.display()
@property
def currentPage(self):
'''The currently displayed page'''
return self._currentPage
@currentPage.setter
def currentPage(self,value):
value=int(value)
if value != self._currentPage and \
0 < value <= self.doc.numPages():
self._currentPage = value
self.display()
self.emit(QtCore.SIGNAL('pageChanged'),self._currentPage)
# Just so I can connect a signal to this
def setCurrentPage(self,value):
self.currentPage=value
def nextPage(self):
self.currentPage += 1
def prevPage(self):
self.currentPage -= 1
@property
def res(self):
'''Display resolution in DPI'''
return self._res
@res.setter
def res(self,value):
self._res=value
self.display()
def zoomin(self):
self.res=self.res*1.25
def zoomout(self):
self.res=self.res/1.25
def display(self):
if self.doc is not None:
if self.doc.numPages() == 0:
self.pdfImage = QtGui.QImage()
else:
page = self.doc.page(self.currentPage-1)
if page:
self.pdfImage = None
self.pdfImage = page.renderToImage(self.res, self.res)
self.resize(self.pdfImage.width(),self.pdfImage.height())
self.setPixmap(QtGui.QPixmap.fromImage(self.pdfImage))
#self.update()
#delete page;
# Firefox-style in-window search widget,
# copied from uRSSus: http://urssus.googlecode.com
from Ui_searchwidget import Ui_Form as UI_SearchWidget
class SearchWidget(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
# Set up the UI from designer
self.ui=UI_SearchWidget()
self.ui.setupUi(self)
# Cute about dialog
from Ui_about import Ui_Dialog as Ui_AboutDialog
class AboutDialog(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
# Set up the UI from designer
self.ui=Ui_AboutDialog()
self.ui.setupUi(self)
# Configuration dialog
from Ui_configdialog import Ui_Dialog as Ui_ConfigDialog
class ConfigDialog(QtGui.QDialog):
def __init__(self, data={}):
QtGui.QDialog.__init__(self)
# Set up the UI from designer
self.ui=Ui_ConfigDialog()
self.ui.setupUi(self)
self.curPageWidget=None
self.scale=.3
self.data=data
# Load all config things
self.pages={
'Stylesheets':StyleSheets,
'Page Setup':PageSetup,
'Page Templates':PageTemplates,
}
keys=self.pages.keys()
keys.sort()
for page in keys:
self.ui.pagelist.addItem(page)
def on_pagelist_currentTextChanged(self, text=None):
if text is None: return
fd, style_file=tempfile.mkstemp()
os.write(fd,json.dumps(self.data))
os.close(fd)
self.styles = StyleSheet([style_file])
os.unlink(style_file)
text=unicode(text)
if self.curPageWidget:
self.curPageWidget.hide()
self.curPageWidget.deleteLater()
widget=self.pages[text]
self.curPageWidget=widget(self.styles,
self.data,
self.ui.preview,
self.ui.snippet)
self.ui.layout.addWidget(self.curPageWidget)
self.curPageWidget.show()
self.curPageWidget.updatePreview()
def on_zoomin_clicked(self):
self.scale=self.scale*1.25
if self.curPageWidget:
self.curPageWidget.scale=self.scale
self.curPageWidget.updatePreview()
def on_zoomout_clicked(self):
self.scale=self.scale/1.25
if self.curPageWidget:
self.curPageWidget.scale=self.scale
self.curPageWidget.updatePreview()
# Widget to edit page templates
from Ui_pagetemplates import Ui_Form as Ui_templates
class PageTemplates(QtGui.QWidget):
def __init__(self, stylesheet, data, preview, snippet, parent=None):
QtGui.QWidget.__init__(self,parent)
self.scale = .3
self.data = data
self.ui=Ui_templates()
self.ui.setupUi(self)
self.ui.preview = preview
self.ui.snippet = snippet
self.stylesheet = stylesheet
self.pw=self.stylesheet.ps[0]
self.ph=self.stylesheet.ps[1]
self.pageImage=QtGui.QImage(int(self.pw),
int(self.ph),
QtGui.QImage.Format_RGB32)
self.templates = copy(self.stylesheet.pageTemplates)
self.template = None
for template in self.templates:
self.ui.templates.addItem(template)
def applyChanges(self):
# TODO: validate everything
self.frame=[unicode(w.text()) for w in [
self.ui.left,
self.ui.top,
self.ui.width,
self.ui.height
]]
self.template["frames"][self.frameIndex]=self.frame
self.template['showFooter']=self.ui.footer.isChecked()
self.template['showHeader']=self.ui.header.isChecked()
if unicode(self.ui.background.text()):
self.template['background']=unicode(self.ui.background.text())
self.updatePreview()
def on_templates_currentIndexChanged(self, text):
if not isinstance(text,StringTypes): return
text=unicode(text)
self.template=self.templates[text]
self.ui.frames.clear()
for i in range(0, len(self.template['frames'])):
self.ui.frames.addItem('Frame %d'%(i+1))
self.ui.footer.setChecked(self.template['showFooter'])
self.ui.header.setChecked(self.template['showHeader'])
self.ui.background.setText(self.template.get("background",""))
self.updatePreview()
def on_frames_currentIndexChanged(self, index):
if type(index) != types.IntType: return
if not self.template: return
self.frameIndex=index
self.frame=self.template['frames'][index]
self.ui.left.setText(self.frame[0])
self.ui.top.setText(self.frame[1])
self.ui.width.setText(self.frame[2])
self.ui.height.setText(self.frame[3])
self.updatePreview()
def on_selectFile_clicked(self,b=None):
if b is not None: return
fname=QtGui.QFileDialog.getOpenFileName(self,
'Open Background Image',
os.getcwd()
)
self.ui.background.setText(fname)
self.applyChanges()
def updatePreview(self):
pm=QtGui.QPixmap(self.pageImage)
p=QtGui.QPainter(pm)
# Draw white page
p.setBrush(QtGui.QBrush(QtGui.QColor("white")))
p.drawRect(-1,-1,pm.width()+2,pm.height()+2)
pen = QtGui.QPen()
pen.setWidth(1/self.scale) # Make it be 1px wide when scaled
p.setPen(pen)
# Draw background
bg=self.template.get("background",None)
if bg:
bg=QtGui.QImageReader(bg,)
bg.setScaledSize(QtCore.QSize(pm.width(),pm.height()))
p.drawImage(QtCore.QPoint(0,0),bg.read())
x1=self.stylesheet.lm
y1=self.stylesheet.tm
tw=self.stylesheet.pw-self.stylesheet.lm-self.stylesheet.rm
th=self.stylesheet.ph-self.stylesheet.bm-self.stylesheet.tm
def drawFrame(frame):
x=self.stylesheet.adjustUnits(frame[0],tw)
y=self.stylesheet.adjustUnits(frame[1],th)
w=self.stylesheet.adjustUnits(frame[2],tw)-1
h=self.stylesheet.adjustUnits(frame[3],th)-1
p.drawRect(x1+x,y1+y,w,h)