diff --git a/Source/HtmlRenderer/Adapters/RAdapter.cs b/Source/HtmlRenderer/Adapters/RAdapter.cs index dad5b9cf1..85bbc2209 100644 --- a/Source/HtmlRenderer/Adapters/RAdapter.cs +++ b/Source/HtmlRenderer/Adapters/RAdapter.cs @@ -45,12 +45,13 @@ public abstract class RAdapter /// /// cache of brush color to brush instance /// + /// The adapter is shared by every container, the caches are locked on themselves. private readonly Dictionary _brushesCache = new Dictionary(); /// - /// cache of pen color to pen instance + /// cache of pens, a cached pen is never changed, since another thread may be drawing with it /// - private readonly Dictionary _penCache = new Dictionary(); + private readonly Dictionary<(RColor Color, double Width, RDashStyle DashStyle), RPen> _penCache = new Dictionary<(RColor, double, RDashStyle), RPen>(); /// /// cache of all the font used not to create same font again and again @@ -256,18 +257,36 @@ public RColor GetColor(string colorName) } /// - /// Get cached pen instance for the given color. + /// Get cached solid pen instance for the given color, 1 wide. /// /// the color to get pen for - /// pen instance + /// pen instance, don't change it public RPen GetPen(RColor color) { - RPen pen; - if (!_penCache.TryGetValue(color, out pen)) + return GetPen(color, 1, RDashStyle.Solid); + } + + /// + /// Get cached pen instance for the given color, width and dash style. + /// + /// the color to get pen for + /// the width of the pen + /// the dash style of the pen + /// pen instance, don't change it + public RPen GetPen(RColor color, double width, RDashStyle dashStyle) + { + lock (_penCache) { - _penCache[color] = pen = CreatePen(color); + RPen pen; + if (!_penCache.TryGetValue((color, width, dashStyle), out pen)) + { + pen = CreatePen(color); + pen.Width = width; + pen.DashStyle = dashStyle; + _penCache[(color, width, dashStyle)] = pen; + } + return pen; } - return pen; } /// @@ -277,12 +296,15 @@ public RPen GetPen(RColor color) /// brush instance public RBrush GetSolidBrush(RColor color) { - RBrush brush; - if (!_brushesCache.TryGetValue(color, out brush)) + lock (_brushesCache) { - _brushesCache[color] = brush = CreateSolidBrush(color); + RBrush brush; + if (!_brushesCache.TryGetValue(color, out brush)) + { + _brushesCache[color] = brush = CreateSolidBrush(color); + } + return brush; } - return brush; } /// @@ -372,7 +394,13 @@ public void AddFontFamilyMapping(string fromFamily, string toFamily) public virtual async Task AddFontFace(string familyName, RUri uri, int weight, bool isItalic, int stretch, IReadOnlyList ranges) { RFontFamily fontFamily; - if (!_fontFaceCache.TryGetValue(uri.AbsoluteUri, out fontFamily)) + bool cached; + lock (_fontFaceCache) + { + cached = _fontFaceCache.TryGetValue(uri.AbsoluteUri, out fontFamily); + } + + if (!cached) { var networkResponse = await GetResourceStream(uri).ConfigureAwait(false); if (networkResponse == null || networkResponse.ResourceStream == null) @@ -404,7 +432,14 @@ public virtual async Task AddFontFace(string familyName, RUri uri, int wei return false; } - _fontFaceCache[uri.AbsoluteUri] = fontFamily; + lock (_fontFaceCache) + { + // Another container may have loaded the same face in the mean time, keep the first + if (_fontFaceCache.TryGetValue(uri.AbsoluteUri, out var existing)) + fontFamily = existing; + else + _fontFaceCache[uri.AbsoluteUri] = fontFamily; + } } _fontsHandler.AddFontFace(familyName, fontFamily, weight, isItalic, stretch, ranges); diff --git a/Source/HtmlRenderer/Adapters/RGraphics.cs b/Source/HtmlRenderer/Adapters/RGraphics.cs index 22ba0df77..e9ff12dee 100644 --- a/Source/HtmlRenderer/Adapters/RGraphics.cs +++ b/Source/HtmlRenderer/Adapters/RGraphics.cs @@ -56,15 +56,27 @@ protected RGraphics(RAdapter adapter, RRect initialClip) } /// - /// Get color pen. + /// Get solid color pen, 1 wide. /// /// the color to get the pen for - /// pen instance + /// pen instance, shared, don't change it public RPen GetPen(RColor color) { return _adapter.GetPen(color); } + /// + /// Get color pen with the given width and dash style. + /// + /// the color to get the pen for + /// the width of the pen + /// the dash style of the pen + /// pen instance, shared, don't change it + public RPen GetPen(RColor color, double width, RDashStyle dashStyle) + { + return _adapter.GetPen(color, width, dashStyle); + } + /// /// Get solid color brush. /// diff --git a/Source/HtmlRenderer/Core/Dom/CssBox.cs b/Source/HtmlRenderer/Core/Dom/CssBox.cs index 388cef667..018c8a29a 100644 --- a/Source/HtmlRenderer/Core/Dom/CssBox.cs +++ b/Source/HtmlRenderer/Core/Dom/CssBox.cs @@ -1958,8 +1958,6 @@ internal void PaintDecoration(RGraphics g, RRect rectangle, bool isFirst, bool i var bottomInset = ActualPaddingBottom - ActualBorderBottomWidth; var pen = g.GetPen(ActualColor); - pen.Width = 1; - pen.DashStyle = RDashStyle.Solid; // CSS 2.1 ยง16.3.1, the value can list several lines. foreach (var line in TextDecoration.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) diff --git a/Source/HtmlRenderer/Core/Handlers/BordersDrawHandler.cs b/Source/HtmlRenderer/Core/Handlers/BordersDrawHandler.cs index 6099b2242..4ef54c628 100644 --- a/Source/HtmlRenderer/Core/Handlers/BordersDrawHandler.cs +++ b/Source/HtmlRenderer/Core/Handlers/BordersDrawHandler.cs @@ -282,21 +282,15 @@ private static RGraphicsPath GetRoundedBorderPath(RGraphics g, Border border, Cs /// private static RPen GetPen(RGraphics g, string style, RColor color, double width) { - var p = g.GetPen(color); - p.Width = width; switch (style) { - case "solid": - p.DashStyle = RDashStyle.Solid; - break; case "dotted": - p.DashStyle = RDashStyle.Dot; - break; + return g.GetPen(color, width, RDashStyle.Dot); case "dashed": - p.DashStyle = RDashStyle.Dash; - break; + return g.GetPen(color, width, RDashStyle.Dash); + default: + return g.GetPen(color, width, RDashStyle.Solid); } - return p; } /// diff --git a/Source/HtmlRenderer/Core/Handlers/FontsHandler.cs b/Source/HtmlRenderer/Core/Handlers/FontsHandler.cs index f9f49f218..5f68eca5a 100644 --- a/Source/HtmlRenderer/Core/Handlers/FontsHandler.cs +++ b/Source/HtmlRenderer/Core/Handlers/FontsHandler.cs @@ -65,6 +65,11 @@ internal sealed class FontsHandler /// private readonly RAdapter _adapter; + /// + /// Guards the dictionaries below, the adapter and with it this handler is shared by every container. + /// + private readonly object _lock = new object(); + /// /// Allow to map not installed fonts to different /// @@ -107,16 +112,19 @@ public FontsHandler(RAdapter adapter) /// true - font exists by given family name, false - otherwise public bool IsFontExists(string family) { - bool exists = _existingFontFamilies.ContainsKey(family); - if (!exists) + lock (_lock) { - string mappedFamily; - if (_fontsMapping.TryGetValue(family, out mappedFamily)) + bool exists = _existingFontFamilies.ContainsKey(family); + if (!exists) { - exists = _existingFontFamilies.ContainsKey(mappedFamily); + string mappedFamily; + if (_fontsMapping.TryGetValue(family, out mappedFamily)) + { + exists = _existingFontFamilies.ContainsKey(mappedFamily); + } } + return exists; } - return exists; } /// @@ -126,12 +134,15 @@ public bool IsFontExists(string family) /// public RFontFamily TryGetExistingFamily(string family) { - FontFamilyModel model; - if (!_existingFontFamilies.TryGetValue(family, out model)) + lock (_lock) { - return null; + FontFamilyModel model; + if (!_existingFontFamilies.TryGetValue(family, out model)) + { + return null; + } + return model.SimpleFamily ?? (model.Faces.Count > 0 ? model.Faces[0].FontFamily : null); } - return model.SimpleFamily ?? (model.Faces.Count > 0 ? model.Faces[0].FontFamily : null); } /// @@ -140,15 +151,18 @@ public RFontFamily TryGetExistingFamily(string family) /// The font family to add. public void AddFontFamily(RFontFamily fontFamily) { - ArgChecker.AssertArgNotNull(fontFamily, "family"); - - FontFamilyModel model; - if (!_existingFontFamilies.TryGetValue(fontFamily.Name, out model)) + lock (_lock) { - model = new FontFamilyModel { Name = fontFamily.Name }; - _existingFontFamilies[fontFamily.Name] = model; + ArgChecker.AssertArgNotNull(fontFamily, "family"); + + FontFamilyModel model; + if (!_existingFontFamilies.TryGetValue(fontFamily.Name, out model)) + { + model = new FontFamilyModel { Name = fontFamily.Name }; + _existingFontFamilies[fontFamily.Name] = model; + } + model.SimpleFamily = fontFamily; } - model.SimpleFamily = fontFamily; } /// @@ -160,10 +174,13 @@ public void AddFontFamily(RFontFamily fontFamily) /// the font family to replace with public void AddFontFamilyMapping(string fromFamily, string toFamily) { - ArgChecker.AssertArgNotNullOrEmpty(fromFamily, "fromFamily"); - ArgChecker.AssertArgNotNullOrEmpty(toFamily, "toFamily"); + lock (_lock) + { + ArgChecker.AssertArgNotNullOrEmpty(fromFamily, "fromFamily"); + ArgChecker.AssertArgNotNullOrEmpty(toFamily, "toFamily"); - _fontsMapping[fromFamily] = toFamily; + _fontsMapping[fromFamily] = toFamily; + } } /// @@ -178,29 +195,32 @@ public void AddFontFamilyMapping(string fromFamily, string toFamily) /// the unicode-range, or null for any character public void AddFontFace(string familyName, RFontFamily fontFamily, int weight, bool isItalic, int stretch, IReadOnlyList ranges) { - ArgChecker.AssertArgNotNullOrEmpty(familyName, "familyName"); - ArgChecker.AssertArgNotNull(fontFamily, "fontFamily"); - - FontFamilyModel model; - if (!_existingFontFamilies.TryGetValue(familyName, out model)) + lock (_lock) { - model = new FontFamilyModel { Name = familyName }; - _existingFontFamilies[familyName] = model; - } + ArgChecker.AssertArgNotNullOrEmpty(familyName, "familyName"); + ArgChecker.AssertArgNotNull(fontFamily, "fontFamily"); - for (var i = model.Faces.Count - 1; i >= 0; i--) - { - if (IsSameFaceSlot(model.Faces[i], weight, isItalic, stretch, ranges)) + FontFamilyModel model; + if (!_existingFontFamilies.TryGetValue(familyName, out model)) { - model.Faces.RemoveAt(i); + model = new FontFamilyModel { Name = familyName }; + _existingFontFamilies[familyName] = model; } - } - model.Faces.Add(new FontFaceEntry(weight, isItalic, stretch, ranges, fontFamily)); + for (var i = model.Faces.Count - 1; i >= 0; i--) + { + if (IsSameFaceSlot(model.Faces[i], weight, isItalic, stretch, ranges)) + { + model.Faces.RemoveAt(i); + } + } - // A new face can change which face is nearest for a request. - _fontsCache.Remove(familyName); - _faceFontsCache.Remove(familyName); + model.Faces.Add(new FontFaceEntry(weight, isItalic, stretch, ranges, fontFamily)); + + // A new face can change which face is nearest for a request. + _fontsCache.Remove(familyName); + _faceFontsCache.Remove(familyName); + } } /// @@ -210,31 +230,34 @@ public void AddFontFace(string familyName, RFontFamily fontFamily, int weight, b /// cached font instance public RFont GetCachedFont(string family, double size, RFontStyle style) { - var font = TryGetFont(family, size, style); - if (font == null) + lock (_lock) { - if (!_existingFontFamilies.ContainsKey(family)) + var font = TryGetFont(family, size, style); + if (font == null) { - string mappedFamily; - if (_fontsMapping.TryGetValue(family, out mappedFamily)) + if (!_existingFontFamilies.ContainsKey(family)) { - font = TryGetFont(mappedFamily, size, style); - if (font == null) + string mappedFamily; + if (_fontsMapping.TryGetValue(family, out mappedFamily)) { - font = CreateFont(mappedFamily, size, style); - _fontsCache[mappedFamily][size][style] = font; + font = TryGetFont(mappedFamily, size, style); + if (font == null) + { + font = CreateFont(mappedFamily, size, style); + _fontsCache[mappedFamily][size][style] = font; + } } } - } - if (font == null) - { - font = CreateFont(family, size, style); - } + if (font == null) + { + font = CreateFont(family, size, style); + } - _fontsCache[family][size][style] = font; + _fontsCache[family][size][style] = font; + } + return font; } - return font; } /// @@ -254,27 +277,30 @@ public RFont GetCachedFont(string family, double size, RFontStyle style) /// public RFont GetCachedFont(string family, double size, RFontStyle style, int weight, int stretch, int? codepoint) { - FontFamilyModel model; - if (_existingFontFamilies.TryGetValue(family, out model) && model.Faces.Count > 0) + lock (_lock) { - var requestedItalic = (style & RFontStyle.Italic) != 0; - - FontFaceEntry face; - if (TryFindNearestFace(model, weight, requestedItalic, stretch, codepoint, out face)) + FontFamilyModel model; + if (_existingFontFamilies.TryGetValue(family, out model) && model.Faces.Count > 0) { - return GetCachedFaceFont(family, face, size, style, weight, requestedItalic, stretch, codepoint ?? -1); - } + var requestedItalic = (style & RFontStyle.Italic) != 0; - if (codepoint != null) - { - // Don't substitute a face that doesn't cover the character. - return null; + FontFaceEntry face; + if (TryFindNearestFace(model, weight, requestedItalic, stretch, codepoint, out face)) + { + return GetCachedFaceFont(family, face, size, style, weight, requestedItalic, stretch, codepoint ?? -1); + } + + if (codepoint != null) + { + // Don't substitute a face that doesn't cover the character. + return null; + } + + // Can't happen, AddFontFace always leaves a face registered. } - // Can't happen, AddFontFace always leaves a face registered. + return GetCachedFont(family, size, style); } - - return GetCachedFont(family, size, style); } diff --git a/Source/HtmlRenderer/Core/Parse/RegexParserUtils.cs b/Source/HtmlRenderer/Core/Parse/RegexParserUtils.cs index a3f90ff50..b877bca52 100644 --- a/Source/HtmlRenderer/Core/Parse/RegexParserUtils.cs +++ b/Source/HtmlRenderer/Core/Parse/RegexParserUtils.cs @@ -10,7 +10,7 @@ // - Sun Tsu, // "The Art of War" -using System.Collections.Generic; +using System.Collections.Concurrent; using System.Text.RegularExpressions; namespace TheArtOfDev.HtmlRenderer.Core.Parse @@ -87,7 +87,8 @@ internal static class RegexParserUtils /// /// the regexes cache that is used by the parser so not to create regex each time /// - private static readonly Dictionary _regexes = new Dictionary(); + /// Shared by every container, which can lay out on different threads. + private static readonly ConcurrentDictionary _regexes = new ConcurrentDictionary(); #endregion @@ -186,13 +187,7 @@ public static string Search(string regex, string source, out int position) /// the regex instance private static Regex GetRegex(string regex) { - Regex r; - if (!_regexes.TryGetValue(regex, out r)) - { - r = new Regex(regex, RegexOptions.IgnoreCase | RegexOptions.Singleline); - _regexes[regex] = r; - } - return r; + return _regexes.GetOrAdd(regex, r => new Regex(r, RegexOptions.IgnoreCase | RegexOptions.Singleline)); } } } diff --git a/Source/Test/HtmlRenderer.Test/Adapters/PenCacheTests.cs b/Source/Test/HtmlRenderer.Test/Adapters/PenCacheTests.cs new file mode 100644 index 000000000..ba2bb6179 --- /dev/null +++ b/Source/Test/HtmlRenderer.Test/Adapters/PenCacheTests.cs @@ -0,0 +1,42 @@ +using HtmlRenderer.Test.TestSupport; +using TheArtOfDev.HtmlRenderer.Adapters.Entities; +using TheArtOfDev.HtmlRenderer.Core; + +namespace HtmlRenderer.Test.Adapters; + +[TestClass] +public sealed class PenCacheTests +{ + [TestMethod] + public void PaintingADashedBorder_LeavesThePlainPenOfItsColorUnchanged() + { + var adapter = new MockAdapter(); + var container = new HtmlContainerInt(adapter) { MaxSize = new RSize(800, 600), PageSize = new RSize(800, 600) }; + container.SetHtml("
"); + var graphics = new RecordingGraphics(adapter); + container.PerformLayout(graphics); + container.PerformPaint(graphics); + + var pen = (MockPen)adapter.GetPen(RColor.FromArgb(255, 255, 0, 0)); + + Assert.AreEqual(1, pen.Width); + Assert.AreEqual(RDashStyle.Solid, pen.RecordedDashStyle); + } + + [TestMethod] + public void PensOfTheSameColor_WithDifferentWidthsOrDashes_AreDifferentInstances() + { + var adapter = new MockAdapter(); + var red = RColor.FromArgb(255, 255, 0, 0); + + var thin = adapter.GetPen(red); + var thick = adapter.GetPen(red, 3, RDashStyle.Solid); + var dashed = adapter.GetPen(red, 3, RDashStyle.Dash); + + Assert.AreNotSame(thin, thick); + Assert.AreNotSame(thick, dashed); + Assert.AreSame(thick, adapter.GetPen(red, 3, RDashStyle.Solid)); + Assert.AreEqual(3, ((MockPen)thick).Width); + Assert.AreEqual(RDashStyle.Dash, ((MockPen)dashed).RecordedDashStyle); + } +}