-
-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathtoodt.py
1627 lines (1333 loc) · 57.3 KB
/
toodt.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
"""
novelWriter – ODT Text Converter
================================
File History:
Created: 2021-01-26 [1.2b1] ToOdt
Created: 2021-01-27 [1.2b1] ODTParagraphStyle
Created: 2021-01-27 [1.2b1] ODTTextStyle
Created: 2021-08-14 [1.5b1] XMLParagraph
This file is a part of novelWriter
Copyright 2018–2024, Veronica Berglyd Olsen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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, see <https://www.gnu.org/licenses/>.
"""
from __future__ import annotations
import logging
import xml.etree.ElementTree as ET
from hashlib import sha256
from pathlib import Path
from zipfile import ZipFile
from datetime import datetime
from collections.abc import Sequence
from novelwriter import __version__
from novelwriter.common import xmlIndent
from novelwriter.constants import nwHeadFmt, nwKeyWords, nwLabels
from novelwriter.core.project import NWProject
from novelwriter.core.tokenizer import Tokenizer, stripEscape
logger = logging.getLogger(__name__)
# Main XML NameSpaces
XML_NS = {
"manifest": "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0",
"office": "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
"style": "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
"loext": "urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0",
"text": "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
"meta": "urn:oasis:names:tc:opendocument:xmlns:meta:1.0",
"fo": "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
"dc": "http://purl.org/dc/elements/1.1/",
}
for ns, uri in XML_NS.items():
ET.register_namespace(ns, uri)
def _mkTag(ns: str, tag: str) -> str:
"""Assemble namespace and tag name."""
uri = XML_NS.get(ns, "")
if uri:
return f"{{{uri}}}{tag}"
logger.warning("Missing xml namespace '%s'", ns)
return tag
# Mimetype and Version
X_MIME = "application/vnd.oasis.opendocument.text"
X_VERS = "1.3"
# Text Formatting Tags
TAG_BR = _mkTag("text", "line-break")
TAG_SPC = _mkTag("text", "s")
TAG_NSPC = _mkTag("text", "c")
TAG_TAB = _mkTag("text", "tab")
TAG_SPAN = _mkTag("text", "span")
TAG_STNM = _mkTag("text", "style-name")
# Formatting Codes
X_BLD = 0x01 # Bold format
X_ITA = 0x02 # Italic format
X_DEL = 0x04 # Strikethrough format
X_UND = 0x08 # Underline format
X_MRK = 0x10 # Marked format
X_SUP = 0x20 # Superscript
X_SUB = 0x40 # Subscript
# Formatting Masks
M_BLD = ~X_BLD
M_ITA = ~X_ITA
M_DEL = ~X_DEL
M_UND = ~X_UND
M_MRK = ~X_MRK
M_SUP = ~X_SUP
M_SUB = ~X_SUB
class ToOdt(Tokenizer):
"""Core: Open Document Writer
Extend the Tokenizer class to writer Open Document files. The output
should conform to the 1.3 Extended standard.
Test with: https://odfvalidator.org/
"""
def __init__(self, project: NWProject, isFlat: bool) -> None:
super().__init__(project)
self._isFlat = isFlat # Flat: .fodt, otherwise .odt
self._dFlat = ET.Element("") # FODT file XML root
self._dCont = ET.Element("") # ODT content.xml root
self._dMeta = ET.Element("") # ODT meta.xml root
self._dStyl = ET.Element("") # ODT styles.xml root
self._xMeta = ET.Element("") # Office meta root
self._xFont = ET.Element("") # Office font face declaration
self._xFnt2 = ET.Element("") # Office font face declaration, secondary
self._xStyl = ET.Element("") # Office styles root
self._xAuto = ET.Element("") # Office auto-styles root
self._xAut2 = ET.Element("") # Office auto-styles root, secondary
self._xMast = ET.Element("") # Office master-styles root
self._xBody = ET.Element("") # Office body root
self._xText = ET.Element("") # Office text root
self._mainPara = {} # User-accessible paragraph styles
self._autoPara = {} # Auto-generated paragraph styles
self._autoText = {} # Auto-generated text styles
self._errData = [] # List of errors encountered
# Properties
self._textFont = "Liberation Serif"
self._textSize = 12
self._textFixed = False
self._colourHead = False
self._firstIndent = False
self._headerFormat = ""
self._pageOffset = 0
# Internal
self._fontFamily = "'Liberation Serif'"
self._fontPitch = "variable"
self._fSizeTitle = "30pt"
self._fSizeHead1 = "24pt"
self._fSizeHead2 = "20pt"
self._fSizeHead3 = "16pt"
self._fSizeHead4 = "14pt"
self._fSizeHead = "14pt"
self._fSizeText = "12pt"
self._fLineHeight = "115%"
self._fBlockIndent = "1.693cm"
self._fTextIndent = "0.499cm"
self._textAlign = "left"
self._dLanguage = "en"
self._dCountry = "GB"
# Text Margins
self._mTopTitle = "0.423cm"
self._mTopHead1 = "0.423cm"
self._mTopHead2 = "0.353cm"
self._mTopHead3 = "0.247cm"
self._mTopHead4 = "0.247cm"
self._mTopHead = "0.423cm"
self._mTopText = "0.000cm"
self._mTopMeta = "0.000cm"
self._mBotTitle = "0.212cm"
self._mBotHead1 = "0.212cm"
self._mBotHead2 = "0.212cm"
self._mBotHead3 = "0.212cm"
self._mBotHead4 = "0.212cm"
self._mBotHead = "0.212cm"
self._mBotText = "0.247cm"
self._mBotMeta = "0.106cm"
# Document Size and Margins
self._mDocWidth = "21.0cm"
self._mDocHeight = "29.7cm"
self._mDocTop = "2.000cm"
self._mDocBtm = "2.000cm"
self._mDocLeft = "2.000cm"
self._mDocRight = "2.000cm"
# Colour
self._colHead12 = None
self._opaHead12 = None
self._colHead34 = None
self._opaHead34 = None
self._colMetaTx = None
self._opaMetaTx = None
self._markText = "#ffffa6"
return
##
# Setters
##
def setLanguage(self, language: str | None) -> None:
"""Set language for the document."""
if language:
langBits = language.split("_")
self._dLanguage = langBits[0]
if len(langBits) > 1:
self._dCountry = langBits[1]
return
def setColourHeaders(self, state: bool) -> None:
"""Enable/disable coloured headings and comments."""
self._colourHead = state
return
def setPageLayout(
self, width: int | float, height: int | float,
top: int | float, bottom: int | float, left: int | float, right: int | float
) -> None:
"""Set the document page size and margins in millimetres."""
self._mDocWidth = f"{width/10.0:.3f}cm"
self._mDocHeight = f"{height/10.0:.3f}cm"
self._mDocTop = f"{top/10.0:.3f}cm"
self._mDocBtm = f"{bottom/10.0:.3f}cm"
self._mDocLeft = f"{left/10.0:.3f}cm"
self._mDocRight = f"{right/10.0:.3f}cm"
return
def setHeaderFormat(self, format: str, offset: int) -> None:
"""Set the document header format."""
self._headerFormat = format.strip()
self._pageOffset = offset
return
def setFirstLineIndent(self, state: bool) -> None:
"""Enable or disable first line indent."""
self._firstIndent = state
return
##
# Class Methods
##
def initDocument(self) -> None:
"""Initialises a new open document XML tree."""
# Initialise Variables
# ====================
self._fontFamily = self._textFont
if len(self._textFont.split()) > 1:
self._fontFamily = f"'{self._textFont}'"
self._fontPitch = "fixed" if self._textFixed else "variable"
self._fSizeTitle = f"{round(2.50 * self._textSize):d}pt"
self._fSizeHead1 = f"{round(2.00 * self._textSize):d}pt"
self._fSizeHead2 = f"{round(1.60 * self._textSize):d}pt"
self._fSizeHead3 = f"{round(1.30 * self._textSize):d}pt"
self._fSizeHead4 = f"{round(1.15 * self._textSize):d}pt"
self._fSizeHead = f"{round(1.15 * self._textSize):d}pt"
self._fSizeText = f"{self._textSize:d}pt"
mScale = self._lineHeight/1.15
self._mTopTitle = self._emToCm(mScale * self._marginTitle[0])
self._mTopHead1 = self._emToCm(mScale * self._marginHead1[0])
self._mTopHead2 = self._emToCm(mScale * self._marginHead2[0])
self._mTopHead3 = self._emToCm(mScale * self._marginHead3[0])
self._mTopHead4 = self._emToCm(mScale * self._marginHead4[0])
self._mTopHead = self._emToCm(mScale * self._marginHead4[0])
self._mTopText = self._emToCm(mScale * self._marginText[0])
self._mTopMeta = self._emToCm(mScale * self._marginMeta[0])
self._mBotTitle = self._emToCm(mScale * self._marginTitle[1])
self._mBotHead1 = self._emToCm(mScale * self._marginHead1[1])
self._mBotHead2 = self._emToCm(mScale * self._marginHead2[1])
self._mBotHead3 = self._emToCm(mScale * self._marginHead3[1])
self._mBotHead4 = self._emToCm(mScale * self._marginHead4[1])
self._mBotHead = self._emToCm(mScale * self._marginHead4[1])
self._mBotText = self._emToCm(mScale * self._marginText[1])
self._mBotMeta = self._emToCm(mScale * self._marginMeta[1])
if self._colourHead:
self._colHead12 = "#2a6099"
self._opaHead12 = "100%"
self._colHead34 = "#444444"
self._opaHead34 = "100%"
self._colMetaTx = "#813709"
self._opaMetaTx = "100%"
self._fLineHeight = f"{round(100 * self._lineHeight):d}%"
self._fBlockIndent = self._emToCm(self._blockIndent)
self._textAlign = "justify" if self._doJustify else "left"
# Clear Errors
self._errData = []
# Create Roots
# ============
tAttr = {}
tAttr[_mkTag("office", "version")] = X_VERS
fAttr = {}
fAttr[_mkTag("style", "name")] = self._textFont
fAttr[_mkTag("style", "font-pitch")] = self._fontPitch
if self._isFlat:
# FODT File
# =========
tAttr[_mkTag("office", "mimetype")] = X_MIME
tFlat = _mkTag("office", "document")
self._dFlat = ET.Element(tFlat, attrib=tAttr)
self._xMeta = ET.SubElement(self._dFlat, _mkTag("office", "meta"))
self._xFont = ET.SubElement(self._dFlat, _mkTag("office", "font-face-decls"))
self._xStyl = ET.SubElement(self._dFlat, _mkTag("office", "styles"))
self._xAuto = ET.SubElement(self._dFlat, _mkTag("office", "automatic-styles"))
self._xMast = ET.SubElement(self._dFlat, _mkTag("office", "master-styles"))
self._xBody = ET.SubElement(self._dFlat, _mkTag("office", "body"))
ET.SubElement(self._xFont, _mkTag("style", "font-face"), attrib=fAttr)
else:
# ODT File
# ========
tCont = _mkTag("office", "document-content")
tMeta = _mkTag("office", "document-meta")
tStyl = _mkTag("office", "document-styles")
# content.xml
self._dCont = ET.Element(tCont, attrib=tAttr)
self._xFont = ET.SubElement(self._dCont, _mkTag("office", "font-face-decls"))
self._xAuto = ET.SubElement(self._dCont, _mkTag("office", "automatic-styles"))
self._xBody = ET.SubElement(self._dCont, _mkTag("office", "body"))
# meta.xml
self._dMeta = ET.Element(tMeta, attrib=tAttr)
self._xMeta = ET.SubElement(self._dMeta, _mkTag("office", "meta"))
# styles.xml
self._dStyl = ET.Element(tStyl, attrib=tAttr)
self._xFnt2 = ET.SubElement(self._dStyl, _mkTag("office", "font-face-decls"))
self._xStyl = ET.SubElement(self._dStyl, _mkTag("office", "styles"))
self._xAut2 = ET.SubElement(self._dStyl, _mkTag("office", "automatic-styles"))
self._xMast = ET.SubElement(self._dStyl, _mkTag("office", "master-styles"))
ET.SubElement(self._xFont, _mkTag("style", "font-face"), attrib=fAttr)
ET.SubElement(self._xFnt2, _mkTag("style", "font-face"), attrib=fAttr)
# Finalise
# ========
self._xText = ET.SubElement(self._xBody, _mkTag("office", "text"))
timeStamp = datetime.now().isoformat(sep="T", timespec="seconds")
# Office Meta Data
xMeta = ET.SubElement(self._xMeta, _mkTag("meta", "creation-date"))
xMeta.text = timeStamp
xMeta = ET.SubElement(self._xMeta, _mkTag("meta", "generator"))
xMeta.text = f"novelWriter/{__version__}"
xMeta = ET.SubElement(self._xMeta, _mkTag("meta", "initial-creator"))
xMeta.text = self._project.data.author
xMeta = ET.SubElement(self._xMeta, _mkTag("meta", "editing-cycles"))
xMeta.text = str(self._project.data.saveCount)
# Format is: PnYnMnDTnHnMnS
# https://www.w3.org/TR/2004/REC-xmlschema-2-20041028/#duration
eT = self._project.data.editTime
xMeta = ET.SubElement(self._xMeta, _mkTag("meta", "editing-duration"))
xMeta.text = f"P{eT//86400:d}DT{eT%86400//3600:d}H{eT%3600//60:d}M{eT%60:d}S"
# Dublin Core Meta Data
xMeta = ET.SubElement(self._xMeta, _mkTag("dc", "title"))
xMeta.text = self._project.data.name
xMeta = ET.SubElement(self._xMeta, _mkTag("dc", "date"))
xMeta.text = timeStamp
xMeta = ET.SubElement(self._xMeta, _mkTag("dc", "creator"))
xMeta.text = self._project.data.author
self._pageStyles()
self._defaultStyles()
self._useableStyles()
self._writeHeader()
return
def doConvert(self) -> None:
"""Convert the list of text tokens into XML elements."""
self._result = "" # Not used, but cleared just in case
pFmt = []
pText = []
pStyle = None
pIndent = True
for tType, _, tText, tFormat, tStyle in self._tokens:
# Styles
oStyle = ODTParagraphStyle()
if tStyle is not None:
if tStyle & self.A_LEFT:
oStyle.setTextAlign("left")
elif tStyle & self.A_RIGHT:
oStyle.setTextAlign("right")
elif tStyle & self.A_CENTRE:
oStyle.setTextAlign("center")
elif tStyle & self.A_JUSTIFY:
oStyle.setTextAlign("justify")
if tStyle & self.A_PBB:
oStyle.setBreakBefore("page")
if tStyle & self.A_PBA:
oStyle.setBreakAfter("page")
if tStyle & self.A_Z_BTMMRG:
oStyle.setMarginBottom("0.000cm")
if tStyle & self.A_Z_TOPMRG:
oStyle.setMarginTop("0.000cm")
if tStyle & self.A_IND_L:
oStyle.setMarginLeft(self._fBlockIndent)
if tStyle & self.A_IND_R:
oStyle.setMarginRight(self._fBlockIndent)
if tType not in (self.T_EMPTY, self.T_TEXT):
pIndent = False
# Process Text Types
if tType == self.T_EMPTY:
if len(pText) > 1 and pStyle is not None:
if self._doJustify:
pStyle.setTextAlign("left")
if len(pText) > 0 and pStyle is not None:
tTxt = ""
tFmt = []
for nText, nFmt in zip(pText, pFmt):
tLen = len(tTxt)
tTxt += f"{nText}\n"
tFmt.extend((p+tLen, fmt) for p, fmt in nFmt)
# Don't indent a paragraph if it has alignment set
tIndent = self._firstIndent and pIndent and pStyle.isUnaligned()
self._addTextPar(
"First_20_line_20_indent" if tIndent else "Text_20_body",
pStyle, tTxt.rstrip(), tFmt=tFmt
)
pIndent = True
pFmt = []
pText = []
pStyle = None
elif tType == self.T_TITLE:
tHead = tText.replace(nwHeadFmt.BR, "\n")
self._addTextPar("Title", oStyle, tHead, isHead=False) # Title must be text:p
elif tType == self.T_HEAD1:
tHead = tText.replace(nwHeadFmt.BR, "\n")
self._addTextPar("Heading_20_1", oStyle, tHead, isHead=True, oLevel="1")
elif tType == self.T_HEAD2:
tHead = tText.replace(nwHeadFmt.BR, "\n")
self._addTextPar("Heading_20_2", oStyle, tHead, isHead=True, oLevel="2")
elif tType == self.T_HEAD3:
tHead = tText.replace(nwHeadFmt.BR, "\n")
self._addTextPar("Heading_20_3", oStyle, tHead, isHead=True, oLevel="3")
elif tType == self.T_HEAD4:
tHead = tText.replace(nwHeadFmt.BR, "\n")
self._addTextPar("Heading_20_4", oStyle, tHead, isHead=True, oLevel="4")
elif tType == self.T_SEP:
self._addTextPar("Separator", oStyle, tText)
elif tType == self.T_SKIP:
self._addTextPar("Separator", oStyle, "")
elif tType == self.T_TEXT:
if pStyle is None:
pStyle = oStyle
pText.append(tText)
pFmt.append(tFormat)
elif tType == self.T_SYNOPSIS and self._doSynopsis:
tTemp, fTemp = self._formatSynopsis(tText, True)
self._addTextPar("Text_20_Meta", oStyle, tTemp, tFmt=fTemp)
elif tType == self.T_SHORT and self._doSynopsis:
tTemp, fTemp = self._formatSynopsis(tText, False)
self._addTextPar("Text_20_Meta", oStyle, tTemp, tFmt=fTemp)
elif tType == self.T_COMMENT and self._doComments:
tTemp, fTemp = self._formatComments(tText)
self._addTextPar("Text_20_Meta", oStyle, tTemp, tFmt=fTemp)
elif tType == self.T_KEYWORD and self._doKeywords:
tTemp, fTemp = self._formatKeywords(tText)
self._addTextPar("Text_20_Meta", oStyle, tTemp, tFmt=fTemp)
return
def closeDocument(self) -> None:
"""Pack the styles of the XML document."""
# Build the auto-generated styles
for styleName, styleObj in self._autoPara.values():
styleObj.packXML(self._xAuto, styleName)
for styleName, styleObj in self._autoText.values():
styleObj.packXML(self._xAuto, styleName)
return
def saveFlatXML(self, path: str | Path) -> None:
"""Save the data to an .fodt file."""
with open(path, mode="wb") as fObj:
xml = ET.ElementTree(self._dFlat)
xmlIndent(xml)
xml.write(fObj, encoding="utf-8", xml_declaration=True)
logger.info("Wrote file: %s", path)
return
def saveOpenDocText(self, path: str | Path) -> None:
"""Save the data to an .odt file."""
mMani = _mkTag("manifest", "manifest")
mVers = _mkTag("manifest", "version")
mPath = _mkTag("manifest", "full-path")
mType = _mkTag("manifest", "media-type")
mFile = _mkTag("manifest", "file-entry")
xMani = ET.Element(mMani, attrib={mVers: X_VERS})
ET.SubElement(xMani, mFile, attrib={mPath: "/", mVers: X_VERS, mType: X_MIME})
ET.SubElement(xMani, mFile, attrib={mPath: "settings.xml", mType: "text/xml"})
ET.SubElement(xMani, mFile, attrib={mPath: "content.xml", mType: "text/xml"})
ET.SubElement(xMani, mFile, attrib={mPath: "meta.xml", mType: "text/xml"})
ET.SubElement(xMani, mFile, attrib={mPath: "styles.xml", mType: "text/xml"})
oRoot = _mkTag("office", "document-settings")
oVers = _mkTag("office", "version")
xSett = ET.Element(oRoot, attrib={oVers: X_VERS})
def putInZip(name, xObj, zipObj):
with zipObj.open(name, mode="w") as fObj:
xml = ET.ElementTree(xObj)
xml.write(fObj, encoding="utf-8", xml_declaration=True)
with ZipFile(path, mode="w") as outZip:
outZip.writestr("mimetype", X_MIME)
putInZip("META-INF/manifest.xml", xMani, outZip)
putInZip("settings.xml", xSett, outZip)
putInZip("content.xml", self._dCont, outZip)
putInZip("meta.xml", self._dMeta, outZip)
putInZip("styles.xml", self._dStyl, outZip)
logger.info("Wrote file: %s", path)
return
##
# Internal Functions
##
def _formatSynopsis(self, text: str, synopsis: bool) -> tuple[str, list[tuple[int, int]]]:
"""Apply formatting to synopsis lines."""
if synopsis:
name = self._localLookup("Synopsis")
else:
name = self._localLookup("Short Description")
rTxt = f"{name}: {text}"
rFmt = [(0, self.FMT_B_B), (len(name) + 1, self.FMT_B_E)]
return rTxt, rFmt
def _formatComments(self, text: str) -> tuple[str, list[tuple[int, int]]]:
"""Apply formatting to comments."""
name = self._localLookup("Comment")
rTxt = f"{name}: {text}"
rFmt = [(0, self.FMT_B_B), (len(name) + 1, self.FMT_B_E)]
return rTxt, rFmt
def _formatKeywords(self, text: str) -> tuple[str, list[tuple[int, int]]]:
"""Apply formatting to keywords."""
valid, bits, _ = self._project.index.scanThis("@"+text)
if not valid or not bits or bits[0] not in nwLabels.KEY_NAME:
return "", []
rTxt = f"{self._localLookup(nwLabels.KEY_NAME[bits[0]])}: "
rFmt = [(0, self.FMT_B_B), (len(rTxt) - 1, self.FMT_B_E)]
if len(bits) > 1:
if bits[0] == nwKeyWords.TAG_KEY:
rTxt += bits[1]
else:
rTxt += ", ".join(bits[1:])
return rTxt, rFmt
def _addTextPar(
self, styleName: str, oStyle: ODTParagraphStyle, tText: str,
tFmt: Sequence[tuple[int, int]] = [], isHead: bool = False, oLevel: str | None = None
) -> None:
"""Add a text paragraph to the text XML element."""
tAttr = {}
tAttr[_mkTag("text", "style-name")] = self._paraStyle(styleName, oStyle)
if oLevel is not None:
tAttr[_mkTag("text", "outline-level")] = oLevel
pTag = "h" if isHead else "p"
xElem = ET.SubElement(self._xText, _mkTag("text", pTag), attrib=tAttr)
# It's important to set the initial text field to empty, otherwise
# xmlIndent will add a line break if the first subelement is a span.
xElem.text = ""
if not tText:
return
# Loop Over Fragments
# ===================
parProc = XMLParagraph(xElem)
pErr = 0
xFmt = 0x00
tFrag = ""
fLast = 0
for fPos, fFmt in tFmt:
# Add the text up to the current fragment
if tFrag := tText[fLast:fPos]:
if xFmt == 0x00:
parProc.appendText(tFrag)
else:
parProc.appendSpan(tFrag, self._textStyle(xFmt))
# Calculate the change of format
if fFmt == self.FMT_B_B:
xFmt |= X_BLD
elif fFmt == self.FMT_B_E:
xFmt &= M_BLD
elif fFmt == self.FMT_I_B:
xFmt |= X_ITA
elif fFmt == self.FMT_I_E:
xFmt &= M_ITA
elif fFmt == self.FMT_D_B:
xFmt |= X_DEL
elif fFmt == self.FMT_D_E:
xFmt &= M_DEL
elif fFmt == self.FMT_U_B:
xFmt |= X_UND
elif fFmt == self.FMT_U_E:
xFmt &= M_UND
elif fFmt == self.FMT_M_B:
xFmt |= X_MRK
elif fFmt == self.FMT_M_E:
xFmt &= M_MRK
elif fFmt == self.FMT_SUP_B:
xFmt |= X_SUP
elif fFmt == self.FMT_SUP_E:
xFmt &= M_SUP
elif fFmt == self.FMT_SUB_B:
xFmt |= X_SUB
elif fFmt == self.FMT_SUB_E:
xFmt &= M_SUB
else:
pErr += 1
fLast = fPos
if tFrag := tText[fLast:]:
if xFmt == 0x00:
parProc.appendText(tFrag)
else:
parProc.appendSpan(tFrag, self._textStyle(xFmt))
if pErr > 0:
self._errData.append("Unknown format tag encountered")
nErr, errMsg = parProc.checkError()
if nErr > 0: # pragma: no cover
# This one should only capture bugs
self._errData.append(errMsg)
return
def _paraStyle(self, parName: str, oStyle: ODTParagraphStyle) -> str:
"""Return a name for a style object."""
refStyle = self._mainPara.get(parName, None)
if refStyle is None:
logger.error("Unknown paragraph style '%s'", parName)
return "Standard"
if not refStyle.checkNew(oStyle):
return parName
oStyle.setParentStyleName(parName)
pID = oStyle.getID()
if pID in self._autoPara:
return self._autoPara[pID][0]
newName = "P%d" % (len(self._autoPara) + 1)
self._autoPara[pID] = (newName, oStyle)
return newName
def _textStyle(self, hFmt: int) -> str:
"""Return a text style for a given style code."""
if hFmt in self._autoText:
return self._autoText[hFmt][0]
newName = "T%d" % (len(self._autoText) + 1)
newStyle = ODTTextStyle()
if hFmt & X_BLD:
newStyle.setFontWeight("bold")
if hFmt & X_ITA:
newStyle.setFontStyle("italic")
if hFmt & X_DEL:
newStyle.setStrikeStyle("solid")
newStyle.setStrikeType("single")
if hFmt & X_UND:
newStyle.setUnderlineStyle("solid")
newStyle.setUnderlineWidth("auto")
newStyle.setUnderlineColour("font-color")
if hFmt & X_MRK:
newStyle.setBackgroundColor(self._markText)
if hFmt & X_SUP:
newStyle.setTextPosition("super")
if hFmt & X_SUB:
newStyle.setTextPosition("sub")
self._autoText[hFmt] = (newName, newStyle)
return newName
def _emToCm(self, value: float) -> str:
"""Converts an em value to centimetres."""
return f"{value*2.54/72*self._textSize:.3f}cm"
##
# Style Elements
##
def _pageStyles(self) -> None:
"""Set the default page style."""
tAttr = {}
tAttr[_mkTag("style", "name")] = "PM1"
if self._isFlat:
xPage = ET.SubElement(self._xAuto, _mkTag("style", "page-layout"), attrib=tAttr)
else:
xPage = ET.SubElement(self._xAut2, _mkTag("style", "page-layout"), attrib=tAttr)
tAttr = {}
tAttr[_mkTag("fo", "page-width")] = self._mDocWidth
tAttr[_mkTag("fo", "page-height")] = self._mDocHeight
tAttr[_mkTag("fo", "margin-top")] = self._mDocTop
tAttr[_mkTag("fo", "margin-bottom")] = self._mDocBtm
tAttr[_mkTag("fo", "margin-left")] = self._mDocLeft
tAttr[_mkTag("fo", "margin-right")] = self._mDocRight
tAttr[_mkTag("fo", "print-orientation")] = "portrait"
ET.SubElement(xPage, _mkTag("style", "page-layout-properties"), attrib=tAttr)
xHead = ET.SubElement(xPage, _mkTag("style", "header-style"))
tAttr = {}
tAttr[_mkTag("fo", "min-height")] = "0.600cm"
tAttr[_mkTag("fo", "margin-left")] = "0.000cm"
tAttr[_mkTag("fo", "margin-right")] = "0.000cm"
tAttr[_mkTag("fo", "margin-bottom")] = "0.500cm"
ET.SubElement(xHead, _mkTag("style", "header-footer-properties"), attrib=tAttr)
return
def _defaultStyles(self) -> None:
"""Set the default styles."""
# Add Paragraph Family Style
# ==========================
tAttr = {}
tAttr[_mkTag("style", "family")] = "paragraph"
xStyl = ET.SubElement(self._xStyl, _mkTag("style", "default-style"), attrib=tAttr)
tAttr = {}
tAttr[_mkTag("style", "line-break")] = "strict"
tAttr[_mkTag("style", "tab-stop-distance")] = "1.251cm"
tAttr[_mkTag("style", "writing-mode")] = "page"
ET.SubElement(xStyl, _mkTag("style", "paragraph-properties"), attrib=tAttr)
tAttr = {}
tAttr[_mkTag("style", "font-name")] = self._textFont
tAttr[_mkTag("fo", "font-family")] = self._fontFamily
tAttr[_mkTag("fo", "font-size")] = self._fSizeText
tAttr[_mkTag("fo", "language")] = self._dLanguage
tAttr[_mkTag("fo", "country")] = self._dCountry
ET.SubElement(xStyl, _mkTag("style", "text-properties"), attrib=tAttr)
# Add Standard Paragraph Style
# ============================
tAttr = {}
tAttr[_mkTag("style", "name")] = "Standard"
tAttr[_mkTag("style", "family")] = "paragraph"
tAttr[_mkTag("style", "class")] = "text"
xStyl = ET.SubElement(self._xStyl, _mkTag("style", "style"), attrib=tAttr)
tAttr = {}
tAttr[_mkTag("style", "font-name")] = self._textFont
tAttr[_mkTag("fo", "font-family")] = self._fontFamily
tAttr[_mkTag("fo", "font-size")] = self._fSizeText
ET.SubElement(xStyl, _mkTag("style", "text-properties"), attrib=tAttr)
# Add Default Heading Style
# =========================
tAttr = {}
tAttr[_mkTag("style", "name")] = "Heading"
tAttr[_mkTag("style", "family")] = "paragraph"
tAttr[_mkTag("style", "parent-style-name")] = "Standard"
tAttr[_mkTag("style", "next-style-name")] = "Text_20_body"
tAttr[_mkTag("style", "class")] = "text"
xStyl = ET.SubElement(self._xStyl, _mkTag("style", "style"), attrib=tAttr)
tAttr = {}
tAttr[_mkTag("fo", "margin-top")] = self._mTopHead
tAttr[_mkTag("fo", "margin-bottom")] = self._mBotHead
tAttr[_mkTag("fo", "keep-with-next")] = "always"
ET.SubElement(xStyl, _mkTag("style", "paragraph-properties"), attrib=tAttr)
tAttr = {}
tAttr[_mkTag("style", "font-name")] = self._textFont
tAttr[_mkTag("fo", "font-family")] = self._fontFamily
tAttr[_mkTag("fo", "font-size")] = self._fSizeHead
ET.SubElement(xStyl, _mkTag("style", "text-properties"), attrib=tAttr)
# Add Header and Footer Styles
# ============================
tAttr = {}
tAttr[_mkTag("style", "name")] = "Header_20_and_20_Footer"
tAttr[_mkTag("style", "display-name")] = "Header and Footer"
tAttr[_mkTag("style", "family")] = "paragraph"
tAttr[_mkTag("style", "parent-style-name")] = "Standard"
tAttr[_mkTag("style", "class")] = "extra"
ET.SubElement(self._xStyl, _mkTag("style", "style"), attrib=tAttr)
return
def _useableStyles(self) -> None:
"""Set the usable styles."""
# Add Text Body Style
# ===================
oStyle = ODTParagraphStyle()
oStyle.setDisplayName("Text body")
oStyle.setParentStyleName("Standard")
oStyle.setClass("text")
oStyle.setMarginTop(self._mTopText)
oStyle.setMarginBottom(self._mBotText)
oStyle.setLineHeight(self._fLineHeight)
oStyle.setFontName(self._textFont)
oStyle.setFontFamily(self._fontFamily)
oStyle.setFontSize(self._fSizeText)
oStyle.setTextAlign(self._textAlign)
oStyle.packXML(self._xStyl, "Text_20_body")
self._mainPara["Text_20_body"] = oStyle
# Add First Line Indent Style
# ===========================
oStyle = ODTParagraphStyle()
oStyle.setDisplayName("First line indent")
oStyle.setParentStyleName("Text_20_body")
oStyle.setClass("text")
oStyle.setTextIndent(self._fTextIndent)
oStyle.packXML(self._xStyl, "First_20_line_20_indent")
self._mainPara["First_20_line_20_indent"] = oStyle
# Add Text Meta Style
# ===================
oStyle = ODTParagraphStyle()
oStyle.setDisplayName("Text Meta")
oStyle.setParentStyleName("Standard")
oStyle.setClass("text")
oStyle.setMarginTop(self._mTopMeta)
oStyle.setMarginBottom(self._mBotMeta)
oStyle.setLineHeight(self._fLineHeight)
oStyle.setFontName(self._textFont)
oStyle.setFontFamily(self._fontFamily)
oStyle.setFontSize(self._fSizeText)
oStyle.setColor(self._colMetaTx)
oStyle.setOpacity(self._opaMetaTx)
oStyle.packXML(self._xStyl, "Text_20_Meta")
self._mainPara["Text_20_Meta"] = oStyle
# Add Title Style
# ===============
oStyle = ODTParagraphStyle()
oStyle.setDisplayName("Title")
oStyle.setParentStyleName("Heading")
oStyle.setNextStyleName("Text_20_body")
oStyle.setClass("chapter")
oStyle.setTextAlign("center")
oStyle.setMarginTop(self._mTopTitle)
oStyle.setMarginBottom(self._mBotTitle)
oStyle.setFontName(self._textFont)
oStyle.setFontFamily(self._fontFamily)
oStyle.setFontSize(self._fSizeTitle)
oStyle.setFontWeight("bold")
oStyle.packXML(self._xStyl, "Title")
self._mainPara["Title"] = oStyle
# Add Separator Style
# ===================
oStyle = ODTParagraphStyle()
oStyle.setDisplayName("Separator")
oStyle.setParentStyleName("Standard")
oStyle.setNextStyleName("Text_20_body")
oStyle.setClass("text")
oStyle.setTextAlign("center")
oStyle.setMarginTop(self._mTopText)
oStyle.setMarginBottom(self._mBotText)
oStyle.setLineHeight(self._fLineHeight)
oStyle.setFontName(self._textFont)
oStyle.setFontFamily(self._fontFamily)
oStyle.setFontSize(self._fSizeText)
oStyle.packXML(self._xStyl, "Separator")
self._mainPara["Separator"] = oStyle
# Add Heading 1 Style
# ===================
oStyle = ODTParagraphStyle()
oStyle.setDisplayName("Heading 1")
oStyle.setParentStyleName("Heading")
oStyle.setNextStyleName("Text_20_body")
oStyle.setOutlineLevel("1")
oStyle.setClass("text")
oStyle.setMarginTop(self._mTopHead1)
oStyle.setMarginBottom(self._mBotHead1)
oStyle.setFontName(self._textFont)
oStyle.setFontFamily(self._fontFamily)
oStyle.setFontSize(self._fSizeHead1)
oStyle.setColor(self._colHead12)
oStyle.setOpacity(self._opaHead12)
oStyle.setFontWeight("bold")
oStyle.packXML(self._xStyl, "Heading_20_1")
self._mainPara["Heading_20_1"] = oStyle
# Add Heading 2 Style
# ===================
oStyle = ODTParagraphStyle()
oStyle.setDisplayName("Heading 2")
oStyle.setParentStyleName("Heading")
oStyle.setNextStyleName("Text_20_body")
oStyle.setOutlineLevel("2")
oStyle.setClass("text")
oStyle.setMarginTop(self._mTopHead2)
oStyle.setMarginBottom(self._mBotHead2)
oStyle.setFontName(self._textFont)
oStyle.setFontFamily(self._fontFamily)
oStyle.setFontSize(self._fSizeHead2)
oStyle.setColor(self._colHead12)
oStyle.setOpacity(self._opaHead12)
oStyle.setFontWeight("bold")
oStyle.packXML(self._xStyl, "Heading_20_2")
self._mainPara["Heading_20_2"] = oStyle
# Add Heading 3 Style
# ===================
oStyle = ODTParagraphStyle()
oStyle.setDisplayName("Heading 3")
oStyle.setParentStyleName("Heading")
oStyle.setNextStyleName("Text_20_body")
oStyle.setOutlineLevel("3")
oStyle.setClass("text")
oStyle.setMarginTop(self._mTopHead3)
oStyle.setMarginBottom(self._mBotHead3)
oStyle.setFontName(self._textFont)
oStyle.setFontFamily(self._fontFamily)
oStyle.setFontSize(self._fSizeHead3)