Merge branch 'rgba-new-from-string' into 'main'

Add convenience function gdk_rgba_new_from_string()

See merge request GNOME/gtk!6599
This commit is contained in:
Matthias Clasen 2023-11-28 17:56:21 +00:00
commit 77f40d7508
3 changed files with 47 additions and 0 deletions

View File

@ -54,6 +54,30 @@ G_DEFINE_BOXED_TYPE (GdkRGBA, gdk_rgba,
* be clamped to this range when drawing.
*/
/**
* gdk_rgba_new_from_string:
* @spec: A string specifying a color
*
* Allocates a new `GdkRGBA` and populates it with the color values
* represented by @spec.
*
* If @spec does not conform to the formats specified by
* [method@Gdk.RGBA.parse], this function will return `NULL`.
*
* Returns: (transfer full) (nullable): A newly allocated `GdkRGBA`
*
* Since: 4.14
*/
GdkRGBA *
gdk_rgba_new_from_string (const char *spec)
{
GdkRGBA *out = g_new (GdkRGBA, 1);
if (gdk_rgba_parse (out, spec))
return out;
gdk_rgba_free (out);
return NULL;
}
/**
* gdk_rgba_copy:
* @rgba: a `GdkRGBA`

View File

@ -45,6 +45,9 @@ struct _GdkRGBA
GDK_AVAILABLE_IN_ALL
GType gdk_rgba_get_type (void) G_GNUC_CONST;
GDK_AVAILABLE_IN_4_14
GdkRGBA * gdk_rgba_new_from_string (const char *spec);
GDK_AVAILABLE_IN_ALL
GdkRGBA * gdk_rgba_copy (const GdkRGBA *rgba);
GDK_AVAILABLE_IN_ALL

View File

@ -207,6 +207,25 @@ test_color_hash (void)
g_assert_cmpuint (hash1, !=, hash2);
}
static void
test_alloc_from_string (void)
{
GdkRGBA expected = {
.red = 1.0,
.green = 0.0,
.blue = 1.0,
.alpha = 1.0,
};
GdkRGBA *parsed = gdk_rgba_new_from_string ("#ff00ff");
g_assert_true (gdk_rgba_equal (&expected, parsed));
gdk_rgba_free (parsed);
GdkRGBA *fail = gdk_rgba_new_from_string ("//xx!!");
g_assert_null (fail);
}
int
main (int argc, char *argv[])
{
@ -217,6 +236,7 @@ main (int argc, char *argv[])
g_test_add_func ("/rgba/to-string", test_color_to_string);
g_test_add_func ("/rgba/copy", test_color_copy);
g_test_add_func ("/rgba/hash", test_color_hash);
g_test_add_func ("/rgba/from-string", test_alloc_from_string);
return g_test_run ();
}