Factory.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. /*
  2. * This source file is part of libRocket, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://www.librocket.com
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. *
  26. */
  27. #include "precompiled.h"
  28. #include "../../Include/Rocket/Core.h"
  29. #include "../../Include/Rocket/Core/StreamMemory.h"
  30. #include "ContextInstancerDefault.h"
  31. #include "DecoratorNoneInstancer.h"
  32. #include "DecoratorTiledBoxInstancer.h"
  33. #include "DecoratorTiledHorizontalInstancer.h"
  34. #include "DecoratorTiledImageInstancer.h"
  35. #include "DecoratorTiledVerticalInstancer.h"
  36. #include "ElementHandle.h"
  37. #include "ElementImage.h"
  38. #include "ElementTextDefault.h"
  39. #include "EventInstancerDefault.h"
  40. #include "FontEffectNoneInstancer.h"
  41. #include "FontEffectOutlineInstancer.h"
  42. #include "FontEffectShadowInstancer.h"
  43. #include "PluginRegistry.h"
  44. #include "PropertyParserColour.h"
  45. #include "StreamFile.h"
  46. #include "StyleSheetFactory.h"
  47. #include "TemplateCache.h"
  48. #include "XMLNodeHandlerBody.h"
  49. #include "XMLNodeHandlerDefault.h"
  50. #include "XMLNodeHandlerHead.h"
  51. #include "XMLNodeHandlerTemplate.h"
  52. #include "XMLParseTools.h"
  53. namespace Rocket {
  54. namespace Core {
  55. // Element instancers.
  56. typedef UnorderedMap< String, ElementInstancer* > ElementInstancerMap;
  57. static ElementInstancerMap element_instancers;
  58. // Decorator instancers.
  59. typedef UnorderedMap< String, DecoratorInstancer* > DecoratorInstancerMap;
  60. static DecoratorInstancerMap decorator_instancers;
  61. // Font effect instancers.
  62. typedef UnorderedMap< String, FontEffectInstancer* > FontEffectInstancerMap;
  63. static FontEffectInstancerMap font_effect_instancers;
  64. // The context instancer.
  65. static ContextInstancer* context_instancer = NULL;
  66. // The event instancer
  67. static EventInstancer* event_instancer = NULL;
  68. // Event listener instancer.
  69. static EventListenerInstancer* event_listener_instancer = NULL;
  70. Factory::Factory()
  71. {
  72. }
  73. Factory::~Factory()
  74. {
  75. }
  76. bool Factory::Initialise()
  77. {
  78. // Bind the default context instancer.
  79. if (context_instancer == NULL)
  80. context_instancer = new ContextInstancerDefault();
  81. // Bind default event instancer
  82. if (event_instancer == NULL)
  83. event_instancer = new EventInstancerDefault();
  84. // No default event listener instancer
  85. if (event_listener_instancer == NULL)
  86. event_listener_instancer = NULL;
  87. // Bind the default element instancers
  88. RegisterElementInstancer("*", new ElementInstancerGeneric< Element >())->RemoveReference();
  89. RegisterElementInstancer("img", new ElementInstancerGeneric< ElementImage >())->RemoveReference();
  90. RegisterElementInstancer("#text", new ElementInstancerGeneric< ElementTextDefault >())->RemoveReference();
  91. RegisterElementInstancer("handle", new ElementInstancerGeneric< ElementHandle >())->RemoveReference();
  92. RegisterElementInstancer("body", new ElementInstancerGeneric< ElementDocument >())->RemoveReference();
  93. // Bind the default decorator instancers
  94. RegisterDecoratorInstancer("tiled-horizontal", new DecoratorTiledHorizontalInstancer())->RemoveReference();
  95. RegisterDecoratorInstancer("tiled-vertical", new DecoratorTiledVerticalInstancer())->RemoveReference();
  96. RegisterDecoratorInstancer("tiled-box", new DecoratorTiledBoxInstancer())->RemoveReference();
  97. RegisterDecoratorInstancer("image", new DecoratorTiledImageInstancer())->RemoveReference();
  98. RegisterDecoratorInstancer("none", new DecoratorNoneInstancer())->RemoveReference();
  99. RegisterFontEffectInstancer("shadow", new FontEffectShadowInstancer())->RemoveReference();
  100. RegisterFontEffectInstancer("outline", new FontEffectOutlineInstancer())->RemoveReference();
  101. RegisterFontEffectInstancer("none", new FontEffectNoneInstancer())->RemoveReference();
  102. // Register the core XML node handlers.
  103. XMLParser::RegisterNodeHandler("", new XMLNodeHandlerDefault())->RemoveReference();
  104. XMLParser::RegisterNodeHandler("body", new XMLNodeHandlerBody())->RemoveReference();
  105. XMLParser::RegisterNodeHandler("head", new XMLNodeHandlerHead())->RemoveReference();
  106. XMLParser::RegisterNodeHandler("template", new XMLNodeHandlerTemplate())->RemoveReference();
  107. return true;
  108. }
  109. void Factory::Shutdown()
  110. {
  111. for (ElementInstancerMap::iterator i = element_instancers.begin(); i != element_instancers.end(); ++i)
  112. (*i).second->RemoveReference();
  113. element_instancers.clear();
  114. for (DecoratorInstancerMap::iterator i = decorator_instancers.begin(); i != decorator_instancers.end(); ++i)
  115. (*i).second->RemoveReference();
  116. decorator_instancers.clear();
  117. for (FontEffectInstancerMap::iterator i = font_effect_instancers.begin(); i != font_effect_instancers.end(); ++i)
  118. (*i).second->RemoveReference();
  119. font_effect_instancers.clear();
  120. if (context_instancer)
  121. context_instancer->RemoveReference();
  122. context_instancer = NULL;
  123. if (event_listener_instancer)
  124. event_listener_instancer->RemoveReference();
  125. event_listener_instancer = NULL;
  126. if (event_instancer)
  127. event_instancer->RemoveReference();
  128. event_instancer = NULL;
  129. XMLParser::ReleaseHandlers();
  130. }
  131. // Registers the instancer to use when instancing contexts.
  132. ContextInstancer* Factory::RegisterContextInstancer(ContextInstancer* instancer)
  133. {
  134. instancer->AddReference();
  135. if (context_instancer != NULL)
  136. context_instancer->RemoveReference();
  137. context_instancer = instancer;
  138. return instancer;
  139. }
  140. // Instances a new context.
  141. Context* Factory::InstanceContext(const String& name)
  142. {
  143. Context* new_context = context_instancer->InstanceContext(name);
  144. if (new_context != NULL)
  145. new_context->SetInstancer(context_instancer);
  146. return new_context;
  147. }
  148. ElementInstancer* Factory::RegisterElementInstancer(const String& name, ElementInstancer* instancer)
  149. {
  150. String lower_case_name = ToLower(name);
  151. instancer->AddReference();
  152. // Check if an instancer for this tag is already defined, if so release it
  153. ElementInstancerMap::iterator itr = element_instancers.find(lower_case_name);
  154. if (itr != element_instancers.end())
  155. {
  156. (*itr).second->RemoveReference();
  157. }
  158. element_instancers[lower_case_name] = instancer;
  159. return instancer;
  160. }
  161. // Looks up the instancer for the given element
  162. ElementInstancer* Factory::GetElementInstancer(const String& tag)
  163. {
  164. ElementInstancerMap::iterator instancer_iterator = element_instancers.find(tag);
  165. if (instancer_iterator == element_instancers.end())
  166. {
  167. instancer_iterator = element_instancers.find("*");
  168. if (instancer_iterator == element_instancers.end())
  169. return NULL;
  170. }
  171. return (*instancer_iterator).second;
  172. }
  173. // Instances a single element.
  174. Element* Factory::InstanceElement(Element* parent, const String& instancer_name, const String& tag, const XMLAttributes& attributes)
  175. {
  176. ElementInstancer* instancer = GetElementInstancer(instancer_name);
  177. if (instancer)
  178. {
  179. Element* element = instancer->InstanceElement(parent, tag, attributes);
  180. // Process the generic attributes and bind any events
  181. if (element)
  182. {
  183. element->SetInstancer(instancer);
  184. element->SetAttributes(&attributes);
  185. ElementUtilities::BindEventAttributes(element);
  186. PluginRegistry::NotifyElementCreate(element);
  187. }
  188. return element;
  189. }
  190. return NULL;
  191. }
  192. // Instances a single text element containing a string.
  193. bool Factory::InstanceElementText(Element* parent, const String& text)
  194. {
  195. SystemInterface* system_interface = GetSystemInterface();
  196. // Do any necessary translation. If any substitutions were made then new XML may have been introduced, so we'll
  197. // have to run the data through the XML parser again.
  198. String translated_data;
  199. if (system_interface != NULL &&
  200. (system_interface->TranslateString(translated_data, text) > 0 ||
  201. translated_data.find("<") != String::npos))
  202. {
  203. StreamMemory* stream = new StreamMemory(translated_data.size() + 32);
  204. stream->Write("<body>", 6);
  205. stream->Write(translated_data);
  206. stream->Write("</body>", 7);
  207. stream->Seek(0, SEEK_SET);
  208. InstanceElementStream(parent, stream);
  209. stream->RemoveReference();
  210. }
  211. else
  212. {
  213. // Check if this text node contains only white-space; if so, we don't want to construct it.
  214. bool only_white_space = true;
  215. for (size_t i = 0; i < translated_data.size(); ++i)
  216. {
  217. if (!StringUtilities::IsWhitespace(translated_data[i]))
  218. {
  219. only_white_space = false;
  220. break;
  221. }
  222. }
  223. if (only_white_space)
  224. return true;
  225. // Attempt to instance the element.
  226. XMLAttributes attributes;
  227. Element* element = Factory::InstanceElement(parent, "#text", "#text", attributes);
  228. if (!element)
  229. {
  230. Log::Message(Log::LT_ERROR, "Failed to instance text element '%s', instancer returned NULL.", translated_data.c_str());
  231. return false;
  232. }
  233. // Assign the element its text value.
  234. ElementText* text_element = dynamic_cast< ElementText* >(element);
  235. if (text_element == NULL)
  236. {
  237. Log::Message(Log::LT_ERROR, "Failed to instance text element '%s'. Found type '%s', was expecting a derivative of ElementText.", translated_data.c_str(), typeid(element).name());
  238. element->RemoveReference();
  239. return false;
  240. }
  241. text_element->SetText(ToWideString(translated_data));
  242. // Add to active node.
  243. parent->AppendChild(element);
  244. element->RemoveReference();
  245. }
  246. return true;
  247. }
  248. // Instances a element tree based on the stream
  249. bool Factory::InstanceElementStream(Element* parent, Stream* stream)
  250. {
  251. XMLParser parser(parent);
  252. parser.Parse(stream);
  253. return true;
  254. }
  255. // Instances a element tree based on the stream
  256. ElementDocument* Factory::InstanceDocumentStream(Rocket::Core::Context* context, Stream* stream)
  257. {
  258. Element* element = Factory::InstanceElement(NULL, "body", "body", XMLAttributes());
  259. if (!element)
  260. {
  261. Log::Message(Log::LT_ERROR, "Failed to instance document, instancer returned NULL.");
  262. return NULL;
  263. }
  264. ElementDocument* document = dynamic_cast< ElementDocument* >(element);
  265. if (!document)
  266. {
  267. Log::Message(Log::LT_ERROR, "Failed to instance document element. Found type '%s', was expecting derivative of ElementDocument.", typeid(element).name());
  268. return NULL;
  269. }
  270. document->context = context;
  271. XMLParser parser(element);
  272. parser.Parse(stream);
  273. return document;
  274. }
  275. // Registers an instancer that will be used to instance decorators.
  276. DecoratorInstancer* Factory::RegisterDecoratorInstancer(const String& name, DecoratorInstancer* instancer)
  277. {
  278. String lower_case_name = ToLower(name);
  279. instancer->AddReference();
  280. // Check if an instancer for this tag is already defined. If so, release it.
  281. DecoratorInstancerMap::iterator iterator = decorator_instancers.find(lower_case_name);
  282. if (iterator != decorator_instancers.end())
  283. (*iterator).second->RemoveReference();
  284. decorator_instancers[lower_case_name] = instancer;
  285. return instancer;
  286. }
  287. // Attempts to instance a decorator from an instancer registered with the factory.
  288. Decorator* Factory::InstanceDecorator(const String& name, const PropertyDictionary& properties)
  289. {
  290. float z_index = 0;
  291. int specificity = -1;
  292. DecoratorInstancerMap::iterator iterator = decorator_instancers.find(name);
  293. if (iterator == decorator_instancers.end())
  294. return NULL;
  295. // Turn the generic, un-parsed properties we've got into a properly parsed dictionary.
  296. const PropertySpecification& property_specification = (*iterator).second->GetPropertySpecification();
  297. PropertyDictionary parsed_properties;
  298. for (PropertyMap::const_iterator i = properties.GetProperties().begin(); i != properties.GetProperties().end(); ++i)
  299. {
  300. specificity = Math::Max(specificity, (*i).second.specificity);
  301. // Check for the 'z-index' property; we don't want to send this through.
  302. if ((*i).first == Z_INDEX)
  303. z_index = (*i).second.value.Get< float >();
  304. else
  305. property_specification.ParsePropertyDeclaration(parsed_properties, (*i).first, (*i).second.value.Get< String >(), (*i).second.source, (*i).second.source_line_number);
  306. }
  307. // Set the property defaults for all unset properties.
  308. property_specification.SetPropertyDefaults(parsed_properties);
  309. Decorator* decorator = (*iterator).second->InstanceDecorator(name, parsed_properties);
  310. if (decorator == NULL)
  311. return NULL;
  312. decorator->SetZIndex(z_index);
  313. decorator->SetSpecificity(specificity);
  314. decorator->instancer = (*iterator).second;
  315. return decorator;
  316. }
  317. // Registers an instancer that will be used to instance font effects.
  318. FontEffectInstancer* Factory::RegisterFontEffectInstancer(const String& name, FontEffectInstancer* instancer)
  319. {
  320. String lower_case_name = ToLower(name);
  321. instancer->AddReference();
  322. // Check if an instancer for this tag is already defined. If so, release it.
  323. FontEffectInstancerMap::iterator iterator = font_effect_instancers.find(lower_case_name);
  324. if (iterator != font_effect_instancers.end())
  325. (*iterator).second->RemoveReference();
  326. font_effect_instancers[lower_case_name] = instancer;
  327. return instancer;
  328. }
  329. // Attempts to instance a font effect from an instancer registered with the factory.
  330. FontEffect* Factory::InstanceFontEffect(const String& name, const PropertyDictionary& properties)
  331. {
  332. bool set_colour = false;
  333. Colourb colour(255, 255, 255);
  334. bool set_z_index = false;
  335. float z_index = 0;
  336. int specificity = -1;
  337. FontEffectInstancerMap::iterator iterator = font_effect_instancers.find(name);
  338. if (iterator == font_effect_instancers.end())
  339. return NULL;
  340. FontEffectInstancer* instancer = iterator->second;
  341. // Turn the generic, un-parsed properties we've got into a properly parsed dictionary.
  342. const PropertySpecification& property_specification = (*iterator).second->GetPropertySpecification();
  343. PropertyDictionary parsed_properties;
  344. for (PropertyMap::const_iterator i = properties.GetProperties().begin(); i != properties.GetProperties().end(); ++i)
  345. {
  346. specificity = Math::Max(specificity, i->second.specificity);
  347. // Check for the 'z-index' property; we don't want to send this through.
  348. if (i->first == Z_INDEX)
  349. {
  350. set_z_index = true;
  351. z_index = i->second.value.Get< float >();
  352. }
  353. else if (i->first == COLOR)
  354. {
  355. static PropertyParserColour colour_parser;
  356. Property colour_property;
  357. if (colour_parser.ParseValue(colour_property, i->second.value.Get< String >(), ParameterMap()))
  358. {
  359. colour = colour_property.value.Get< Colourb >();
  360. set_colour = true;
  361. }
  362. }
  363. else
  364. {
  365. property_specification.ParsePropertyDeclaration(parsed_properties, (*i).first, (*i).second.value.Get< String >(), (*i).second.source, (*i).second.source_line_number);
  366. }
  367. }
  368. // Set the property defaults for all unset properties.
  369. property_specification.SetPropertyDefaults(parsed_properties);
  370. // Compile an ordered list of the values of the properties used to generate the effect's
  371. // textures and geometry.
  372. typedef std::list< std::pair< String, String > > GenerationPropertyList;
  373. GenerationPropertyList generation_properties;
  374. for (PropertyMap::const_iterator i = parsed_properties.GetProperties().begin(); i != parsed_properties.GetProperties().end(); ++i)
  375. {
  376. if (instancer->volatile_properties.find(i->first) != instancer->volatile_properties.end())
  377. {
  378. GenerationPropertyList::iterator j = generation_properties.begin();
  379. while (j != generation_properties.end() &&
  380. j->first < i->first)
  381. ++j;
  382. generation_properties.insert(j, GenerationPropertyList::value_type(i->first, i->second.value.Get< String >()));
  383. }
  384. }
  385. String generation_key;
  386. for (GenerationPropertyList::iterator i = generation_properties.begin(); i != generation_properties.end(); ++i)
  387. {
  388. generation_key += i->second;
  389. generation_key += ";";
  390. }
  391. // Now we can actually instance the effect!
  392. FontEffect* font_effect = (*iterator).second->InstanceFontEffect(name, parsed_properties);
  393. if (font_effect == NULL)
  394. return NULL;
  395. font_effect->name = name;
  396. font_effect->generation_key = generation_key;
  397. if (set_z_index)
  398. font_effect->SetZIndex(z_index);
  399. if (set_colour)
  400. font_effect->SetColour(colour);
  401. font_effect->SetSpecificity(specificity);
  402. font_effect->instancer = (*iterator).second;
  403. return font_effect;
  404. }
  405. // Creates a style sheet containing the passed in styles.
  406. StyleSheet* Factory::InstanceStyleSheetString(const String& string)
  407. {
  408. StreamMemory* memory_stream = new StreamMemory((const byte*) string.c_str(), string.size());
  409. StyleSheet* style_sheet = InstanceStyleSheetStream(memory_stream);
  410. memory_stream->RemoveReference();
  411. return style_sheet;
  412. }
  413. // Creates a style sheet from a file.
  414. StyleSheet* Factory::InstanceStyleSheetFile(const String& file_name)
  415. {
  416. StreamFile* file_stream = new StreamFile();
  417. file_stream->Open(file_name);
  418. StyleSheet* style_sheet = InstanceStyleSheetStream(file_stream);
  419. file_stream->RemoveReference();
  420. return style_sheet;
  421. }
  422. // Creates a style sheet from an Stream.
  423. StyleSheet* Factory::InstanceStyleSheetStream(Stream* stream)
  424. {
  425. StyleSheet* style_sheet = new StyleSheet();
  426. if (style_sheet->LoadStyleSheet(stream))
  427. {
  428. return style_sheet;
  429. }
  430. style_sheet->RemoveReference();
  431. return NULL;
  432. }
  433. // Clears the style sheet cache. This will force style sheets to be reloaded.
  434. void Factory::ClearStyleSheetCache()
  435. {
  436. StyleSheetFactory::ClearStyleSheetCache();
  437. }
  438. /// Clears the template cache. This will force templates to be reloaded.
  439. void Factory::ClearTemplateCache()
  440. {
  441. TemplateCache::Clear();
  442. }
  443. // Registers an instancer for all RKTEvents
  444. EventInstancer* Factory::RegisterEventInstancer(EventInstancer* instancer)
  445. {
  446. instancer->AddReference();
  447. if (event_instancer)
  448. event_instancer->RemoveReference();
  449. event_instancer = instancer;
  450. return instancer;
  451. }
  452. // Instance an event object.
  453. Event* Factory::InstanceEvent(Element* target, EventId id, const Dictionary& parameters)
  454. {
  455. Event* event = event_instancer->InstanceEvent(target, id, parameters);
  456. if (event != NULL)
  457. event->instancer = event_instancer;
  458. return event;
  459. }
  460. // Register an instancer for all event listeners
  461. EventListenerInstancer* Factory::RegisterEventListenerInstancer(EventListenerInstancer* instancer)
  462. {
  463. instancer->AddReference();
  464. if (event_listener_instancer)
  465. event_listener_instancer->RemoveReference();
  466. event_listener_instancer = instancer;
  467. return instancer;
  468. }
  469. // Instance an event listener with the given string
  470. EventListener* Factory::InstanceEventListener(const String& value, Element* element)
  471. {
  472. // If we have an event listener instancer, use it
  473. if (event_listener_instancer)
  474. return event_listener_instancer->InstanceEventListener(value, element);
  475. return NULL;
  476. }
  477. }
  478. }