summaryrefslogtreecommitdiff
path: root/src/plugins/html/DemoOutput.cpp
blob: cefb3c9c25717a0ee0b8dc466e8a1287de0f7e3a (plain)
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
/*
    Ousía
    Copyright (C) 2014  Benjamin Paaßen, Andreas Stöckel

    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 <http://www.gnu.org/licenses/>.
*/

#include <stack>

#include <core/common/Exceptions.hpp>
#include <core/common/Rtti.hpp>
#include <core/common/Variant.hpp>

#include "DemoOutput.hpp"

namespace ousia {
namespace html {

void DemoHTMLTransformer::writeHTML(Handle<Document> doc,
                                    std::ostream &out, bool pretty)
{
	Manager &mgr = doc->getManager();
	// Create an XML object tree for the document first.
	Rooted<xml::Element> html{new xml::Element{mgr, {nullptr}, "html"}};
	// add the head Element
	Rooted<xml::Element> head{new xml::Element{mgr, html, "head"}};
	html->addChild(head);
	// add the meta element.
	Rooted<xml::Element> meta{
	    new xml::Element{mgr,
	                     head,
	                     "meta",
	                     {{"http-equiv", "Content-Type"},
	                      {"content", "text/html; charset=utf-8"}}}};
	head->addChild(meta);
	// add the title Element with Text
	Rooted<xml::Element> title{new xml::Element{mgr, head, "title"}};
	head->addChild(title);
	title->addChild(
	    new xml::Text(mgr, title, "Test HTML Output for " + doc->getName()));
	// add the body Element
	Rooted<xml::Element> body{new xml::Element{mgr, html, "body"}};
	html->addChild(body);

	// So far was the "preamble". No we have to get to the document content.

	// build the start and end map for annotation processing.
	AnnoMap startMap;
	AnnoMap endMap;
	for (auto &a : doc->getAnnotations()) {
		// we assume uniquely IDed annotations, which should be checked in the
		// validation process.
		startMap.emplace(a->getStart()->getName(), a);
		endMap.emplace(a->getEnd()->getName(), a);
	}

	// extract the book root node.
	Rooted<StructuredEntity> root = doc->getRoot();
	if (root->getDescriptor()->getName() != "book") {
		throw OusiaException("The given documents root is no book node!");
	}
	// transform the book node.
	Rooted<xml::Element> book = transformSection(body, root, startMap, endMap);
	// add it as child to the body node.
	body->addChild(book);

	// After the content has been transformed, we serialize it.
	html->serialize(out, "<!DOCTYPE html>", pretty);
}

/**
 * This is just for easier internal handling.
 */
enum class SectionType { BOOK, SECTION, SUBSECTION, NONE };

SectionType getSectionType(const std::string &name)
{
	if (name == "book") {
		return SectionType::BOOK;
	} else if (name == "section") {
		return SectionType::SECTION;
	} else if (name == "subsection") {
		return SectionType::SUBSECTION;
	} else {
		return SectionType::NONE;
	}
}

Rooted<xml::Element> DemoHTMLTransformer::transformSection(
    Handle<xml::Element> parent, Handle<StructuredEntity> section,
    AnnoMap &startMap, AnnoMap &endMap)
{
	Manager &mgr = section->getManager();
	// check the section type.
	const std::string secclass = section->getDescriptor()->getName();
	SectionType type = getSectionType(secclass);
	if (type == SectionType::NONE) {
		// if the input node is no section, we ignore it.
		return {nullptr};
	}
	// create a section tag containing the sections content.
	Rooted<xml::Element> sec{
	    new xml::Element{mgr, parent, "section", {{"class", secclass}}}};
	// check if we have a heading.
	if (section->hasField("heading") &&
	    section->getField("heading").size() > 0) {
		Handle<StructuredEntity> heading =
		    section->getField("heading")[0].cast<StructuredEntity>();
		std::string headingclass;
		switch (type) {
			case SectionType::BOOK:
				headingclass = "h1";
				break;
			case SectionType::SECTION:
				headingclass = "h2";
				break;
			case SectionType::SUBSECTION:
				headingclass = "h3";
				break;
			case SectionType::NONE:
				// this can not happen;
				break;
		}
		Rooted<xml::Element> h{new xml::Element{mgr, sec, headingclass}};
		sec->addChild(h);
		// extract the heading text, enveloped in a paragraph Element.
		Rooted<xml::Element> h_content =
		    transformParagraph(h, heading, startMap, endMap);
		// We omit the paragraph Element and add the children directly to the
		// heading Element
		for (auto &n : h_content->getChildren()) {
			h->addChild(n);
		}
	}

	// Then we get all the children.
	for (auto &n : section->getField()) {
		if (!n->isa(RttiTypes::StructuredEntity)) {
			continue;
		}
		Handle<StructuredEntity> s = n.cast<StructuredEntity>();
		/*
		 * Strictly speaking this is the wrong mechanism, because we would have
		 * to make an "isa" call here because we can not rely on our knowledge
		 * that paragraphs can only be paragraphs or lists. There would have
		 * to be a listener structure of transformations that check if they can
		 * transform this specific node.
		 */
		const std::string childDescriptorName = s->getDescriptor()->getName();
		Rooted<xml::Element> child;
		if (childDescriptorName == "paragraph") {
			child = transformParagraph(sec, s, startMap, endMap);
		} else if (childDescriptorName == "ul" || childDescriptorName == "ol") {
			child = transformList(sec, s, startMap, endMap);
		} else {
			child = transformSection(sec, s, startMap, endMap);
		}
		if (!child.isNull()) {
			sec->addChild(child);
		}
	}
	return sec;
}

Rooted<xml::Element> DemoHTMLTransformer::transformList(
    Handle<xml::Element> parent, Handle<StructuredEntity> list,
    AnnoMap &startMap, AnnoMap &endMap)
{
	Manager &mgr = list->getManager();
	// create the list Element, which is either ul or ol (depends on descriptor)
	std::string listclass = list->getDescriptor()->getName();
	Rooted<xml::Element> l{new xml::Element{mgr, parent, listclass}};
	// iterate through list items.
	for (auto &it : list->getField()) {
		Handle<StructuredEntity> item =
		    it.cast<StructuredEntity>();
		std::string itDescrName = item->getDescriptor()->getName();
		if (itDescrName == "item") {
			// create the list item.
			Rooted<xml::Element> li{new xml::Element{mgr, l, "li"}};
			l->addChild(li);
			// extract the item text, enveloped in a paragraph Element.
			Rooted<xml::Element> li_content =
			    transformParagraph(li, item, startMap, endMap);
			// We omit the paragraph Element and add the children directly to
			// the list item
			for (auto &n : li_content->getChildren()) {
				li->addChild(n);
			}
		}
	}
	return l;
}

typedef std::stack<Rooted<AnnotationEntity>> AnnoStack;

static Rooted<xml::Element> openAnnotation(
    Manager &mgr, AnnoStack &opened, Handle<AnnotationEntity> entity,
    Handle<xml::Element> current)
{
	// we push the newly opened entity on top of the stack.
	opened.push(entity);
	// get the elment name
	std::string elemName = entity->getDescriptor()->getName();
	// emphasized has to be shortened
	if (elemName == "emphasized") {
		elemName = "em";
	}
	// create the new XML element representing the annotation
	Rooted<xml::Element> tmp{new xml::Element{mgr, current, elemName}};
	current->addChild(tmp);
	// and return it.
	return tmp;
}

Rooted<xml::Element> DemoHTMLTransformer::transformParagraph(
    Handle<xml::Element> parent, Handle<StructuredEntity> par,
    AnnoMap &startMap, AnnoMap &endMap)
{
	Manager &mgr = par->getManager();
	// create the p Element
	Rooted<xml::Element> p{new xml::Element{mgr, parent, "p"}};

	// check if we have a heading.
	if (par->hasField("heading") && par->getField("heading").size() > 0) {
		Handle<StructuredEntity> heading =
		    par->getField("heading")[0].cast<StructuredEntity>();
		// put the heading in a strong xml::Element.
		Rooted<xml::Element> strong{new xml::Element{mgr, p, "strong"}};
		p->addChild(strong);
		// extract the heading text, enveloped in a paragraph Element.
		Rooted<xml::Element> h_content =
		    transformParagraph(strong, heading, startMap, endMap);
		// We omit the paragraph Element and add the children directly to the
		// heading Element
		for (auto &n : h_content->getChildren()) {
			strong->addChild(n);
		}
	}

	// transform paragraph children to XML as well
	/*
	 * We need a stack of AnnotationEntities that are currently open.
	 * In principle we wouldn't, because the nested structure of XML elements
	 * provides a stack-like structure anyways, but we need to have a mapping of
	 * XML tags to AnnotationEntities, which is implicitly provided by this
	 * stack.
	 */
	AnnoStack opened;
	// this is a handle for our current XML element for annotation handling.
	Rooted<xml::Element> current = p;
	for (auto &n : par->getField()) {
		if (n->isa(RttiTypes::Anchor)) {
			// check if this is a start Anchor.
			// here we assume, again, that the ids/names of anchors are unique.
			auto it = startMap.find(n->getName());
			if (it != startMap.end()) {
				// if we have a start anchor, we open an annotation element.
				current = openAnnotation(mgr, opened, it->second, current);
				continue;
			}
			// check if this is an end Anchor.
			auto it2 = endMap.find(n->getName());
			if (it2 != endMap.end()) {
				/*
				 * Now it gets somewhat interesting: We have to close all
				 * tags that started after the one that is closed now and
				 * re-open them afterwards. So we create a lokal stack to
				 * temporarily store all AnnotationEntities that need to
				 * be re-opened.
				 */
				AnnoStack tmp;
				Rooted<AnnotationEntity> closed = opened.top();
				current = current->getParent();
				opened.pop();
				while (closed->getEnd()->getName() != n->getName()) {
					/*
					 * We implicitly do close tags by climbing up the XML tree
					 * until we are at the right element.
					 */
					current = current->getParent();
					tmp.push(closed);
					if (opened.empty()) {
						// if we have no opened entities left, that is a
						// malformed document.
						throw OusiaException("An unopened entity was closed!");
					}
					closed = opened.top();
					opened.pop();
				}
				// At this point we have closed all necessary entities. Now we
				// need to re-open some of them.
				while (!tmp.empty()) {
					closed = tmp.top();
					tmp.pop();
					current = openAnnotation(mgr, opened, closed, current);
				}
			}
			continue;
		}
		// if this is not an anchor, we can only handle text.
		if (!n->isa(RttiTypes::StructuredEntity)) {
			continue;
		}
		Handle<StructuredEntity> t = n.cast<StructuredEntity>();

		std::string childDescriptorName = t->getDescriptor()->getName();
		if (childDescriptorName == "text") {
			Handle<DocumentPrimitive> primitive =
			    t->getField("content")[0].cast<DocumentPrimitive>();
			if (primitive.isNull()) {
				throw OusiaException("Text field is not primitive!");
			}
			current->addChild(new xml::Text(
			    mgr, current, primitive->getContent().asString()));
		}
	}
	return p;
}
}
}