ElementImage.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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-2023 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 "ElementImage.h"
  29. #include "../../../Include/RmlUi/Core/ComputedValues.h"
  30. #include "../../../Include/RmlUi/Core/ElementDocument.h"
  31. #include "../../../Include/RmlUi/Core/ElementUtilities.h"
  32. #include "../../../Include/RmlUi/Core/GeometryUtilities.h"
  33. #include "../../../Include/RmlUi/Core/PropertyIdSet.h"
  34. #include "../../../Include/RmlUi/Core/StyleSheet.h"
  35. #include "../../../Include/RmlUi/Core/URL.h"
  36. #include "../TextureDatabase.h"
  37. namespace Rml {
  38. ElementImage::ElementImage(const String& tag) : Element(tag), dimensions(-1, -1), rect_source(RectSource::None)
  39. {
  40. dimensions_scale = 1.0f;
  41. geometry_dirty = false;
  42. texture_dirty = true;
  43. }
  44. ElementImage::~ElementImage() {}
  45. bool ElementImage::GetIntrinsicDimensions(Vector2f& _dimensions, float& _ratio)
  46. {
  47. // Check if we need to reload the texture.
  48. if (texture_dirty)
  49. LoadTexture();
  50. // Calculate the x dimension.
  51. if (HasAttribute("width"))
  52. dimensions.x = GetAttribute<float>("width", -1);
  53. else if (rect_source == RectSource::None)
  54. dimensions.x = (float)texture.GetDimensions().x;
  55. else
  56. dimensions.x = rect.Width();
  57. // Calculate the y dimension.
  58. if (HasAttribute("height"))
  59. dimensions.y = GetAttribute<float>("height", -1);
  60. else if (rect_source == RectSource::None)
  61. dimensions.y = (float)texture.GetDimensions().y;
  62. else
  63. dimensions.y = rect.Height();
  64. dimensions *= dimensions_scale;
  65. // Return the calculated dimensions. If this changes the size of the element, it will result in
  66. // a call to 'onresize' below which will regenerate the geometry.
  67. _dimensions = dimensions;
  68. _ratio = dimensions.x / dimensions.y;
  69. return true;
  70. }
  71. void ElementImage::OnRender()
  72. {
  73. // Regenerate the geometry if required (this will be set if 'rect' changes but does not result in a resize).
  74. if (geometry_dirty)
  75. GenerateGeometry();
  76. // Render the geometry beginning at this element's content region.
  77. geometry.Render(GetAbsoluteOffset(BoxArea::Content).Round());
  78. }
  79. void ElementImage::OnAttributeChange(const ElementAttributes& changed_attributes)
  80. {
  81. // Call through to the base element's OnAttributeChange().
  82. Element::OnAttributeChange(changed_attributes);
  83. bool dirty_layout = false;
  84. // Check for a changed 'src' attribute. If this changes, the old texture handle is released,
  85. // forcing a reload when the layout is regenerated.
  86. if (changed_attributes.find("src") != changed_attributes.end() || changed_attributes.find("sprite") != changed_attributes.end())
  87. {
  88. texture_dirty = true;
  89. dirty_layout = true;
  90. }
  91. // Check for a changed 'width' attribute. If this changes, a layout is forced which will
  92. // recalculate the dimensions.
  93. if (changed_attributes.find("width") != changed_attributes.end() || changed_attributes.find("height") != changed_attributes.end())
  94. {
  95. dirty_layout = true;
  96. }
  97. // Check for a change to the 'rect' attribute. If this changes, the coordinates are
  98. // recomputed and a layout forced. If a sprite is set to source, then that will override any attribute.
  99. if (changed_attributes.find("rect") != changed_attributes.end())
  100. {
  101. UpdateRect();
  102. // Rectangle has changed; this will most likely result in a size change, so we need to force a layout.
  103. dirty_layout = true;
  104. }
  105. if (dirty_layout)
  106. DirtyLayout();
  107. }
  108. void ElementImage::OnPropertyChange(const PropertyIdSet& changed_properties)
  109. {
  110. Element::OnPropertyChange(changed_properties);
  111. if (changed_properties.Contains(PropertyId::ImageColor) || changed_properties.Contains(PropertyId::Opacity))
  112. {
  113. GenerateGeometry();
  114. }
  115. }
  116. void ElementImage::OnChildAdd(Element* child)
  117. {
  118. // Load the texture once we have attached to the document so that it can immediately be found during the call to `Rml::GetTextureSourceList`. The
  119. // texture won't actually be loaded from the backend before it is shown. However, only do this if we have an active context so that the dp-ratio
  120. // can be retrieved. If there is no context now the texture loading will be deferred until the next layout update.
  121. if (child == this && texture_dirty && GetContext())
  122. {
  123. LoadTexture();
  124. }
  125. }
  126. void ElementImage::OnResize()
  127. {
  128. GenerateGeometry();
  129. }
  130. void ElementImage::OnDpRatioChange()
  131. {
  132. texture_dirty = true;
  133. DirtyLayout();
  134. }
  135. void ElementImage::OnStyleSheetChange()
  136. {
  137. if (HasAttribute("sprite"))
  138. {
  139. texture_dirty = true;
  140. DirtyLayout();
  141. }
  142. }
  143. void ElementImage::GenerateGeometry()
  144. {
  145. // Release the old geometry before specifying the new vertices.
  146. geometry.Release(true);
  147. Vector<Vertex>& vertices = geometry.GetVertices();
  148. Vector<int>& indices = geometry.GetIndices();
  149. vertices.resize(4);
  150. indices.resize(6);
  151. // Generate the texture coordinates.
  152. Vector2f texcoords[2];
  153. if (rect_source != RectSource::None)
  154. {
  155. Vector2f texture_dimensions = Vector2f(Math::Max(texture.GetDimensions(), Vector2i(1)));
  156. texcoords[0] = rect.TopLeft() / texture_dimensions;
  157. texcoords[1] = rect.BottomRight() / texture_dimensions;
  158. }
  159. else
  160. {
  161. texcoords[0] = Vector2f(0, 0);
  162. texcoords[1] = Vector2f(1, 1);
  163. }
  164. const ComputedValues& computed = GetComputedValues();
  165. ColourbPremultiplied quad_colour = computed.image_color().ToPremultiplied(computed.opacity());
  166. Vector2f quad_size = GetBox().GetSize(BoxArea::Content).Round();
  167. GeometryUtilities::GenerateQuad(&vertices[0], &indices[0], Vector2f(0, 0), quad_size, quad_colour, texcoords[0], texcoords[1]);
  168. geometry_dirty = false;
  169. }
  170. bool ElementImage::LoadTexture()
  171. {
  172. texture_dirty = false;
  173. geometry_dirty = true;
  174. dimensions_scale = 1.0f;
  175. const float dp_ratio = ElementUtilities::GetDensityIndependentPixelRatio(this);
  176. // Check for a sprite first, this takes precedence.
  177. const String sprite_name = GetAttribute<String>("sprite", "");
  178. if (!sprite_name.empty())
  179. {
  180. // Load sprite.
  181. bool valid_sprite = false;
  182. if (ElementDocument* document = GetOwnerDocument())
  183. {
  184. if (const StyleSheet* style_sheet = document->GetStyleSheet())
  185. {
  186. if (const Sprite* sprite = style_sheet->GetSprite(sprite_name))
  187. {
  188. rect = sprite->rectangle;
  189. rect_source = RectSource::Sprite;
  190. texture = sprite->sprite_sheet->texture;
  191. dimensions_scale = sprite->sprite_sheet->display_scale * dp_ratio;
  192. valid_sprite = true;
  193. }
  194. }
  195. }
  196. if (!valid_sprite)
  197. {
  198. texture = Texture();
  199. rect_source = RectSource::None;
  200. UpdateRect();
  201. Log::Message(Log::LT_WARNING, "Could not find sprite '%s' specified in img element %s", sprite_name.c_str(), GetAddress().c_str());
  202. return false;
  203. }
  204. }
  205. else
  206. {
  207. // Load image from source URL.
  208. const String source_name = GetAttribute<String>("src", "");
  209. if (source_name.empty())
  210. {
  211. texture = Texture();
  212. rect_source = RectSource::None;
  213. return false;
  214. }
  215. URL source_url;
  216. if (ElementDocument* document = GetOwnerDocument())
  217. source_url.SetURL(document->GetSourceURL());
  218. texture.Set(source_name, source_url.GetPath());
  219. dimensions_scale = dp_ratio;
  220. }
  221. // Set the texture onto our geometry object.
  222. geometry.SetTexture(&texture);
  223. return true;
  224. }
  225. void ElementImage::UpdateRect()
  226. {
  227. if (rect_source != RectSource::Sprite)
  228. {
  229. bool valid_rect = false;
  230. String rect_string = GetAttribute<String>("rect", "");
  231. if (!rect_string.empty())
  232. {
  233. StringList coords_list;
  234. StringUtilities::ExpandString(coords_list, rect_string, ' ');
  235. if (coords_list.size() != 4)
  236. {
  237. Log::Message(Log::LT_WARNING, "Element '%s' has an invalid 'rect' attribute; rect requires 4 space-separated values, found %zu.",
  238. GetAddress().c_str(), coords_list.size());
  239. }
  240. else
  241. {
  242. const Vector2f position = {FromString(coords_list[0], 0.f), FromString(coords_list[1], 0.f)};
  243. const Vector2f size = {FromString(coords_list[2], 0.f), FromString(coords_list[3], 0.f)};
  244. rect = Rectanglef::FromPositionSize(position, size);
  245. // We have new, valid coordinates; force the geometry to be regenerated.
  246. valid_rect = true;
  247. geometry_dirty = true;
  248. rect_source = RectSource::Attribute;
  249. }
  250. }
  251. if (!valid_rect)
  252. {
  253. rect = {};
  254. rect_source = RectSource::None;
  255. }
  256. }
  257. }
  258. } // namespace Rml