Factory.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "../../Include/RmlUi/Core/Factory.h"
  29. #include "../../Include/RmlUi/Core/StreamMemory.h"
  30. #include "../../Include/RmlUi/Core.h"
  31. #include "ContextInstancerDefault.h"
  32. #include "DecoratorTiledBoxInstancer.h"
  33. #include "DecoratorTiledHorizontalInstancer.h"
  34. #include "DecoratorTiledImageInstancer.h"
  35. #include "DecoratorTiledVerticalInstancer.h"
  36. #include "DecoratorNinePatch.h"
  37. #include "DecoratorGradient.h"
  38. #include "ElementHandle.h"
  39. #include "ElementImage.h"
  40. #include "ElementTextDefault.h"
  41. #include "EventInstancerDefault.h"
  42. #include "FontEffectBlur.h"
  43. #include "FontEffectGlow.h"
  44. #include "FontEffectOutline.h"
  45. #include "FontEffectShadow.h"
  46. #include "PluginRegistry.h"
  47. #include "PropertyParserColour.h"
  48. #include "StreamFile.h"
  49. #include "StyleSheetFactory.h"
  50. #include "TemplateCache.h"
  51. #include "XMLNodeHandlerBody.h"
  52. #include "XMLNodeHandlerDefault.h"
  53. #include "XMLNodeHandlerHead.h"
  54. #include "XMLNodeHandlerTemplate.h"
  55. #include "XMLParseTools.h"
  56. namespace Rml {
  57. namespace Core {
  58. // Element instancers.
  59. typedef UnorderedMap< String, ElementInstancer* > ElementInstancerMap;
  60. static ElementInstancerMap element_instancers;
  61. // Decorator instancers.
  62. typedef UnorderedMap< String, DecoratorInstancer* > DecoratorInstancerMap;
  63. static DecoratorInstancerMap decorator_instancers;
  64. // Font effect instancers.
  65. typedef UnorderedMap< String, FontEffectInstancer* > FontEffectInstancerMap;
  66. static FontEffectInstancerMap font_effect_instancers;
  67. // The context instancer.
  68. static ContextInstancer* context_instancer = nullptr;;
  69. // The event instancer
  70. static EventInstancer* event_instancer = nullptr;;
  71. // Event listener instancer.
  72. static EventListenerInstancer* event_listener_instancer = nullptr;
  73. // Default instancers are constructed and destroyed on Initialise and Shutdown, respectively.
  74. struct DefaultInstancers {
  75. template<typename T> using Ptr = UniquePtr<T>;
  76. Ptr<ContextInstancer> context_default;
  77. Ptr<EventInstancer> event_default;
  78. Ptr<ElementInstancer> element_default = std::make_unique<ElementInstancerElement>();
  79. Ptr<ElementInstancer> element_text_default = std::make_unique<ElementInstancerTextDefault>();
  80. Ptr<ElementInstancer> element_img = std::make_unique<ElementInstancerGeneric<ElementImage>>();
  81. Ptr<ElementInstancer> element_handle = std::make_unique<ElementInstancerGeneric<ElementHandle>>();
  82. Ptr<ElementInstancer> element_body = std::make_unique<ElementInstancerGeneric<ElementDocument>>();
  83. Ptr<DecoratorInstancer> decorator_tiled_horizontal = std::make_unique<DecoratorTiledHorizontalInstancer>();
  84. Ptr<DecoratorInstancer> decorator_tiled_vertical = std::make_unique<DecoratorTiledVerticalInstancer>();
  85. Ptr<DecoratorInstancer> decorator_tiled_box = std::make_unique<DecoratorTiledBoxInstancer>();
  86. Ptr<DecoratorInstancer> decorator_image = std::make_unique<DecoratorTiledImageInstancer>();
  87. Ptr<DecoratorInstancer> decorator_ninepatch = std::make_unique<DecoratorNinePatchInstancer>();
  88. Ptr<DecoratorInstancer> decorator_gradient = std::make_unique<DecoratorGradientInstancer>();
  89. Ptr<FontEffectInstancer> font_effect_blur = std::make_unique<FontEffectBlurInstancer>();
  90. Ptr<FontEffectInstancer> font_effect_glow = std::make_unique<FontEffectGlowInstancer>();
  91. Ptr<FontEffectInstancer> font_effect_outline = std::make_unique<FontEffectOutlineInstancer>();
  92. Ptr<FontEffectInstancer> font_effect_shadow = std::make_unique<FontEffectShadowInstancer>();
  93. };
  94. static UniquePtr<DefaultInstancers> default_instancers;
  95. Factory::Factory()
  96. {
  97. }
  98. Factory::~Factory()
  99. {
  100. }
  101. bool Factory::Initialise()
  102. {
  103. default_instancers = std::make_unique<DefaultInstancers>();
  104. // Bind the default context instancer.
  105. if (!context_instancer)
  106. {
  107. default_instancers->context_default = std::make_unique<ContextInstancerDefault>();
  108. context_instancer = default_instancers->context_default.get();
  109. }
  110. // Bind default event instancer
  111. if (!event_instancer)
  112. {
  113. default_instancers->event_default = std::make_unique<EventInstancerDefault>();
  114. event_instancer = default_instancers->event_default.get();
  115. }
  116. // No default event listener instancer
  117. if (!event_listener_instancer)
  118. event_listener_instancer = nullptr;
  119. // Bind the default element instancers
  120. RegisterElementInstancer("*", default_instancers->element_default.get());
  121. RegisterElementInstancer("img", default_instancers->element_img.get());
  122. RegisterElementInstancer("#text", default_instancers->element_text_default.get());
  123. RegisterElementInstancer("handle", default_instancers->element_handle.get());
  124. RegisterElementInstancer("body", default_instancers->element_body.get());
  125. // Bind the default decorator instancers
  126. RegisterDecoratorInstancer("tiled-horizontal", default_instancers->decorator_tiled_horizontal.get());
  127. RegisterDecoratorInstancer("tiled-vertical", default_instancers->decorator_tiled_vertical.get());
  128. RegisterDecoratorInstancer("tiled-box", default_instancers->decorator_tiled_box.get());
  129. RegisterDecoratorInstancer("image", default_instancers->decorator_image.get());
  130. RegisterDecoratorInstancer("ninepatch", default_instancers->decorator_ninepatch.get());
  131. RegisterDecoratorInstancer("gradient", default_instancers->decorator_gradient.get());
  132. RegisterFontEffectInstancer("blur", default_instancers->font_effect_blur.get());
  133. RegisterFontEffectInstancer("glow", default_instancers->font_effect_glow.get());
  134. RegisterFontEffectInstancer("outline", default_instancers->font_effect_outline.get());
  135. RegisterFontEffectInstancer("shadow", default_instancers->font_effect_shadow.get());
  136. // Register the core XML node handlers.
  137. XMLParser::RegisterNodeHandler("", std::make_shared<XMLNodeHandlerDefault>());
  138. XMLParser::RegisterNodeHandler("body", std::make_shared<XMLNodeHandlerBody>());
  139. XMLParser::RegisterNodeHandler("head", std::make_shared<XMLNodeHandlerHead>());
  140. XMLParser::RegisterNodeHandler("template", std::make_shared<XMLNodeHandlerTemplate>());
  141. return true;
  142. }
  143. void Factory::Shutdown()
  144. {
  145. element_instancers.clear();
  146. decorator_instancers.clear();
  147. font_effect_instancers.clear();
  148. context_instancer = nullptr;
  149. event_listener_instancer = nullptr;
  150. event_instancer = nullptr;
  151. XMLParser::ReleaseHandlers();
  152. default_instancers.reset();
  153. }
  154. // Registers the instancer to use when instancing contexts.
  155. void Factory::RegisterContextInstancer(ContextInstancer* instancer)
  156. {
  157. context_instancer = instancer;
  158. }
  159. // Instances a new context.
  160. ContextPtr Factory::InstanceContext(const String& name)
  161. {
  162. ContextPtr new_context = context_instancer->InstanceContext(name);
  163. if (new_context)
  164. new_context->SetInstancer(context_instancer);
  165. return new_context;
  166. }
  167. void Factory::RegisterElementInstancer(const String& name, ElementInstancer* instancer)
  168. {
  169. element_instancers[StringUtilities::ToLower(name)] = instancer;
  170. }
  171. // Looks up the instancer for the given element
  172. ElementInstancer* Factory::GetElementInstancer(const String& tag)
  173. {
  174. ElementInstancerMap::iterator instancer_iterator = element_instancers.find(tag);
  175. if (instancer_iterator == element_instancers.end())
  176. {
  177. instancer_iterator = element_instancers.find("*");
  178. if (instancer_iterator == element_instancers.end())
  179. return nullptr;
  180. }
  181. return instancer_iterator->second;
  182. }
  183. // Instances a single element.
  184. ElementPtr Factory::InstanceElement(Element* parent, const String& instancer_name, const String& tag, const XMLAttributes& attributes)
  185. {
  186. ElementInstancer* instancer = GetElementInstancer(instancer_name);
  187. if (instancer)
  188. {
  189. ElementPtr element = instancer->InstanceElement(parent, tag, attributes);
  190. // Process the generic attributes and bind any events
  191. if (element)
  192. {
  193. element->SetInstancer(instancer);
  194. element->SetAttributes(attributes);
  195. ElementUtilities::BindEventAttributes(element.get());
  196. // TODO: Relies on parent, a bit hacky.
  197. if (parent && !parent->HasAttribute("data-for"))
  198. {
  199. // Look for the data-model attribute or otherwise copy it from the parent element
  200. auto it = attributes.find("data-model");
  201. if (it != attributes.end())
  202. {
  203. String error_msg;
  204. if (auto context = parent->GetContext())
  205. {
  206. String name = it->second.Get<String>();
  207. if (auto model = context->GetDataModel(name))
  208. element->data_model = model;
  209. else
  210. Log::Message(Log::LT_WARNING, "Could not locate data model '%s'.", name.c_str());
  211. }
  212. else
  213. {
  214. Log::Message(Log::LT_WARNING, "Could not add data model to element '%s' because the context is not available.", element->GetAddress().c_str());
  215. }
  216. }
  217. else if (parent && parent->data_model)
  218. {
  219. element->data_model = parent->data_model;
  220. }
  221. // If we have an active data model, check the attributes for any data bindings
  222. if (DataModel* data_model = element->data_model)
  223. {
  224. for (auto& attribute : attributes)
  225. {
  226. auto& name = attribute.first;
  227. if (name.size() > 5 && name[0] == 'd' && name[1] == 'a' && name[2] == 't' && name[3] == 'a' && name[4] == '-')
  228. {
  229. const size_t data_type_end = name.find('-', 5);
  230. const size_t count = (data_type_end == String::npos ? String::npos : data_type_end - 5);
  231. const String data_type = name.substr(5, count);
  232. const String value_bind_name = attribute.second.Get<String>();
  233. if (data_type == "attr")
  234. {
  235. const String attr_bind_name = name.substr(5 + data_type.size() + 1);
  236. auto view = std::make_unique<DataViewAttribute>(*data_model, element.get(), parent, value_bind_name, attr_bind_name);
  237. if (*view)
  238. data_model->AddView(std::move(view));
  239. else
  240. Log::Message(Log::LT_WARNING, "Could not add data-attr view to element '%s'.", parent->GetAddress().c_str());
  241. }
  242. else if (data_type == "value")
  243. {
  244. const String attr_bind_name = "value";
  245. auto view = std::make_unique<DataViewAttribute>(*data_model, element.get(), parent, value_bind_name, attr_bind_name);
  246. if (*view)
  247. data_model->AddView(std::move(view));
  248. else
  249. Log::Message(Log::LT_WARNING, "Could not add data-value view to element '%s'.", parent->GetAddress().c_str());
  250. auto controller = std::make_unique<DataControllerValue>(*data_model, element.get(), value_bind_name);
  251. if (controller)
  252. data_model->AddController(std::move(controller));
  253. else
  254. Log::Message(Log::LT_WARNING, "Could not add data-value controller to element '%s'.", parent->GetAddress().c_str());
  255. }
  256. else if (data_type == "style")
  257. {
  258. const String property_name = name.substr(5 + data_type.size() + 1);
  259. auto view = std::make_unique<DataViewStyle>(*data_model, element.get(), parent, value_bind_name, property_name);
  260. if (*view)
  261. data_model->AddView(std::move(view));
  262. else
  263. Log::Message(Log::LT_WARNING, "Could not add data-style view to element '%s'.", parent->GetAddress().c_str());
  264. }
  265. else if (data_type == "if")
  266. {
  267. auto view = std::make_unique<DataViewIf>(*data_model, element.get(), parent, value_bind_name);
  268. if (*view)
  269. data_model->AddView(std::move(view));
  270. else
  271. Log::Message(Log::LT_WARNING, "Could not add data-if view to element '%s'.", parent->GetAddress().c_str());
  272. }
  273. }
  274. }
  275. }
  276. }
  277. PluginRegistry::NotifyElementCreate(element.get());
  278. }
  279. return element;
  280. }
  281. return nullptr;
  282. }
  283. // Instances a single text element containing a string.
  284. bool Factory::InstanceElementText(Element* parent, const String& text)
  285. {
  286. SystemInterface* system_interface = GetSystemInterface();
  287. // Do any necessary translation. If any substitutions were made then new XML may have been introduced, so we'll
  288. // have to run the data through the XML parser again.
  289. String translated_data;
  290. if (system_interface != nullptr &&
  291. (system_interface->TranslateString(translated_data, text) > 0 ||
  292. translated_data.find("<") != String::npos))
  293. {
  294. RMLUI_ZoneScopedNC("InstanceStream", 0xDC143C);
  295. auto stream = std::make_unique<StreamMemory>(translated_data.size() + 32);
  296. stream->Write("<body>", 6);
  297. stream->Write(translated_data);
  298. stream->Write("</body>", 7);
  299. stream->Seek(0, SEEK_SET);
  300. InstanceElementStream(parent, stream.get());
  301. }
  302. else
  303. {
  304. RMLUI_ZoneScopedNC("InstanceText", 0x8FBC8F);
  305. // Check if this text node contains only white-space; if so, we don't want to construct it.
  306. bool only_white_space = true;
  307. for (size_t i = 0; i < translated_data.size(); ++i)
  308. {
  309. if (!StringUtilities::IsWhitespace(translated_data[i]))
  310. {
  311. only_white_space = false;
  312. break;
  313. }
  314. }
  315. if (only_white_space)
  316. return true;
  317. // Attempt to instance the element.
  318. XMLAttributes attributes;
  319. ElementPtr element_ptr = Factory::InstanceElement(parent, "#text", "#text", attributes);
  320. if (!element_ptr)
  321. {
  322. Log::Message(Log::LT_ERROR, "Failed to instance text element '%s', instancer returned nullptr.", translated_data.c_str());
  323. return false;
  324. }
  325. // Assign the element its text value.
  326. ElementText* text_element = rmlui_dynamic_cast< ElementText* >(element_ptr.get());
  327. if (!text_element)
  328. {
  329. Log::Message(Log::LT_ERROR, "Failed to instance text element '%s'. Found type '%s', was expecting a derivative of ElementText.", translated_data.c_str(), rmlui_type_name(*element_ptr));
  330. return false;
  331. }
  332. // Add to active node.
  333. Element* element = parent->AppendChild(std::move(element_ptr));
  334. // See if this text element uses data bindings.
  335. bool data_view_added = false;
  336. if (DataModel* data_model = element->data_model)
  337. {
  338. const size_t i_brackets = translated_data.find("{{", 0);
  339. if (i_brackets != String::npos)
  340. {
  341. auto view = std::make_unique<DataViewText>(*data_model, text_element, translated_data, i_brackets);
  342. if (*view)
  343. {
  344. data_model->AddView(std::move(view));
  345. data_view_added = true;
  346. }
  347. else
  348. {
  349. Log::Message(Log::LT_WARNING, "Could not add data binding view to element '%s'.", parent->GetAddress().c_str());
  350. }
  351. }
  352. }
  353. if(!data_view_added)
  354. text_element->SetText(translated_data);
  355. }
  356. return true;
  357. }
  358. // Instances a element tree based on the stream
  359. bool Factory::InstanceElementStream(Element* parent, Stream* stream)
  360. {
  361. XMLParser parser(parent);
  362. parser.Parse(stream);
  363. return true;
  364. }
  365. // Instances a element tree based on the stream
  366. ElementPtr Factory::InstanceDocumentStream(Rml::Core::Context* context, Stream* stream)
  367. {
  368. RMLUI_ZoneScoped;
  369. ElementPtr element = Factory::InstanceElement(nullptr, "body", "body", XMLAttributes());
  370. if (!element)
  371. {
  372. Log::Message(Log::LT_ERROR, "Failed to instance document, instancer returned nullptr.");
  373. return nullptr;
  374. }
  375. ElementDocument* document = rmlui_dynamic_cast< ElementDocument* >(element.get());
  376. if (!document)
  377. {
  378. Log::Message(Log::LT_ERROR, "Failed to instance document element. Found type '%s', was expecting derivative of ElementDocument.", rmlui_type_name(*element));
  379. return nullptr;
  380. }
  381. document->context = context;
  382. XMLParser parser(element.get());
  383. parser.Parse(stream);
  384. return element;
  385. }
  386. // Registers an instancer that will be used to instance decorators.
  387. void Factory::RegisterDecoratorInstancer(const String& name, DecoratorInstancer* instancer)
  388. {
  389. RMLUI_ASSERT(instancer);
  390. decorator_instancers[StringUtilities::ToLower(name)] = instancer;
  391. }
  392. // Retrieves a decorator instancer registered with the factory.
  393. DecoratorInstancer* Factory::GetDecoratorInstancer(const String& name)
  394. {
  395. auto iterator = decorator_instancers.find(name);
  396. if (iterator == decorator_instancers.end())
  397. return nullptr;
  398. return iterator->second;
  399. }
  400. // Registers an instancer that will be used to instance font effects.
  401. void Factory::RegisterFontEffectInstancer(const String& name, FontEffectInstancer* instancer)
  402. {
  403. RMLUI_ASSERT(instancer);
  404. font_effect_instancers[StringUtilities::ToLower(name)] = instancer;
  405. }
  406. FontEffectInstancer* Factory::GetFontEffectInstancer(const String& name)
  407. {
  408. auto iterator = font_effect_instancers.find(name);
  409. if (iterator == font_effect_instancers.end())
  410. return nullptr;
  411. return iterator->second;
  412. }
  413. // Creates a style sheet containing the passed in styles.
  414. SharedPtr<StyleSheet> Factory::InstanceStyleSheetString(const String& string)
  415. {
  416. auto memory_stream = std::make_unique<StreamMemory>((const byte*) string.c_str(), string.size());
  417. return InstanceStyleSheetStream(memory_stream.get());
  418. }
  419. // Creates a style sheet from a file.
  420. SharedPtr<StyleSheet> Factory::InstanceStyleSheetFile(const String& file_name)
  421. {
  422. auto file_stream = std::make_unique<StreamFile>();
  423. file_stream->Open(file_name);
  424. return InstanceStyleSheetStream(file_stream.get());
  425. }
  426. // Creates a style sheet from an Stream.
  427. SharedPtr<StyleSheet> Factory::InstanceStyleSheetStream(Stream* stream)
  428. {
  429. SharedPtr<StyleSheet> style_sheet = std::make_shared<StyleSheet>();
  430. if (style_sheet->LoadStyleSheet(stream))
  431. {
  432. return style_sheet;
  433. }
  434. return nullptr;
  435. }
  436. // Clears the style sheet cache. This will force style sheets to be reloaded.
  437. void Factory::ClearStyleSheetCache()
  438. {
  439. StyleSheetFactory::ClearStyleSheetCache();
  440. }
  441. /// Clears the template cache. This will force templates to be reloaded.
  442. void Factory::ClearTemplateCache()
  443. {
  444. TemplateCache::Clear();
  445. }
  446. // Registers an instancer for all RmlEvents
  447. void Factory::RegisterEventInstancer(EventInstancer* instancer)
  448. {
  449. event_instancer = instancer;
  450. }
  451. // Instance an event object.
  452. EventPtr Factory::InstanceEvent(Element* target, EventId id, const String& type, const Dictionary& parameters, bool interruptible)
  453. {
  454. EventPtr event = event_instancer->InstanceEvent(target, id, type, parameters, interruptible);
  455. if (event)
  456. event->instancer = event_instancer;
  457. return event;
  458. }
  459. // Register an instancer for all event listeners
  460. void Factory::RegisterEventListenerInstancer(EventListenerInstancer* instancer)
  461. {
  462. event_listener_instancer = instancer;
  463. }
  464. // Instance an event listener with the given string
  465. EventListener* Factory::InstanceEventListener(const String& value, Element* element)
  466. {
  467. // If we have an event listener instancer, use it
  468. if (event_listener_instancer)
  469. return event_listener_instancer->InstanceEventListener(value, element);
  470. return nullptr;
  471. }
  472. }
  473. }