]> Shamusworld >> Repos - ardour-manual/blob - build.py
Various improvements in the PDF rendering. More efficient build
[ardour-manual] / build.py
1 #!/usr/bin/python3
2 #
3 # Script to take the master document and ancillary files and create the
4 # finished manual/website.
5 #
6 # by James Hammons
7 # (C) 2017 Underground Software
8 #
9 # Contributors: Ed Ward
10 #
11
12 # Remnants (could go into the master document as the first header)
13
14 import os
15 import re
16 import shutil
17 import argparse
18
19
20 # Global vars
21 global_bootstrap_path = '/bootstrap-3.3.7'
22 global_page_title = 'The Ardour Manual'
23 global_site_dir = './website/'
24 global_githuburl = 'https://github.com/Ardour/manual/edit/master/include/'
25 global_screen_template = 'page-template.html'
26 global_onepage_template = 'onepage-template.html'
27 global_pdf_template = 'pdf-template.html'
28 global_master_doc = 'master-doc.txt'
29
30 # This matches all *non* letter/number, ' ', '.', '-', and '_' chars
31 cleanString = re.compile(r'[^a-zA-Z0-9 \._-]+')
32 # This matches new 'unbreakable' links, up to the closing quote or anchor
33 findLinks = re.compile(r'"@@[^#"]*[#"]')
34
35 #
36 # Create an all lowercase filename without special characters and with spaces
37 # replaced with dashes.
38 #
39 def MakeFilename(s):
40         global cleanString
41         # Clean up the file name, removing all non letter/number or " .-_" chars.
42         # Also, convert to lower case and replace all spaces with dashes.
43         fn = cleanString.sub('', s).lower().replace(' ', '-')
44         # Double dashes can creep in from the above replacement, so we check for
45         # that here.
46         fn = fn.replace('--', '-')
47
48         return fn
49
50
51 #
52 # Parse headers into a dictionary
53 #
54 def ParseHeader(fileObj):
55         header = {}
56
57         while (True):
58                 hdrLine = fileObj.readline().rstrip('\r\n')
59
60                 # Break out of the loop if we hit the end of header marker
61                 if hdrLine.startswith('---'):
62                         break
63
64                 # Check to see that we have a well-formed header construct
65                 match = re.findall(': ', hdrLine)
66
67                 if match:
68                         # Parse out foo: bar pairs & put into header dictionary
69                         a = re.split(': ', hdrLine, 1)
70                         header[a[0]] = a[1]
71
72         return header
73
74
75 #
76 # Turn a "part" name into an int
77 #
78 def PartToLevel(s):
79         level = -1
80         lvl = {'part': 0, 'chapter': 1, 'subchapter': 2}
81         if s in lvl:
82                 return lvl[s]
83         else:
84                 return -1
85
86
87 #
88 # Converts a integer to a Roman numeral
89 #
90 def num2roman(num):
91         num_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
92         roman = ''
93
94         while num > 0:
95                 for i, r in num_map:
96                         while num >= i:
97                                 roman += r
98                                 num -= i
99
100         return roman
101
102 #
103 # Capture the master document's structure (and content, if any) in a list
104 #
105 def GetFileStructure():
106         fs = []
107         fnames = [None]*6
108         content = ''
109         grab = False
110         mf = open(global_master_doc)
111
112         for ln in mf:
113                 if ln.startswith('---'):
114                         # First, stuff any content that we may have read into the current
115                         # header's dictionary
116                         if grab:
117                                 fs[-1]['content'] = content
118                                 grab = False
119                                 content = ''
120
121                         # Then, get the new header and do things to it
122                         hdr = ParseHeader(mf)
123                         level = PartToLevel(hdr['part'])
124                         hdr['level'] = level
125                         fnames[level] = MakeFilename(hdr['title'])
126
127                         # Ickyness--user specified URIs
128                         if 'uri' in hdr:
129                                 hdr['filename'] = hdr['uri']
130                         else:
131                                 fullName = ''
132
133                                 for i in range(level + 1):
134                                         fullName = fullName + fnames[i] + '/'
135
136                                 # Strip trailing '/' on filename
137                                 hdr['filename'] = fullName[:-1]
138
139                         fs.append(hdr)
140
141                         if ('include' not in hdr) and (level > 0):
142                                 grab = True
143                 else:
144                         if grab:
145                                 content = content + ln
146
147         # Catch the last file, since it would be missed above
148         if grab:
149                 fs[-1]['content'] = content
150
151         mf.close()
152         return fs
153
154
155 #
156 # Determine if a particular node has child nodes
157 #
158 def HaveChildren(fs, pos):
159         # If we're at the end of the list, there can be no children
160         if pos == len(fs) - 1:
161                 return False
162
163         # If the next node is at a lower level than the current node, we have
164         # children.
165         if fs[pos]['level'] < fs[pos + 1]['level']:
166                 return True
167
168         # Otherwise, no children at this node.
169         return False
170
171
172 #
173 # Get the children at this level, and return them in a list
174 #
175 def GetChildren(fs, pos):
176         children = []
177         pos = pos + 1
178         childLevel =  fs[pos]['level']
179
180         while fs[pos]['level'] >= childLevel:
181                 if fs[pos]['level'] == childLevel:
182                         children.append(pos)
183
184                 pos = pos + 1
185
186                 # Sanity check
187                 if pos == len(fs):
188                         break
189
190         return children
191
192
193 #
194 # Get the parent at this level
195 #
196 def GetParent(fs, pos):
197         thisLevel =  fs[pos]['level']
198         pos = pos - 1
199
200         while pos >= 0 and fs[pos]['level'] >= thisLevel:
201                 pos = pos - 1
202
203         return pos
204
205
206 #
207 # Change the hierarchy of titles : h1->hn, h2->hn+1, etc... n being delta-1
208 #
209 def reheader(txt, delta):
210         for i in range(6, 0, -1):
211                 txt = txt.replace('<h' + str(i),'<h' + str(i+delta))
212                 txt = txt.replace('</h' + str(i),'</h' + str(i+delta))
213         return txt
214
215
216 #
217 # Creates the BreadCrumbs
218 #
219 def GetBreadCrumbs(fs, pos):
220         breadcrumbs = '<li class="active">'+ fs[pos]['title'] + '</li>'
221
222         while pos >= 0:
223                 pos = GetParent(fs, pos)
224
225                 if pos >= 0:
226                         breadcrumbs='<li><a href="/' + fs[pos]['filename'] + '/">'+ fs[pos]['title'] + '</a></li>'+ breadcrumbs
227
228         breadcrumbs = '<ul class="breadcrumb"><li><a href="/toc/index.html">Home</a></li>' + breadcrumbs + '</ul>'
229         return breadcrumbs
230
231
232 #
233 # Make an array of children attached to each node in the file structure
234 # (It's a quasi-tree structure, and can be traversed as such.)
235 #
236 def FindChildren(fs):
237         childArray = []
238
239         for i in range(len(fs)):
240                 if HaveChildren(fs, i):
241                         childArray.append(GetChildren(fs, i))
242                 else:
243                         childArray.append([])
244
245         return childArray
246
247
248 #
249 # Make an array of the top level nodes in the file structure
250 #
251 def FindTopLevelNodes(fs):
252         level0 = []
253
254         for i in range(len(fs)):
255                 if fs[i]['level'] == 0:
256                         level0.append(i)
257
258         return level0
259
260
261 #
262 # Find all header links and create a dictionary out of them
263 #
264 def FindInternalLinks(fs):
265         linkDict = {}
266
267         for hdr in fs:
268                 if 'link' in hdr:
269                         linkDict['"@@' + hdr['link'] + '"'] = '"/' + hdr['filename'] + '/"'
270                         linkDict['"@@' + hdr['link'] + '#'] = '"/' + hdr['filename'] + '/index.html#'
271
272         return linkDict
273
274 #
275 # Same as above, but create anchors (for the one-page version)
276 #
277 def FindInternalAnchors(fs):
278         linkDict = {}
279
280         for hdr in fs:
281                 if 'link' in hdr:
282                         linkDict['"@@' + hdr['link'] + '"'] = '"#' + hdr['link'] + '"'
283                         linkDict['"@@' + hdr['link'] + '#'] = '"#' + hdr['link'] + '"'
284
285         return linkDict
286
287
288 #
289 # Internal links are of the form '@@link-name', which are references to the
290 # 'link:' field in the part header. We have to find all occurrences and replace
291 # them with the appropriate link.
292 #
293 def FixInternalLinks(links, content, title):
294         global findLinks
295         match = findLinks.findall(content)
296         missing = []
297
298         if len(match) > 0:
299                 for s in match:
300                         if s in links:
301                                 content = content.replace(s, links[s])
302                         else:
303                                 missing.append(s)
304
305         # Report missing link targets to the user (if any)
306         if len(missing) > 0:
307                 print('\nMissing link target' + ('s' if len(missing) > 1 else '') + ' in "' + title + '":')
308
309                 for s in missing:
310                         print('  ' + s)
311
312                 print()
313
314         return content
315
316
317 #
318 # Recursively build a list of links based on the location of the page we're
319 # looking at currently
320 #
321 def BuildList(lst, fs, pagePos, cList):
322         content = '\n\n<ul>\n'
323
324         for i in range(len(lst)):
325                 curPos = lst[i]
326                 nextPos = lst[i + 1] if i + 1 < len(lst) else len(fs)
327
328                 active = ' class=active' if curPos == pagePos else ''
329                 menuTitle = fs[curPos]['menu_title'] if 'menu_title' in fs[curPos] else fs[curPos]['title']
330                 content = content + '<li' + active + '><a href="/' + fs[curPos]['filename'] + '/">' + menuTitle + '</a></li>'
331
332                 # If the current page is our page, and it has children, enumerate them
333                 if curPos == pagePos:
334                         if len(cList[curPos]) > 0:
335                                 content = content + BuildList(cList[curPos], fs, -1, cList)
336
337                 # Otherwise, if our page lies between the current one and the next,
338                 # build a list of links from those nodes one level down.
339                 elif (pagePos > curPos) and (pagePos < nextPos):
340                         content = content + BuildList(cList[curPos], fs, pagePos, cList)
341
342         content = content + '\n</ul>\n'
343
344         return content
345
346
347 #
348 # Builds the sidebar for the one-page version
349 #
350 def BuildOnePageSidebar(fs):
351
352         content = '\n\n<ul class="toc" style="white-space:nowrap;">\n'
353         lvl = 0
354         levelNums = [0]*3
355
356         for i in range(len(fs)):
357                 # Handle Part/Chapter/subchapter numbering
358                 level = fs[i]['level']
359                 if level < 2:
360                         levelNums[2] = 0
361                 levelNums[level] = levelNums[level] + 1;
362                 j = level
363                 txtlevel = ''
364                 while j > 0:  #level 0 is the part number which is not shown
365                         txtlevel = str(levelNums[j]) + '.' + txtlevel
366                         j = j-1
367                 if len(txtlevel) > 0:
368                         txtlevel = txtlevel[:-1] + ' - '
369
370                 if 'link' in fs[i]:
371                         anchor = fs[i]['link']
372                 else:
373                         anchor = fs[i]['filename']
374
375                 while lvl < level:
376                         content = content + '<ul style="white-space:nowrap;">\n'
377                         lvl = lvl + 1
378                 while lvl > level:
379                         content = content + '</ul>\n'
380                         lvl = lvl - 1
381
382                 content = content + '<li><a href="#' + anchor + '">' + txtlevel + fs[i]['title'] + '</a></li>\n'
383
384         content = content + '</ul>\n'
385
386         return content
387
388
389 #
390 # Create link sidebar given a position in the list.
391 #
392 def CreateLinkSidebar(fs, pos, childList):
393
394         # Build the list recursively from the top level nodes
395         content = BuildList(FindTopLevelNodes(fs), fs, pos, childList)
396         # Shove the TOC link and one file link at the top...
397         active = ' class=active' if pos<0 else ''
398         content = content.replace('<ul>','<ul><li' + active + '><a href="/toc/">Table of Contents</a></li>\n',1)
399
400         return content
401
402 # Preliminaries
403
404 # We have command line arguments now, so deal with them
405 parser = argparse.ArgumentParser(description='A build script for the Ardour Manual')
406 parser.add_argument('-v', '--verbose', action='store_true', help='Display the high-level structure of the manual')
407 parser.add_argument('-q', '--quiet', action='store_true', help='Suppress all output (overrides -v)')
408 parser.add_argument('-d', '--devmode', action='store_true', help='Add content to pages to help developers debug them')
409 parser.add_argument('-n', '--nopdf', action='store_true', help='Do not automatically generate PDF from content')
410 args = parser.parse_args()
411 verbose = args.verbose
412 quiet = args.quiet
413 devmode = args.devmode
414 nopdf = args.nopdf
415
416 if quiet:
417         verbose = False
418
419 level = 0
420 fileCount = 0
421 levelNums = [0]*3
422 lastFile = ''
423 page = ''
424 onepage = ''
425 pdfpage = ''
426 toc = ''
427 pageNumber = 0
428
429
430
431 if not quiet and devmode:
432         print('Devmode active: scribbling extra junk to the manual...')
433
434 if os.access(global_site_dir, os.F_OK):
435         if not quiet:
436                 print('Removing stale HTML data...')
437
438         shutil.rmtree(global_site_dir)
439
440 shutil.copytree('./source', global_site_dir)
441
442
443 # Read the template, and fix the stuff that's fixed for all pages
444 temp = open(global_screen_template)
445 template = temp.read()
446 temp.close()
447 template = template.replace('{{page.bootstrap_path}}', global_bootstrap_path)
448 template = template.replace('{{page.page_title}}', global_page_title)
449
450 # Same as above, but for the One-page version
451 temp = open(global_onepage_template)
452 onepage = temp.read()
453 temp.close()
454 onepage = onepage.replace('{{page.bootstrap_path}}', global_bootstrap_path)
455 onepage = onepage.replace('{{page.page_title}}', global_page_title)
456
457 if not nopdf:
458         # Same as above, but for the PDF version
459         temp = open(global_pdf_template)
460         pdfpage = temp.read()
461         temp.close()
462         pdfpage = pdfpage.replace('{{page.page_title}}', global_page_title)
463
464 # Parse out the master document's structure into a dictionary list
465 fileStruct = GetFileStructure()
466
467 # Build a quasi-tree structure listing children at level + 1 for each node
468 nodeChildren = FindChildren(fileStruct)
469
470 # Create a dictionary for translation of internal links to real links
471 links = FindInternalLinks(fileStruct)
472 oplinks = FindInternalAnchors(fileStruct)
473
474 if not quiet:
475         print('Found ' + str(len(links)) + ' internal link target', end='')
476         print('.') if len(links) == 1 else print('s.')
477
478 if not quiet:
479         master = open(global_master_doc)
480         firstLine = master.readline().rstrip('\r\n')
481         master.close()
482
483         if firstLine == '<!-- exploded -->':
484                 print('Parsing exploded file...')
485         elif firstLine == '<!-- imploded -->':
486                 print('Parsing imploded file...')
487         else:
488                 print('Parsing unknown type...')
489
490 # Here we go!
491
492 for header in fileStruct:
493         fileCount = fileCount + 1
494         content = ''
495         more = ''
496
497         lastLevel = level
498         level = header['level']
499
500         # Handle Part/Chapter/subchapter numbering
501         if level < 2:
502                 levelNums[2] = 0
503         levelNums[level] = levelNums[level] + 1;
504
505         # This is totally unnecessary, but nice; besides which, you can capture
506         # the output to a file to look at later if you like :-)
507         if verbose:
508                 for i in range(level):
509                         print('\t', end='')
510
511                 if (level == 0):
512                         print('\nPart ' + num2roman(levelNums[0]) + ': ', end='')
513                 elif (level == 1):
514                         print('\n\tChapter ' + str(levelNums[1]) + ': ', end='')
515
516                 print(header['title'])
517
518         # Handle TOC scriblings...
519         if level == 0:
520                 toc = toc + '<h2>Part ' + num2roman(levelNums[level]) + ': ' + header['title'] + '</h2>\n';
521         elif level == 1:
522                 toc = toc + '\t<p class="chapter">Ch. ' + str(levelNums[level]) + ':&nbsp;&nbsp;<a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
523         elif level == 2:
524                 toc = toc + '\t\t<p class="subchapter"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
525
526         # Handle one-page and PDF titles...
527         opl = ''
528         if 'link' in header:
529                 opl = ' id="' + header['link'] + '"'
530         else:
531                 opl = ' id="' + header['filename'] + '"'
532         oph = '<h' + str(level+1) + ' class="clear"' + opl +'>' + header['title'] + '</h' + str(level+1) + '>\n';
533
534
535         # Make the 'this thing contains...' stuff
536         if HaveChildren(fileStruct, pageNumber):
537                 pages = GetChildren(fileStruct, pageNumber)
538
539                 for pg in pages:
540                         more = more + '<li>' + '<a href="/' + fileStruct[pg]['filename'] + '/">' + fileStruct[pg]['title'] + '</a>' + '</li>\n'
541
542                 more = '<div id=subtopics>\n' + '<h2>This section contains the following topics:</h2>\n' + '<ul>\n' + more + '</ul>\n' + '</div>\n'
543
544         parent = GetParent(fileStruct, pageNumber)
545
546         # Make the 'Previous', 'Up' & 'Next' content
547         nLink = ''
548         pLink = ''
549         uLink = ''
550
551         if pageNumber > 0:
552                 pLink = '<li class="previous"><a title="' + fileStruct[pageNumber - 1]['title'] + '" href="/' + fileStruct[pageNumber - 1]['filename'] + '/" class="previous"> &larr; Previous </a></li>'
553
554         if pageNumber < len(fileStruct) - 1:
555                 nLink = '<li class="next"><a title="' + fileStruct[pageNumber + 1]['title'] + '" href="/' + fileStruct[pageNumber + 1]['filename'] + '/" class="next"> Next &rarr; </a></li>'
556
557         if level > 0:
558                 uLink = '<li><a title="' + fileStruct[parent]['title'] + '" href="/' + fileStruct[parent]['filename'] + '/" class="active"> &uarr; Up </a></li>'
559         else:
560                 uLink = '<li><a title="Ardour Table of Contents" href="/toc/index.html" class="active"> &uarr; Up </a></li>'
561
562         prevnext = '<ul class="pager">' + pLink + uLink + nLink + '</ul>'
563
564         # Make the BreadCrumbs
565         breadcrumbs = GetBreadCrumbs(fileStruct, pageNumber)
566
567         # Create the link sidebar
568         sidebar = CreateLinkSidebar(fileStruct, pageNumber, nodeChildren)
569
570         # Parts DO NOT have any content, they are ONLY an organizing construct!
571         # Chapters, subchapters, sections & subsections can all have content,
572         # but the basic fundamental organizing unit WRT content is still the
573         # chapter.
574         githubedit = ''
575
576         if level > 0:
577                 if 'include' in header:
578                         srcFile = open('include/' + header['include'])
579                         githubedit = '<span style="float:right;"><a title="Edit in GitHub" href="' + global_githuburl + header['include'] + '"><img src="/images/github.png" alt="Edit in GitHub"/></a></span>'
580                         content = srcFile.read()
581                         srcFile.close()
582
583                         # Get rid of any extant header in the include file
584                         # (once this is accepted, we can nuke this bit, as content files
585                         # will not have any headers or footers in them)
586                         content = re.sub('---.*\n(.*\n)*---.*\n', '', content)
587                         content = content.replace('{% children %}', '')
588
589                 else:
590                         if 'content' in header:
591                                 content = header['content']
592                         else:
593                                 content = '[something went wrong]'
594
595         # Add header information to the page if in dev mode
596         if devmode:
597                 devnote ='<aside style="background-color:indigo; color:white;">'
598
599                 if 'filename' in header:
600                         devnote = devnote + 'filename: ' + header['filename'] + '<br>'
601
602                 if 'include' in header:
603                         devnote = devnote + 'include: ' + header['include'] + '<br>'
604
605                 if 'link' in header:
606                         devnote = devnote + 'link: ' + header['link'] + '<br>'
607
608                 content = devnote + '</aside>' + content
609
610         # ----- One page and PDF version -----
611
612         # Fix up any internal links
613         opcontent = FixInternalLinks(oplinks, content, header['title'])
614         opcontent = reheader(opcontent, 2)
615
616         # Set up the actual page from the template
617         onepage = onepage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
618         if not nopdf:
619                 pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
620
621         # ----- Normal version -----
622
623         # Fix up any internal links
624         content = FixInternalLinks(links, content, header['title'])
625
626         # Set up the actual page from the template
627         if 'style' not in header:
628                 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
629         else:
630                 page = template.replace('{{page.style}}', header['style'])
631                 page = page.replace('{% if page.style %}', '')
632                 page = page.replace('{% endif %}', '')
633
634         page = page.replace('{{ page.title }}', header['title'])
635         page = page.replace('{% tree %}', sidebar)
636         page = page.replace('{% prevnext %}', prevnext)
637         page = page.replace('{% githubedit %}', githubedit)
638         page = page.replace('{% breadcrumbs %}', breadcrumbs)
639         page = page.replace('{{ content }}', content + more)
640
641         # Create the directory for the index.html file to go into (we use makedirs,
642         # because we have to in order to accomodate the 'uri' keyword)
643         os.makedirs(global_site_dir + header['filename'], 0o775, exist_ok=True)
644
645         # Finally, write the file!
646         destFile = open(global_site_dir + header['filename'] + '/index.html', 'w')
647         destFile.write(page)
648         destFile.close()
649
650         # Save filename for next header...
651         lastFile = header['filename']
652         pageNumber = pageNumber + 1
653
654 # Finally, create the TOC
655 sidebar = CreateLinkSidebar(fileStruct, -1, nodeChildren)
656
657 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
658 page = page.replace('{{ page.title }}', 'Ardour Table of Contents')
659 page = page.replace('{% tree %}', sidebar)
660 page = page.replace('{{ content }}', toc)
661 page = page.replace('{% prevnext %}', '')
662 page = page.replace('{% githubedit %}', '')
663 page = page.replace('{% breadcrumbs %}', '')
664
665 os.mkdir(global_site_dir + 'toc', 0o775)
666 tocFile = open(global_site_dir + 'toc/index.html', 'w')
667 tocFile.write(page)
668 tocFile.close()
669
670 # Create the one-page version of the documentation
671 onepageFile = open(global_site_dir + 'ardourmanual.html', 'w')
672 opsidebar = BuildOnePageSidebar(fileStruct) # create the link sidebar
673 onepage = onepage.replace('{% tree %}', opsidebar)
674 onepage = onepage.replace('{{ content }}', '') # cleans up the last spaceholder
675 onepageFile.write(onepage)
676 onepageFile.close()
677
678 if not nopdf:
679         if not quiet:
680                 print('Generating the PDF...')
681
682         # Create the PDF version of the documentation
683         pdfpage = pdfpage.replace('{% tree %}', opsidebar) # create the TOC
684         pdfpage = pdfpage.replace('{{ content }}', '') # cleans up the last spaceholder
685         pdfpage = pdfpage.replace('src="/images/', 'src="images/') # makes images links relative
686         pdfpage = pdfpage.replace('url(\'/images/', 'url(\'images/') # CSS images links relative
687         # Write it to disk (optional, can be removed)
688         pdfpageFile = open(global_site_dir + 'pdf.html', 'w')
689         pdfpageFile.write(pdfpage)
690         pdfpageFile.close()
691
692         # Generating the actual PDF with weasyprint (https://weasyprint.org/)
693         from weasyprint import HTML
694         #from weasyprint.fonts import FontConfiguration
695         #html_font_config = FontConfiguration()
696         doc = HTML(string = pdfpage, base_url = global_site_dir)
697         doc.write_pdf(global_site_dir + 'manual.pdf')#, font_config = html_font_config)
698
699 if not quiet:
700         print('Processed ' + str(fileCount) + ' files.')
701