[gnome-text-editor] recoloring: improve dark style scheme detection



commit f9b62ed9869b15112ca19461a9053b9e75984582
Author: Christian Hergert <chergert redhat com>
Date:   Fri Dec 3 12:56:34 2021 -0800

    recoloring: improve dark style scheme detection
    
    As a fallback, after metadata and id, we can resort to checking the text
    background and calculating an HSP value.
    
    Related #139

 src/editor-recoloring-private.h |  3 ++-
 src/editor-recoloring.c         | 29 +++++++++++++++++++++++------
 2 files changed, 25 insertions(+), 7 deletions(-)
---
diff --git a/src/editor-recoloring-private.h b/src/editor-recoloring-private.h
index 147611c..0abe22c 100644
--- a/src/editor-recoloring-private.h
+++ b/src/editor-recoloring-private.h
@@ -24,6 +24,7 @@
 
 G_BEGIN_DECLS
 
-char *_editor_recoloring_generate_css (GtkSourceStyleScheme *style_scheme);
+char     *_editor_recoloring_generate_css     (GtkSourceStyleScheme *style_scheme);
+gboolean  _editor_source_style_scheme_is_dark (GtkSourceStyleScheme *style_scheme);
 
 G_END_DECLS
diff --git a/src/editor-recoloring.c b/src/editor-recoloring.c
index e0d7b27..db661d2 100644
--- a/src/editor-recoloring.c
+++ b/src/editor-recoloring.c
@@ -20,6 +20,8 @@
 
 #include "config.h"
 
+#include <math.h>
+
 #include "editor-recoloring-private.h"
 
 #define SHARED_CSS \
@@ -160,18 +162,33 @@ premix_colors (GdkRGBA       *dest,
     }
 }
 
-static gboolean
-scheme_is_dark (GtkSourceStyleScheme *scheme)
+gboolean
+_editor_source_style_scheme_is_dark (GtkSourceStyleScheme *scheme)
 {
   const char *id = gtk_source_style_scheme_get_id (scheme);
   const char *variant = gtk_source_style_scheme_get_metadata (scheme, "variant");
+  GdkRGBA text_bg;
 
-  if (strstr (id, "-dark") != NULL)
+  if (g_strcmp0 (variant, "light") == 0)
+    return FALSE;
+  else if (g_strcmp0 (variant, "dark") == 0)
     return TRUE;
-
-  if (g_strcmp0 (variant, "dark") == 0)
+  else if (strstr (id, "-dark") != NULL)
     return TRUE;
 
+  if (get_background (scheme, "text", &text_bg))
+    {
+      /* http://alienryderflex.com/hsp.html */
+      double r = text_bg.red * 255.0;
+      double g = text_bg.green * 255.0;
+      double b = text_bg.blue * 255.0;
+      double hsp = sqrt (0.299 * (r * r) +
+                         0.587 * (g * g) +
+                         0.114 * (b * b));
+
+      return hsp <= 127.5;
+    }
+
   return FALSE;
 }
 
@@ -198,7 +215,7 @@ _editor_recoloring_generate_css (GtkSourceStyleScheme *style_scheme)
     return NULL;
 
   name = gtk_source_style_scheme_get_name (style_scheme);
-  is_dark = scheme_is_dark (style_scheme);
+  is_dark = _editor_source_style_scheme_is_dark (style_scheme);
   alt = is_dark ? &white : &black;
 
   str = g_string_new (SHARED_CSS);


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]