Factory.cpp 17 KB

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