ElementImage.cpp 9.6 KB

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