File: Factory.cpp

package info (click to toggle)
freespace2 24.2.0%2Brepack-3
  • links: PTS, VCS
  • area: non-free
  • in suites: forky, sid
  • size: 43,740 kB
  • sloc: cpp: 595,005; ansic: 21,741; python: 1,174; sh: 457; makefile: 243; xml: 181
file content (585 lines) | stat: -rw-r--r-- 19,353 bytes parent folder | download | duplicates (2)
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
/*
 * This source file is part of libRocket, the HTML/CSS Interface Middleware
 *
 * For the latest information, see http://www.librocket.com
 *
 * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#include "precompiled.h"
#include "../../Include/Rocket/Core.h"
#include "../../Include/Rocket/Core/StreamMemory.h"
#include "ContextInstancerDefault.h"
#include "DecoratorNoneInstancer.h"
#include "DecoratorTiledBoxInstancer.h"
#include "DecoratorTiledHorizontalInstancer.h"
#include "DecoratorTiledImageInstancer.h"
#include "DecoratorTiledVerticalInstancer.h"
#include "ElementHandle.h"
#include "ElementImage.h"
#include "ElementTextDefault.h"
#include "EventInstancerDefault.h"
#include "FontEffectNoneInstancer.h"
#include "FontEffectOutlineInstancer.h"
#include "FontEffectShadowInstancer.h"
#include "PluginRegistry.h"
#include "PropertyParserColour.h"
#include "../../Include/Rocket/Core/StreamFile.h"
#include "StyleSheetFactory.h"
#include "TemplateCache.h"
#include "XMLNodeHandlerBody.h"
#include "XMLNodeHandlerDefault.h"
#include "XMLNodeHandlerHead.h"
#include "XMLNodeHandlerTemplate.h"
#include "../../Include/Rocket/Core/XMLParseTools.h"

namespace Rocket {
namespace Core {

// Element instancers.
typedef std::map< String, ElementInstancer* > ElementInstancerMap;
static ElementInstancerMap element_instancers;

// Decorator instancers.
typedef std::map< String, DecoratorInstancer* > DecoratorInstancerMap;
static DecoratorInstancerMap decorator_instancers;

// Font effect instancers.
typedef std::map< String, FontEffectInstancer* > FontEffectInstancerMap;
static FontEffectInstancerMap font_effect_instancers;

// The context instancer.
static ContextInstancer* context_instancer = NULL;

// The event instancer
static EventInstancer* event_instancer = NULL;

// Event listener instancer.
static EventListenerInstancer* event_listener_instancer = NULL;

Factory::Factory()
{
}

Factory::~Factory()
{
}

bool Factory::Initialise()
{
	// Bind the default context instancer.
	if (context_instancer == NULL)
		context_instancer = new ContextInstancerDefault();

	// Bind default event instancer
	if (event_instancer == NULL)
		event_instancer = new EventInstancerDefault();

	// No default event listener instancer
	if (event_listener_instancer == NULL)
		event_listener_instancer = NULL;

	// Bind the default element instancers
	RegisterElementInstancer("*", new ElementInstancerGeneric< Element >())->RemoveReference();
	RegisterElementInstancer("img", new ElementInstancerGeneric< ElementImage >())->RemoveReference();
	RegisterElementInstancer("#text", new ElementInstancerGeneric< ElementTextDefault >())->RemoveReference();
	RegisterElementInstancer("handle", new ElementInstancerGeneric< ElementHandle >())->RemoveReference();
	RegisterElementInstancer("body", new ElementInstancerGeneric< ElementDocument >())->RemoveReference();

	// Bind the default decorator instancers
	RegisterDecoratorInstancer("tiled-horizontal", new DecoratorTiledHorizontalInstancer())->RemoveReference();
	RegisterDecoratorInstancer("tiled-vertical", new DecoratorTiledVerticalInstancer())->RemoveReference();
	RegisterDecoratorInstancer("tiled-box", new DecoratorTiledBoxInstancer())->RemoveReference();
	RegisterDecoratorInstancer("image", new DecoratorTiledImageInstancer())->RemoveReference();
	RegisterDecoratorInstancer("none", new DecoratorNoneInstancer())->RemoveReference();

	RegisterFontEffectInstancer("shadow", new FontEffectShadowInstancer())->RemoveReference();
	RegisterFontEffectInstancer("outline", new FontEffectOutlineInstancer())->RemoveReference();
	RegisterFontEffectInstancer("none", new FontEffectNoneInstancer())->RemoveReference();

	// Register the core XML node handlers.
	XMLParser::RegisterNodeHandler("", new XMLNodeHandlerDefault())->RemoveReference();
	XMLParser::RegisterNodeHandler("body", new XMLNodeHandlerBody())->RemoveReference();
	XMLParser::RegisterNodeHandler("head", new XMLNodeHandlerHead())->RemoveReference();
	XMLParser::RegisterNodeHandler("template", new XMLNodeHandlerTemplate())->RemoveReference();

	return true;
}

void Factory::Shutdown()
{
	for (ElementInstancerMap::iterator i = element_instancers.begin(); i != element_instancers.end(); ++i)
		(*i).second->RemoveReference();
	element_instancers.clear();

	for (DecoratorInstancerMap::iterator i = decorator_instancers.begin(); i != decorator_instancers.end(); ++i)
		(*i).second->RemoveReference();
	decorator_instancers.clear();

	for (FontEffectInstancerMap::iterator i = font_effect_instancers.begin(); i != font_effect_instancers.end(); ++i)
		(*i).second->RemoveReference();
	font_effect_instancers.clear();

	if (context_instancer)
		context_instancer->RemoveReference();
	context_instancer = NULL;

	if (event_listener_instancer)
		event_listener_instancer->RemoveReference();
	event_listener_instancer = NULL;

	if (event_instancer)
		event_instancer->RemoveReference();
	event_instancer = NULL;

	XMLParser::ReleaseHandlers();
}

// Registers the instancer to use when instancing contexts.
ContextInstancer* Factory::RegisterContextInstancer(ContextInstancer* instancer)
{
	instancer->AddReference();
	if (context_instancer != NULL)
		context_instancer->RemoveReference();

	context_instancer = instancer;
	return instancer;
}

// Instances a new context.
Context* Factory::InstanceContext(const String& name)
{
	Context* new_context = context_instancer->InstanceContext(name);
	if (new_context != NULL)
		new_context->SetInstancer(context_instancer);

	return new_context;
}

ElementInstancer* Factory::RegisterElementInstancer(const String& name, ElementInstancer* instancer)
{
	String lower_case_name = name.ToLower();
	instancer->AddReference();

	// Check if an instancer for this tag is already defined, if so release it
	ElementInstancerMap::iterator itr = element_instancers.find(lower_case_name);
	if (itr != element_instancers.end())
	{
		(*itr).second->RemoveReference();
	}

	element_instancers[lower_case_name] = instancer;
	return instancer;
}

// Looks up the instancer for the given element
ElementInstancer* Factory::GetElementInstancer(const String& tag)
{
	ElementInstancerMap::iterator instancer_iterator = element_instancers.find(tag);
	if (instancer_iterator == element_instancers.end())
	{
		instancer_iterator = element_instancers.find("*");
		if (instancer_iterator == element_instancers.end())
			return NULL;
	}

	return (*instancer_iterator).second;
}

// Instances a single element.
Element* Factory::InstanceElement(Element* parent, const String& instancer_name, const String& tag, const XMLAttributes& attributes)
{
	ElementInstancer* instancer = GetElementInstancer(instancer_name);

	if (instancer)
	{
		Element* element = instancer->InstanceElement(parent, tag, attributes);		

		// Process the generic attributes and bind any events
		if (element)
		{
			element->SetInstancer(instancer);
			element->SetAttributes(&attributes);
			ElementUtilities::BindEventAttributes(element);

			PluginRegistry::NotifyElementCreate(element);
		}

		return element;
	}

	return NULL;
}

// Instances a single text element containing a string.
bool Factory::InstanceElementText(Element* parent, const String& text)
{
	SystemInterface* system_interface = GetSystemInterface();

	// Do any necessary translation. If any substitutions were made then new XML may have been introduced, so we'll
	// have to run the data through the XML parser again.
	String translated_data;
	if (system_interface != NULL &&
		(system_interface->TranslateString(translated_data, text) > 0 ||
		 translated_data.Find("<") != String::npos))
	{
		StreamMemory* stream = new StreamMemory(translated_data.Length() + 32);
		stream->Write("<body>", 6);
		stream->Write(translated_data);
		stream->Write("</body>", 7);
		stream->Seek(0, SEEK_SET);

		InstanceElementStream(parent, stream);
		stream->RemoveReference();
	}
	else
	{
		// Check if this text node contains only white-space; if so, we don't want to construct it.
		bool only_white_space = true;
		for (size_t i = 0; i < translated_data.Length(); ++i)
		{
			if (!StringUtilities::IsWhitespace(translated_data[i]))
			{
				only_white_space = false;
				break;
			}
		}

		if (only_white_space)
			return true;

		// Attempt to instance the element.
		XMLAttributes attributes;
		Element* element = Factory::InstanceElement(parent, "#text", "#text", attributes);
		if (!element)
		{
			Log::Message(Log::LT_ERROR, "Failed to instance text element '%s', instancer returned NULL.", translated_data.CString());
			return false;
		}

		// Assign the element its text value.
		ElementText* text_element = dynamic_cast< ElementText* >(element);
		if (text_element == NULL)
		{
			Log::Message(Log::LT_ERROR, "Failed to instance text element '%s'. Found type '%s', was expecting a derivative of ElementText.", translated_data.CString(), typeid(element).name());
			element->RemoveReference();
			return false;
		}

		text_element->SetText(translated_data);

		// Add to active node.
		parent->AppendChild(element);
		element->RemoveReference();
	}

	return true;
}

// Instances a element tree based on the stream
bool Factory::InstanceElementStream(Element* parent, Stream* stream)
{
	XMLParser parser(parent);
	parser.Parse(stream);
	return true;
}

// Instances a element tree based on the stream
ElementDocument* Factory::InstanceDocumentStream(Rocket::Core::Context* context, Stream* stream)
{
	Element* element = Factory::InstanceElement(NULL, "body", "body", XMLAttributes());
	if (!element)
	{
		Log::Message(Log::LT_ERROR, "Failed to instance document, instancer returned NULL.");
		return NULL;
	}

	ElementDocument* document = dynamic_cast< ElementDocument* >(element);
	if (!document)
	{
		Log::Message(Log::LT_ERROR, "Failed to instance document element. Found type '%s', was expecting derivative of ElementDocument.", typeid(element).name());
		return NULL;
	}

	document->lock_layout = true;
	document->context = context;

	XMLParser parser(element);
	parser.Parse(stream);

	document->lock_layout = false;

	return document;
}

// Registers an instancer that will be used to instance decorators.
DecoratorInstancer* Factory::RegisterDecoratorInstancer(const String& name, DecoratorInstancer* instancer)
{
	String lower_case_name = name.ToLower();
	instancer->AddReference();

	// Check if an instancer for this tag is already defined. If so, release it.
	DecoratorInstancerMap::iterator iterator = decorator_instancers.find(lower_case_name);
	if (iterator != decorator_instancers.end())
		(*iterator).second->RemoveReference();

	decorator_instancers[lower_case_name] = instancer;
	return instancer;
}

// Attempts to instance a decorator from an instancer registered with the factory.
Decorator* Factory::InstanceDecorator(const String& name, const PropertyDictionary& properties)
{
	float z_index = 0;
	int specificity = -1;

	DecoratorInstancerMap::iterator iterator = decorator_instancers.find(name);
	if (iterator == decorator_instancers.end())
		return NULL;

	// Turn the generic, un-parsed properties we've got into a properly parsed dictionary.
	const PropertySpecification& property_specification = (*iterator).second->GetPropertySpecification();

	PropertyDictionary parsed_properties;
	for (PropertyMap::const_iterator i = properties.GetProperties().begin(); i != properties.GetProperties().end(); ++i)
	{
		specificity = Math::Max(specificity, (*i).second.specificity);

		// Check for the 'z-index' property; we don't want to send this through.
		if ((*i).first == Z_INDEX)
			z_index = (*i).second.value.Get< float >();
		else
			property_specification.ParsePropertyDeclaration(parsed_properties, (*i).first, (*i).second.value.Get< String >(), (*i).second.source, (*i).second.source_line_number);
	}

	// Set the property defaults for all unset properties.
	property_specification.SetPropertyDefaults(parsed_properties);

	Decorator* decorator = (*iterator).second->InstanceDecorator(name, parsed_properties);
	if (decorator == NULL)
		return NULL;

	decorator->SetZIndex(z_index);
	decorator->SetSpecificity(specificity);
	decorator->instancer = (*iterator).second;
	return decorator;
}

// Registers an instancer that will be used to instance font effects.
FontEffectInstancer* Factory::RegisterFontEffectInstancer(const String& name, FontEffectInstancer* instancer)
{
	String lower_case_name = name.ToLower();
	instancer->AddReference();

	// Check if an instancer for this tag is already defined. If so, release it.
	FontEffectInstancerMap::iterator iterator = font_effect_instancers.find(lower_case_name);
	if (iterator != font_effect_instancers.end())
		(*iterator).second->RemoveReference();

	font_effect_instancers[lower_case_name] = instancer;
	return instancer;
}

// Attempts to instance a font effect from an instancer registered with the factory.
FontEffect* Factory::InstanceFontEffect(const String& name, const PropertyDictionary& properties)
{
	bool set_colour = false;
	Colourb colour(255, 255, 255);

	bool set_z_index = false;
	float z_index = 0;

	int specificity = -1;

	FontEffectInstancerMap::iterator iterator = font_effect_instancers.find(name);
	if (iterator == font_effect_instancers.end())
		return NULL;

	FontEffectInstancer* instancer = iterator->second;

	// Turn the generic, un-parsed properties we've got into a properly parsed dictionary.
	const PropertySpecification& property_specification = (*iterator).second->GetPropertySpecification();

	PropertyDictionary parsed_properties;
	for (PropertyMap::const_iterator i = properties.GetProperties().begin(); i != properties.GetProperties().end(); ++i)
	{
		specificity = Math::Max(specificity, i->second.specificity);

		// Check for the 'z-index' property; we don't want to send this through.
		if (i->first == Z_INDEX)
		{
			set_z_index = true;
			z_index = i->second.value.Get< float >();
		}
		else if (i->first == COLOR)
		{
			static PropertyParserColour colour_parser;

			Property colour_property;
			if (colour_parser.ParseValue(colour_property, i->second.value.Get< String >(), ParameterMap()))
			{
				colour = colour_property.value.Get< Colourb >();
				set_colour = true;
			}
		}
		else
		{
			property_specification.ParsePropertyDeclaration(parsed_properties, (*i).first, (*i).second.value.Get< String >(), (*i).second.source, (*i).second.source_line_number);
		}
	}

	// Set the property defaults for all unset properties.
	property_specification.SetPropertyDefaults(parsed_properties);

	// Compile an ordered list of the values of the properties used to generate the effect's
	// textures and geometry.
	typedef std::list< std::pair< String, String > > GenerationPropertyList;
	GenerationPropertyList generation_properties;
	for (PropertyMap::const_iterator i = parsed_properties.GetProperties().begin(); i != parsed_properties.GetProperties().end(); ++i)
	{
		if (instancer->volatile_properties.find(i->first) != instancer->volatile_properties.end())
		{
			GenerationPropertyList::iterator j = generation_properties.begin();
			while (j != generation_properties.end() &&
				   j->first < i->first)
				++j;

			generation_properties.insert(j, GenerationPropertyList::value_type(i->first, i->second.value.Get< String >()));
		}
	}

	String generation_key;
	for (GenerationPropertyList::iterator i = generation_properties.begin(); i != generation_properties.end(); ++i)
	{
		generation_key += i->second;
		generation_key += ";";
	}

	// Now we can actually instance the effect!
	FontEffect* font_effect = (*iterator).second->InstanceFontEffect(name, parsed_properties);
	if (font_effect == NULL)
		return NULL;

	font_effect->name = name;
	font_effect->generation_key = generation_key;

	if (set_z_index)
		font_effect->SetZIndex(z_index);

	if (set_colour)
		font_effect->SetColour(colour);

	font_effect->SetSpecificity(specificity);
	font_effect->instancer = (*iterator).second;
	return font_effect;
}

// Creates a style sheet containing the passed in styles.
StyleSheet* Factory::InstanceStyleSheetString(const String& string)
{
	StreamMemory* memory_stream = new StreamMemory((const byte*) string.CString(), string.Length());
	StyleSheet* style_sheet = InstanceStyleSheetStream(memory_stream);
	memory_stream->RemoveReference();
	return style_sheet;
}

// Creates a style sheet from a file.
StyleSheet* Factory::InstanceStyleSheetFile(const String& file_name)
{
	StreamFile* file_stream = new StreamFile();
	file_stream->Open(file_name);
	StyleSheet* style_sheet = InstanceStyleSheetStream(file_stream);
	file_stream->RemoveReference();
	return style_sheet;
}

// Creates a style sheet from an Stream.
StyleSheet* Factory::InstanceStyleSheetStream(Stream* stream)
{
	StyleSheet* style_sheet = new StyleSheet();
	if (style_sheet->LoadStyleSheet(stream))
	{
		return style_sheet;
	}

	style_sheet->RemoveReference();
	return NULL;
}

// Clears the style sheet cache. This will force style sheets to be reloaded.
void Factory::ClearStyleSheetCache()
{
	StyleSheetFactory::ClearStyleSheetCache();
}

/// Clears the template cache. This will force templates to be reloaded.
void Factory::ClearTemplateCache()
{
	TemplateCache::Clear();
}

// Registers an instancer for all RKTEvents
EventInstancer* Factory::RegisterEventInstancer(EventInstancer* instancer)
{
	instancer->AddReference();

	if (event_instancer)
		event_instancer->RemoveReference();

	event_instancer = instancer;
	return instancer;
}

// Instance an event object.
Event* Factory::InstanceEvent(Element* target, const String& name, const Dictionary& parameters, bool interruptible)
{
	Event* event = event_instancer->InstanceEvent(target, name, parameters, interruptible);
	if (event != NULL)
		event->instancer = event_instancer;

	return event;
}

// Register an instancer for all event listeners
EventListenerInstancer* Factory::RegisterEventListenerInstancer(EventListenerInstancer* instancer)
{
	instancer->AddReference();

	if (event_listener_instancer)
		event_listener_instancer->RemoveReference();

	event_listener_instancer = instancer;
	return instancer;
}

// Instance an event listener with the given string
EventListener* Factory::InstanceEventListener(const String& value, Element* element)
{
	// If we have an event listener instancer, use it
	if (event_listener_instancer)
		return event_listener_instancer->InstanceEventListener(value, element);

	return NULL;
}

}
}