ElementDocument.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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/ElementDocument.h"
  29. #include "../../Include/Rocket/Core/StreamMemory.h"
  30. #include "../../Include/Rocket/Core.h"
  31. #include "DocumentHeader.h"
  32. #include "ElementStyle.h"
  33. #include "EventDispatcher.h"
  34. #include "LayoutEngine.h"
  35. #include "StreamFile.h"
  36. #include "StyleSheetFactory.h"
  37. #include "Template.h"
  38. #include "TemplateCache.h"
  39. #include "XMLParseTools.h"
  40. namespace Rocket {
  41. namespace Core {
  42. ElementDocument::ElementDocument(const String& tag) : Element(tag)
  43. {
  44. style_sheet = NULL;
  45. context = NULL;
  46. modal = false;
  47. layout_dirty = true;
  48. lock_layout = 0;
  49. ForceLocalStackingContext();
  50. SetProperty(POSITION, "absolute");
  51. }
  52. ElementDocument::~ElementDocument()
  53. {
  54. if (style_sheet != NULL)
  55. style_sheet->RemoveReference();
  56. }
  57. void ElementDocument::ProcessHeader(const DocumentHeader* document_header)
  58. {
  59. // Store the source address that we came from
  60. source_url = document_header->source;
  61. // Construct a new header and copy the template details across
  62. DocumentHeader header;
  63. header.MergePaths(header.template_resources, document_header->template_resources, document_header->source);
  64. // Merge in any templates, note a merge may cause more templates to merge
  65. for (size_t i = 0; i < header.template_resources.size(); i++)
  66. {
  67. Template* merge_template = TemplateCache::LoadTemplate(URL(header.template_resources[i]).GetURL());
  68. if (merge_template)
  69. header.MergeHeader(*merge_template->GetHeader());
  70. else
  71. Log::Message(Log::LT_WARNING, "Template %s not found", header.template_resources[i].CString());
  72. }
  73. // Merge the document's header last, as it is the most overriding.
  74. header.MergeHeader(*document_header);
  75. // Set the title to the document title.
  76. title = document_header->title;
  77. // If a style-sheet (or sheets) has been specified for this element, then we load them and set the combined sheet
  78. // on the element; all of its children will inherit it by default.
  79. StyleSheet* style_sheet = NULL;
  80. if (header.rcss_external.size() > 0)
  81. style_sheet = StyleSheetFactory::GetStyleSheet(header.rcss_external);
  82. // Combine any inline sheets.
  83. if (header.rcss_inline.size() > 0)
  84. {
  85. for (size_t i = 0;i < header.rcss_inline.size(); i++)
  86. {
  87. StyleSheet* new_sheet = new StyleSheet();
  88. StreamMemory* stream = new StreamMemory((const byte*) header.rcss_inline[i].CString(), header.rcss_inline[i].Length());
  89. stream->SetSourceURL(document_header->source);
  90. if (new_sheet->LoadStyleSheet(stream))
  91. {
  92. if (style_sheet)
  93. {
  94. StyleSheet* combined_sheet = style_sheet->CombineStyleSheet(new_sheet);
  95. style_sheet->RemoveReference();
  96. new_sheet->RemoveReference();
  97. style_sheet = combined_sheet;
  98. }
  99. else
  100. style_sheet = new_sheet;
  101. }
  102. else
  103. new_sheet->RemoveReference();
  104. stream->RemoveReference();
  105. }
  106. }
  107. // If a style sheet is available, set it on the document and release it.
  108. if (style_sheet)
  109. {
  110. SetStyleSheet(style_sheet);
  111. style_sheet->RemoveReference();
  112. }
  113. // Load external scripts.
  114. for (size_t i = 0; i < header.scripts_external.size(); i++)
  115. {
  116. StreamFile* stream = new StreamFile();
  117. if (stream->Open(header.scripts_external[i]))
  118. LoadScript(stream, header.scripts_external[i]);
  119. stream->RemoveReference();
  120. }
  121. // Load internal scripts.
  122. for (size_t i = 0; i < header.scripts_inline.size(); i++)
  123. {
  124. StreamMemory* stream = new StreamMemory((const byte*) header.scripts_inline[i].CString(), header.scripts_inline[i].Length());
  125. LoadScript(stream, "");
  126. stream->RemoveReference();
  127. }
  128. // Hide this document.
  129. SetProperty(VISIBILITY, "hidden");
  130. }
  131. ElementDocument* ElementDocument::GetOwnerDocument()
  132. {
  133. return this;
  134. }
  135. // Returns the document's context.
  136. Context* ElementDocument::GetContext()
  137. {
  138. return context;
  139. }
  140. // Sets the document's title.
  141. void ElementDocument::SetTitle(const String& _title)
  142. {
  143. title = _title;
  144. }
  145. const String& ElementDocument::GetTitle() const
  146. {
  147. return title;
  148. }
  149. const String& ElementDocument::GetSourceURL() const
  150. {
  151. return source_url;
  152. }
  153. // Sets the style sheet this document, and all of its children, uses.
  154. void ElementDocument::SetStyleSheet(StyleSheet* _style_sheet)
  155. {
  156. if (style_sheet == _style_sheet)
  157. return;
  158. if (style_sheet != NULL)
  159. style_sheet->RemoveReference();
  160. style_sheet = _style_sheet;
  161. if (style_sheet != NULL)
  162. {
  163. style_sheet->AddReference();
  164. style_sheet->BuildNodeIndex();
  165. }
  166. GetStyle()->DirtyDefinition();
  167. }
  168. // Returns the document's style sheet.
  169. StyleSheet* ElementDocument::GetStyleSheet() const
  170. {
  171. return style_sheet;
  172. }
  173. // Brings the document to the front of the document stack.
  174. void ElementDocument::PullToFront()
  175. {
  176. if (context != NULL)
  177. context->PullDocumentToFront(this);
  178. }
  179. // Sends the document to the back of the document stack.
  180. void ElementDocument::PushToBack()
  181. {
  182. if (context != NULL)
  183. context->PushDocumentToBack(this);
  184. }
  185. void ElementDocument::Show(int focus_flags)
  186. {
  187. // Store the modal attribute
  188. modal = (focus_flags & MODAL) > 0;
  189. // Set to visible and switch focus if necessary
  190. SetProperty(VISIBILITY, "visible");
  191. if (focus_flags & FOCUS || focus_flags & MODAL)
  192. {
  193. // If no element could be focused, focus the window
  194. if (!FocusNextTabElement(this, true))
  195. {
  196. Focus();
  197. }
  198. }
  199. DispatchEvent("show", Dictionary(), false);
  200. }
  201. void ElementDocument::Hide()
  202. {
  203. SetProperty(VISIBILITY, "hidden");
  204. DispatchEvent("hide", Dictionary(), false);
  205. }
  206. // Close this document
  207. void ElementDocument::Close()
  208. {
  209. if (context != NULL)
  210. context->UnloadDocument(this);
  211. }
  212. Element* ElementDocument::CreateElement(const String& name)
  213. {
  214. return Factory::InstanceElement(NULL, name, name, XMLAttributes());
  215. }
  216. // Create a text element.
  217. ElementText* ElementDocument::CreateTextNode(const String& text)
  218. {
  219. // Create the element.
  220. Element* element = CreateElement("#text");
  221. if (!element)
  222. {
  223. Log::Message(Log::LT_ERROR, "Failed to create text element, instancer returned NULL.");
  224. return NULL;
  225. }
  226. // Cast up
  227. ElementText* element_text = dynamic_cast< ElementText* >(element);
  228. if (!element_text)
  229. {
  230. Log::Message(Log::LT_ERROR, "Failed to create text element, instancer didn't return a derivative of ElementText.");
  231. element->RemoveReference();
  232. return NULL;
  233. }
  234. // Set the text
  235. element_text->SetText(text);
  236. return element_text;
  237. }
  238. // Is the current document modal
  239. bool ElementDocument::IsModal() const
  240. {
  241. return modal;
  242. }
  243. // Default load script implementation
  244. void ElementDocument::LoadScript(Stream* ROCKET_UNUSED_PARAMETER(stream), const String& ROCKET_UNUSED_PARAMETER(source_name))
  245. {
  246. ROCKET_UNUSED(stream);
  247. ROCKET_UNUSED(source_name);
  248. }
  249. // Updates the layout if necessary.
  250. void ElementDocument::_UpdateLayout()
  251. {
  252. layout_dirty = false;
  253. lock_layout++;
  254. Vector2f containing_block(0, 0);
  255. if (GetParentNode() != NULL)
  256. containing_block = GetParentNode()->GetBox().GetSize();
  257. LayoutEngine layout_engine;
  258. layout_engine.FormatElement(this, containing_block);
  259. lock_layout--;
  260. }
  261. // Updates the position of the document based on the style properties.
  262. void ElementDocument::UpdatePosition()
  263. {
  264. // We are only positioned relative to our parent, so if we're not parented we may as well bail now.
  265. if (GetParentNode() == NULL)
  266. return;
  267. Vector2f position;
  268. // Work out our containing block; relative offsets are calculated against it.
  269. Vector2f containing_block = GetParentNode()->GetBox().GetSize(Box::CONTENT);
  270. const Property *left = GetLocalProperty(LEFT);
  271. const Property *right = GetLocalProperty(RIGHT);
  272. if (left != NULL && left->unit != Property::KEYWORD)
  273. position.x = ResolveProperty(LEFT, containing_block.x);
  274. else if (right != NULL && right->unit != Property::KEYWORD)
  275. position.x = (containing_block.x - GetBox().GetSize(Box::MARGIN).x) - ResolveProperty(RIGHT, containing_block.x);
  276. else
  277. position.x = GetBox().GetEdge(Box::MARGIN, Box::LEFT);
  278. const Property *top = GetLocalProperty(TOP);
  279. const Property *bottom = GetLocalProperty(BOTTOM);
  280. if (top != NULL && top->unit != Property::KEYWORD)
  281. position.y = ResolveProperty(TOP, containing_block.y);
  282. else if (bottom != NULL && bottom->unit != Property::KEYWORD)
  283. position.y = (containing_block.y - GetBox().GetSize(Box::MARGIN).y) - ResolveProperty(BOTTOM, containing_block.y);
  284. else
  285. position.y = GetBox().GetEdge(Box::MARGIN, Box::TOP);
  286. SetOffset(position, NULL);
  287. }
  288. void ElementDocument::LockLayout(bool lock)
  289. {
  290. if (lock)
  291. lock_layout++;
  292. else
  293. lock_layout--;
  294. ROCKET_ASSERT(lock_layout >= 0);
  295. }
  296. void ElementDocument::DirtyLayout()
  297. {
  298. layout_dirty = true;
  299. }
  300. bool ElementDocument::IsLayoutDirty()
  301. {
  302. return layout_dirty;
  303. }
  304. // Refreshes the document layout if required.
  305. void ElementDocument::OnUpdate()
  306. {
  307. UpdateLayout();
  308. }
  309. // Repositions the document if necessary.
  310. void ElementDocument::OnPropertyChange(const PropertyNameList& changed_properties)
  311. {
  312. Element::OnPropertyChange(changed_properties);
  313. // If the document's font-size has been changed, we need to dirty all rem properties.
  314. if (changed_properties.find(FONT_SIZE) != changed_properties.end())
  315. GetStyle()->DirtyRemProperties();
  316. if (changed_properties.find(TOP) != changed_properties.end() ||
  317. changed_properties.find(RIGHT) != changed_properties.end() ||
  318. changed_properties.find(BOTTOM) != changed_properties.end() ||
  319. changed_properties.find(LEFT) != changed_properties.end())
  320. UpdatePosition();
  321. }
  322. // Processes the 'onpropertychange' event, checking for a change in position or size.
  323. void ElementDocument::ProcessEvent(Event& event)
  324. {
  325. Element::ProcessEvent(event);
  326. // Process generic keyboard events for this window in capture phase
  327. if (event.GetPhase() == Event::PHASE_BUBBLE && event == KEYDOWN)
  328. {
  329. int key_identifier = event.GetParameter<int>("key_identifier", Input::KI_UNKNOWN);
  330. // Process TAB
  331. if (key_identifier == Input::KI_TAB)
  332. {
  333. FocusNextTabElement(event.GetTargetElement(), !event.GetParameter<bool>("shift_key", false));
  334. }
  335. // Process ENTER being pressed on a focusable object (emulate click)
  336. else if (key_identifier == Input::KI_RETURN ||
  337. key_identifier == Input::KI_NUMPADENTER)
  338. {
  339. Element* focus_node = GetFocusLeafNode();
  340. if (focus_node && focus_node->GetProperty<int>(TAB_INDEX) == TAB_INDEX_AUTO)
  341. {
  342. focus_node->Click();
  343. }
  344. }
  345. }
  346. else if (event.GetTargetElement() == this)
  347. {
  348. if (event == RESIZE)
  349. UpdatePosition();
  350. }
  351. }
  352. // Find the next element to focus, starting at the current element
  353. //
  354. // This algorithm is quite sneaky, I originally thought a depth first search would
  355. // work, but it appears not. What is required is to cut the tree in half along the nodes
  356. // from current_element up the root and then either traverse the tree in a clockwise or
  357. // anticlock wise direction depending if you're searching forward or backward respectively
  358. bool ElementDocument::FocusNextTabElement(Element* current_element, bool forward)
  359. {
  360. // If we're searching forward, check the immediate children of this node first off
  361. if (forward)
  362. {
  363. for (int i = 0; i < current_element->GetNumChildren(); i++)
  364. if (SearchFocusSubtree(current_element->GetChild(i), forward))
  365. return true;
  366. }
  367. // Now walk up the tree, testing either the bottom or top
  368. // of the tree, depending on whether we're going forwards
  369. // or backwards respectively
  370. //
  371. // If we make it all the way up to the document, then
  372. // we search the entire tree (to loop back round)
  373. bool search_enabled = false;
  374. Element* document = current_element->GetOwnerDocument();
  375. Element* child = current_element;
  376. Element* parent = current_element->GetParentNode();
  377. while (child != document)
  378. {
  379. for (int i = 0; i < parent->GetNumChildren(); i++)
  380. {
  381. // Calculate index into children
  382. int child_index = i;
  383. if (!forward)
  384. child_index = parent->GetNumChildren() - i - 1;
  385. Element* search_child = parent->GetChild(child_index);
  386. // Do a search if its enabled
  387. if (search_enabled && SearchFocusSubtree(search_child, forward))
  388. return true;
  389. // If we find the child, enable searching
  390. if (search_child == child)
  391. search_enabled = true;
  392. }
  393. // Advance up the tree
  394. child = parent;
  395. parent = parent->GetParentNode();
  396. // If we hit the top, enable searching the entire tree
  397. if (parent == document)
  398. search_enabled = true;
  399. else // otherwise enable searching if we're going backward and disable if we're going forward
  400. search_enabled = false;
  401. }
  402. return false;
  403. }
  404. bool ElementDocument::SearchFocusSubtree(Element* element, bool forward)
  405. {
  406. // Skip disabled elements
  407. if (element->IsPseudoClassSet("disabled"))
  408. {
  409. return false;
  410. }
  411. if (!element->IsVisible())
  412. {
  413. return false;
  414. }
  415. // Check if this is the node we're looking for
  416. if (element->GetProperty<int>(TAB_INDEX) == TAB_INDEX_AUTO)
  417. {
  418. element->Focus();
  419. element->ScrollIntoView(false);
  420. return true;
  421. }
  422. // Check all children
  423. for (int i = 0; i < element->GetNumChildren(); i++)
  424. {
  425. int child_index = i;
  426. if (!forward)
  427. child_index = element->GetNumChildren() - i - 1;
  428. if (SearchFocusSubtree(element->GetChild(child_index), forward))
  429. return true;
  430. }
  431. return false;
  432. }
  433. }
  434. }