ElementImage.cpp 9.6 KB

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