From 6284264ca3c33f0c22ef42e562d1ae7c19e44027 Mon Sep 17 00:00:00 2001
From: Cyrus Bakhtiari-Haftlang <cyrus.bh@gmail.com>
Date: Wed, 30 Sep 2020 09:26:56 +0200
Subject: [PATCH] Resolves style issues in CustomTypefaceSpan

When two or more `CustomTypefaceSpan` are applied on a same character
sequence, previous `TextPaint`'s style was not respected.

Example:
--------
**Strong Emphasis _strong emphasis and emphasis combined_**

Before the inner text will only have the font applied without respecting
that the outer text is strong.

Related [bug report](https://issuetracker.google.com/issues/169658958)
on Google:
---
 .../markwon/core/spans/CustomTypefaceSpan.java   | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/markwon-core/src/main/java/io/noties/markwon/core/spans/CustomTypefaceSpan.java b/markwon-core/src/main/java/io/noties/markwon/core/spans/CustomTypefaceSpan.java
index b12a80d6..2d5ac089 100644
--- a/markwon-core/src/main/java/io/noties/markwon/core/spans/CustomTypefaceSpan.java
+++ b/markwon-core/src/main/java/io/noties/markwon/core/spans/CustomTypefaceSpan.java
@@ -1,5 +1,6 @@
 package io.noties.markwon.core.spans;
 
+import android.annotation.SuppressLint;
 import android.graphics.Typeface;
 import android.text.TextPaint;
 import android.text.style.MetricAffectingSpan;
@@ -34,11 +35,22 @@ public class CustomTypefaceSpan extends MetricAffectingSpan {
     }
 
     @Override
-    public void updateDrawState(TextPaint tp) {
+    public void updateDrawState(@NonNull TextPaint tp) {
         updatePaint(tp);
     }
 
     private void updatePaint(@NonNull TextPaint paint) {
-        paint.setTypeface(typeface);
+        final Typeface old = paint.getTypeface();
+        final int oldStyle;
+        if (old == null) {
+            oldStyle = Typeface.NORMAL;
+        } else {
+            oldStyle = old.getStyle();
+        }
+
+        @SuppressLint("WrongConstant") final int want = oldStyle | typeface.getStyle();
+        final Typeface styledTypeface = Typeface.create(typeface, want);
+
+        paint.setTypeface(styledTypeface);
     }
 }