<commit_before>/*
 * This file is part of GtkSourceView
 *
 * Copyright 2008, 2011, 2016 - <NAME> <<EMAIL>>
 * Copyright 2008, 2010 - <NAME> <<EMAIL>>
 * Copyright 2010 - <NAME>
 * Copyright 2013 - <NAME> <<EMAIL>>
 * Copyright 2015, 2016 - <NAME> <<EMAIL>>
 * Copyright 2016 - <NAME> <<EMAIL>>
 *
 * GtkSourceView is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * GtkSourceView is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"

#include "gtksourcespacedrawer.h"
#include "gtksourcespacedrawer-private.h"
#include "gtksourcebuffer.h"
#include "gtksourcebuffer-private.h"
#include "gtksourceiter-private.h"
#include "gtksourcestylescheme.h"
#include "gtksourcestylescheme-private.h"
#include "gtksourcetag.h"
#include "gtksourceview.h"

/**
 * SECTION:spacedrawer
 * @Short_description: Represent white space characters with symbols
 * @Title: GtkSourceSpaceDrawer
 * @See_also: #GtkSourceView
 *
 * #GtkSourceSpaceDrawer provides a way to visualize white spaces, by drawing
 * symbols.
 *
 * Call gtk_source_view_get_space_drawer() to get the #GtkSourceSpaceDrawer
 * instance of a certain #GtkSourceView.
 *
 * By default, no white spaces are drawn because the
 * #GtkSourceSpaceDrawer:enable-matrix is %FALSE.
 *
 * To draw white spaces, gtk_source_space_drawer_set_types_for_locations() can
 * be called to set the #GtkSourceSpaceDrawer:matrix property (by default all
 * space types are enabled at all locations). Then call
 * gtk_source_space_drawer_set_enable_matrix().
 *
 * For a finer-grained method, there is also the GtkSourceTag's
 * #GtkSourceTag:draw-spaces property.
 *
 * # Example
 *
 * To draw non-breaking spaces everywhere and draw all types of trailing spaces
 * except newlines:
 * |[
 * gtk_source_space_drawer_set_types_for_locations (space_drawer,
 *                                                  GTK_SOURCE_SPACE_LOCATION_ALL,
 *                                                  GTK_SOURCE_SPACE_TYPE_NBSP);
 *
 * gtk_source_space_drawer_set_types_for_locations (space_drawer,
 *                                                  GTK_SOURCE_SPACE_LOCATION_TRAILING,
 *                                                  GTK_SOURCE_SPACE_TYPE_ALL &
 *                                                  ~GTK_SOURCE_SPACE_TYPE_NEWLINE);
 *
 * gtk_source_space_drawer_set_enable_matrix (space_drawer, TRUE);
 * ]|
 *
 * # Use-case: draw unwanted white spaces
 *
 * A possible use-case is to draw only unwanted white spaces. Examples:
 * - Draw all trailing spaces.
 * - If the indentation and alignment must be done with spaces, draw tabs.
 *
 * And non-breaking spaces can always be drawn, everywhere, to distinguish them
 * from normal spaces.
 */

/* A drawer specially designed for the International Space Station. It comes by
 * default with a DVD of Matrix, in case the astronauts are bored.
 */

#if 0
# define ENABLE_PROFILE
#else
# undef ENABLE_PROFILE
#endif

typedef enum
{
	DRAW_TAB,
	DRAW_NARROW_NBSP,
	DRAW_NBSP,
	DRAW_SPACE,
	DRAW_NEWLINE,
	N_DRAW
} Draw;

typedef struct
{
	GskRenderNode *node;
	gint           width;
	gint           height;
} CachedNode;

struct _GtkSourceSpaceDrawer
{
	GObject                  parent_instance;

	GtkSourceSpaceTypeFlags *matrix;

	CachedNode               cached[N_DRAW];

	GdkRGBA                  color;

	guint                    color_set : 1;
	guint                    enable_matrix : 1;
};

enum
{
	PROP_0,
	PROP_ENABLE_MATRIX,
	PROP_MATRIX,
	N_PROPERTIES
};

static GParamSpec *properties[N_PROPERTIES];

G_DEFINE_TYPE (GtkSourceSpaceDrawer, gtk_source_space_drawer, G_TYPE_OBJECT)

static void
gtk_source_space_drawer_purge_cache (GtkSourceSpaceDrawer *drawer)
{
	guint i;

	g_return_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer));

	for (i = 0; i < G_N_ELEMENTS (drawer->cached); i++)
	{
		g_clear_pointer (&drawer->cached[i].node, gsk_render_node_unref);
	}
}

static gint
get_number_of_locations (void)
{
	gint num;
	gint flags;

	num = 0;
	flags = GTK_SOURCE_SPACE_LOCATION_ALL;

	while (flags != 0)
	{
		flags >>= 1;
		num++;
	}

	return num;
}

static GVariant *
get_default_matrix (void)
{
	GVariantBuilder builder;
	gint num_locations;
	gint i;

	g_variant_builder_init (&builder, G_VARIANT_TYPE ("au"));

	num_locations = get_number_of_locations ();

	for (i = 0; i < num_locations; i++)
	{
		GVariant *space_types;

		space_types = g_variant_new_uint32 (GTK_SOURCE_SPACE_TYPE_ALL);

		g_variant_builder_add_value (&builder, space_types);
	}

	return g_variant_builder_end (&builder);
}

static gboolean
is_zero_matrix (GtkSourceSpaceDrawer *drawer)
{
	gint num_locations;
	gint i;

	num_locations = get_number_of_locations ();

	for (i = 0; i < num_locations; i++)
	{
		if (drawer->matrix[i] != 0)
		{
			return FALSE;
		}
	}

	return TRUE;
}

static void
set_zero_matrix (GtkSourceSpaceDrawer *drawer)
{
	gint num_locations;
	gint i;
	gboolean changed = FALSE;

	num_locations = get_number_of_locations ();

	for (i = 0; i < num_locations; i++)
	{
		if (drawer->matrix[i] != 0)
		{
			drawer->matrix[i] = 0;
			changed = TRUE;
		}
	}

	if (changed)
	{
		g_object_notify_by_pspec (G_OBJECT (drawer), properties[PROP_MATRIX]);
	}
}

/* AND */
static GtkSourceSpaceTypeFlags
get_types_at_all_locations (GtkSourceSpaceDrawer        *drawer,
                            GtkSourceSpaceLocationFlags  locations)
{
	GtkSourceSpaceTypeFlags ret = GTK_SOURCE_SPACE_TYPE_ALL;
	gint index;
	gint num_locations;
	gboolean found;

	index = 0;
	num_locations = get_number_of_locations ();
	found = FALSE;

	while (locations != 0 && index < num_locations)
	{
		if ((locations & 1) == 1)
		{
			ret &= drawer->matrix[index];
			found = TRUE;
		}

		locations >>= 1;
		index++;
	}

	return found ? ret : GTK_SOURCE_SPACE_TYPE_NONE;
}

/* OR */
static GtkSourceSpaceTypeFlags
get_types_at_any_locations (GtkSourceSpaceDrawer        *drawer,
                            GtkSourceSpaceLocationFlags  locations)
{
	GtkSourceSpaceTypeFlags ret = GTK_SOURCE_SPACE_TYPE_NONE;
	gint index;
	gint num_locations;

	index = 0;
	num_locations = get_number_of_locations ();

	while (locations != 0 && index < num_locations)
	{
		if ((locations & 1) == 1)
		{
			ret |= drawer->matrix[index];
		}

		locations >>= 1;
		index++;
	}

	return ret;
}

static void
gtk_source_space_drawer_get_property (GObject    *object,
                                      guint       prop_id,
                                      GValue     *value,
                                      GParamSpec *pspec)
{
	GtkSourceSpaceDrawer *drawer = GTK_SOURCE_SPACE_DRAWER (object);

	switch (prop_id)
	{
		case PROP_ENABLE_MATRIX:
			g_value_set_boolean (value, gtk_source_space_drawer_get_enable_matrix (drawer));
			break;

		case PROP_MATRIX:
			g_value_set_variant (value, gtk_source_space_drawer_get_matrix (drawer));
			break;

		default:
			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
			break;
	}
}

static void
gtk_source_space_drawer_set_property (GObject      *object,
                                      guint         prop_id,
                                      const GValue *value,
                                      GParamSpec   *pspec)
{
	GtkSourceSpaceDrawer *drawer = GTK_SOURCE_SPACE_DRAWER (object);

	switch (prop_id)
	{
		case PROP_ENABLE_MATRIX:
			gtk_source_space_drawer_set_enable_matrix (drawer, g_value_get_boolean (value));
			break;

		case PROP_MATRIX:
			gtk_source_space_drawer_set_matrix (drawer, g_value_get_variant (value));
			break;

		default:
			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
			break;
	}
}

static void
gtk_source_space_drawer_finalize (GObject *object)
{
	GtkSourceSpaceDrawer *drawer = GTK_SOURCE_SPACE_DRAWER (object);

	gtk_source_space_drawer_purge_cache (drawer);
	g_free (drawer->matrix);

	G_OBJECT_CLASS (gtk_source_space_drawer_parent_class)->finalize (object);
}

static void
gtk_source_space_drawer_class_init (GtkSourceSpaceDrawerClass *klass)
{
	GObjectClass *object_class = G_OBJECT_CLASS (klass);

	object_class->get_property = gtk_source_space_drawer_get_property;
	object_class->set_property = gtk_source_space_drawer_set_property;
	object_class->finalize = gtk_source_space_drawer_finalize;

	/**
	 * GtkSourceSpaceDrawer:enable-matrix:
	 *
	 * Whether the #GtkSourceSpaceDrawer:matrix property is enabled.
	 *
	 * Since: 3.24
	 */
	properties[PROP_ENABLE_MATRIX] =
		g_param_spec_boolean ("enable-matrix",
				      "Enable Matrix",
				      "",
				      FALSE,
				      G_PARAM_READWRITE |
				      G_PARAM_CONSTRUCT |
				      G_PARAM_STATIC_STRINGS);

	/**
	 * GtkSourceSpaceDrawer:matrix:
	 *
	 * The :matrix property is a #GVariant property to specify where and
	 * what kind of white spaces to draw.
	 *
	 * The #GVariant is of type `"au"`, an array of unsigned integers. Each
	 * integer is a combination of #GtkSourceSpaceTypeFlags. There is one
	 * integer for each #GtkSourceSpaceLocationFlags, in the same order as
	 * they are defined in the enum (%GTK_SOURCE_SPACE_LOCATION_NONE and
	 * %GTK_SOURCE_SPACE_LOCATION_ALL are not taken into account).
	 *
	 * If the array is shorter than the number of locations, then the value
	 * for the missing locations will be %GTK_SOURCE_SPACE_TYPE_NONE.
	 *
	 * By default, %GTK_SOURCE_SPACE_TYPE_ALL is set for all locations.
	 *
	 * Since: 3.24
	 */
	properties[PROP_MATRIX] =
		g_param_spec_variant ("matrix",
				      "Matrix",
				      "",
				      G_VARIANT_TYPE ("au"),
				      get_default_matrix (),
				      G_PARAM_READWRITE |
				      G_PARAM_CONSTRUCT |
				      G_PARAM_STATIC_STRINGS);

	g_object_class_install_properties (object_class, N_PROPERTIES, properties);
}

static void
gtk_source_space_drawer_init (GtkSourceSpaceDrawer *drawer)
{
	drawer->matrix = g_new0 (GtkSourceSpaceTypeFlags, get_number_of_locations ());
}

/**
 * gtk_source_space_drawer_new:
 *
 * Creates a new #GtkSourceSpaceDrawer object. Useful for storing space drawing
 * settings independently of a #GtkSourceView.
 *
 * Returns: a new #GtkSourceSpaceDrawer.
 * Since: 3.24
 */
GtkSourceSpaceDrawer *
gtk_source_space_drawer_new (void)
{
	return g_object_new (GTK_SOURCE_TYPE_SPACE_DRAWER, NULL);
}

/**
 * gtk_source_space_drawer_get_types_for_locations:
 * @drawer: a #GtkSourceSpaceDrawer.
 * @locations: one or several #GtkSourceSpaceLocationFlags.
 *
 * If only one location is specified, this function returns what kind of
 * white spaces are drawn at that location. The value is retrieved from the
 * #GtkSourceSpaceDrawer:matrix property.
 *
 * If several locations are specified, this function returns the logical AND for
 * those locations. Which means that if a certain kind of white space is present
 * in the return value, then that kind of white space is drawn at all the
 * specified @locations.
 *
 * Returns: a combination of #GtkSourceSpaceTypeFlags.
 * Since: 3.24
 */
GtkSourceSpaceTypeFlags
gtk_source_space_drawer_get_types_for_locations (GtkSourceSpaceDrawer        *drawer,
                                                 GtkSourceSpaceLocationFlags  locations)
{
	g_return_val_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer), GTK_SOURCE_SPACE_TYPE_NONE);

	return get_types_at_all_locations (drawer, locations);
}

/**
 * gtk_source_space_drawer_set_types_for_locations:
 * @drawer: a #GtkSourceSpaceDrawer.
 * @locations: one or several #GtkSourceSpaceLocationFlags.
 * @types: a combination of #GtkSourceSpaceTypeFlags.
 *
 * Modifies the #GtkSourceSpaceDrawer:matrix property at the specified
 * @locations.
 *
 * Since: 3.24
 */
void
gtk_source_space_drawer_set_types_for_locations (GtkSourceSpaceDrawer        *drawer,
                                                 GtkSourceSpaceLocationFlags  locations,
                                                 GtkSourceSpaceTypeFlags      types)
{
	gint index;
	gint num_locations;
	gboolean changed = FALSE;

	g_return_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer));

	index = 0;
	num_locations = get_number_of_locations ();

	while (locations != 0 && index < num_locations)
	{
		if ((locations & 1) == 1 &&
		    drawer->matrix[index] != types)
		{
			drawer->matrix[index] = types;
			changed = TRUE;
		}

		locations >>= 1;
		index++;
	}

	if (changed)
	{
		g_object_notify_by_pspec (G_OBJECT (drawer), properties[PROP_MATRIX]);
	}
}

/**
 * gtk_source_space_drawer_get_matrix:
 * @drawer: a #GtkSourceSpaceDrawer.
 *
 * Gets the value of the #GtkSourceSpaceDrawer:matrix property, as a #GVariant.
 * An empty array can be returned in case the matrix is a zero matrix.
 *
 * The gtk_source_space_drawer_get_types_for_locations() function may be more
 * convenient to use.
 *
 * Returns: the #GtkSourceSpaceDrawer:matrix value as a new floating #GVariant
 *   instance.
 * Since: 3.24
 */
GVariant *
gtk_source_space_drawer_get_matrix (GtkSourceSpaceDrawer *drawer)
{
	GVariantBuilder builder;
	gint num_locations;
	gint i;

	g_return_val_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer), NULL);

	if (is_zero_matrix (drawer))
	{
		return g_variant_new ("au", NULL);
	}

	g_variant_builder_init (&builder, G_VARIANT_TYPE ("au"));

	num_locations = get_number_of_locations ();

	for (i = 0; i < num_locations; i++)
	{
		GVariant *space_types;

		space_types = g_variant_new_uint32 (drawer->matrix[i]);

		g_variant_builder_add_value (&builder, space_types);
	}

	return g_variant_builder_end (&builder);
}

/**
 * gtk_source_space_drawer_set_matrix:
 * @drawer: a #GtkSourceSpaceDrawer.
 * @matrix: (transfer floating) (nullable): the new matrix value, or %NULL.
 *
 * Sets a new value to the #GtkSourceSpaceDrawer:matrix property, as a
 * #GVariant. If @matrix is %NULL, then an empty array is set.
 *
 * If @matrix is floating, it is consumed.
 *
 * The gtk_source_space_drawer_set_types_for_locations() function may be more
 * convenient to use.
 *
 * Since: 3.24
 */
void
gtk_source_space_drawer_set_matrix (GtkSourceSpaceDrawer *drawer,
                                    GVariant             *matrix)
{
	gint num_locations;
	gint index;
	GVariantIter iter;
	gboolean changed = FALSE;

	g_return_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer));

	if (matrix == NULL)
	{
		set_zero_matrix (drawer);
		return;
	}

	g_return_if_fail (g_variant_is_of_type (matrix, G_VARIANT_TYPE ("au")));

	g_variant_iter_init (&iter, matrix);

	num_locations = get_number_of_locations ();
	index = 0;
	while (index < num_locations)
	{
		GVariant *child;
		guint32 space_types;

		child = g_variant_iter_next_value (&iter);
		if (child == NULL)
		{
			break;
		}

		space_types = g_variant_get_uint32 (child);

		if (drawer->matrix[index] != space_types)
		{
			drawer->matrix[index] = space_types;
			changed = TRUE;
		}

		g_variant_unref (child);
		index++;
	}

	while (index < num_locations)
	{
		if (drawer->matrix[index] != 0)
		{
			drawer->matrix[index] = 0;
			changed = TRUE;
		}

		index++;
	}

	if (changed)
	{
		g_object_notify_by_pspec (G_OBJECT (drawer), properties[PROP_MATRIX]);
	}

	if (g_variant_is_floating (matrix))
	{
		g_variant_ref_sink (matrix);
		g_variant_unref (matrix);
	}
}

/**
 * gtk_source_space_drawer_get_enable_matrix:
 * @drawer: a #GtkSourceSpaceDrawer.
 *
 * Returns: whether the #GtkSourceSpaceDrawer:matrix property is enabled.
 * Since: 3.24
 */
gboolean
gtk_source_space_drawer_get_enable_matrix (GtkSourceSpaceDrawer *drawer)
{
	g_return_val_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer), FALSE);

	return drawer->enable_matrix;
}

/**
 * gtk_source_space_drawer_set_enable_matrix:
 * @drawer: a #GtkSourceSpaceDrawer.
 * @enable_matrix: the new value.
 *
 * Sets whether the #GtkSourceSpaceDrawer:matrix property is enabled.
 *
 * Since: 3.24
 */
void
gtk_source_space_drawer_set_enable_matrix (GtkSourceSpaceDrawer *drawer,
                                           gboolean              enable_matrix)
{
	g_return_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer));

	enable_matrix = enable_matrix != FALSE;

	if (drawer->enable_matrix != enable_matrix)
	{
		drawer->enable_matrix = enable_matrix;
		g_object_notify_by_pspec (G_OBJECT (drawer), properties[PROP_ENABLE_MATRIX]);
	}
}

static gboolean
matrix_get_mapping (GValue   *value,
                    GVariant *variant,
                    gpointer  user_data)
{
	g_value_set_variant (value, variant);
	return TRUE;
}

static GVariant *
matrix_set_mapping (const GValue       *value,
                    const GVariantType *expected_type,
                    gpointer            user_data)
{
	return g_value_dup_variant (value);
}

/**
 * gtk_source_space_drawer_bind_matrix_setting:
 * @drawer: a #GtkSourceSpaceDrawer object.
 * @settings: a #GSettings object.
 * @key: the @settings key to bind.
 * @flags: flags for the binding.
 *
 * Binds the #GtkSourceSpaceDrawer:matrix property to a #GSettings key.
 *
 * The #GSettings key must be of the same type as the
 * #GtkSourceSpaceDrawer:matrix property, that is, `"au"`.
 *
 * The g_settings_bind() function cannot be used, because the default GIO
 * mapping functions don't support #GVariant properties (maybe it will be
 * supported by a future GIO version, in which case this function can be
 * deprecated).
 *
 * Since: 3.24
 */
void
gtk_source_space_drawer_bind_matrix_setting (GtkSourceSpaceDrawer *drawer,
                                             GSettings            *settings,
                                             const gchar          *key,
                                             GSettingsBindFlags    flags)
{
	GVariant *value;

	g_return_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer));
	g_return_if_fail (G_IS_SETTINGS (settings));
	g_return_if_fail (key != NULL);
	g_return_if_fail ((flags & G_SETTINGS_BIND_INVERT_BOOLEAN) == 0);

	value = g_settings_get_value (settings, key);
	if (!g_variant_is_of_type (value, G_VARIANT_TYPE ("au")))
	{
		g_warning ("%s(): the GSettings key must be of type \"au\".", G_STRFUNC);
		g_variant_unref (value);
		return;
	}
	g_variant_unref (value);

	g_settings_bind_with_mapping (settings, key,
				      drawer, "matrix",
				      flags,
				      matrix_get_mapping,
				      matrix_set_mapping,
				      NULL, NULL);
}

void
_gtk_source_space_drawer_update_color (GtkSourceSpaceDrawer *drawer,
                                       GtkSourceView        *view)
{
	GtkSourceBuffer *buffer;
	GtkSourceStyleScheme *style_scheme;

	g_return_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer));
	g_return_if_fail (GTK_SOURCE_IS_VIEW (view));

	gtk_source_space_drawer_purge_cache (drawer);

	drawer->color_set = FALSE;

	buffer = GTK_SOURCE_BUFFER (gtk_text_view_get_buffer (GTK_TEXT_VIEW (view)));
	style_scheme = gtk_source_buffer_get_style_scheme (buffer);

	if (style_scheme != NULL)
	{
		GtkSourceStyle *style;

		style = _gtk_source_style_scheme_get_draw_spaces_style (style_scheme);

		if (style != NULL)
		{
			gchar *color_str = NULL;
			gboolean color_set;
			GdkRGBA color;

			g_object_get (style,
				      "foreground", &color_str,
				      "foreground-set", &color_set,
				      NULL);

			if (color_set &&
			    color_str != NULL &&
			    gdk_rgba_parse (&color, color_str))
			{
				drawer->color = color;
				drawer->color_set = TRUE;
			}

			g_free (color_str);
		}
	}

	if (!drawer->color_set)
	{
		GtkStyleContext *context;
		GdkRGBA color;

		context = gtk_widget_get_style_context (GTK_WIDGET (view));
		gtk_style_context_save (context);
		gtk_style_context_set_state (context, GTK_STATE_FLAG_INSENSITIVE);
		gtk_style_context_get_color (context, &color);
		gtk_style_context_restore (context);

		drawer->color = color;
		drawer->color_set = TRUE;
	}
}

static inline gboolean
is_tab (gunichar ch)
{<commit_msg>spacedrawer: remove deprecated API use<commit_after>/*
 * This file is part of GtkSourceView
 *
 * Copyright 2008, 2011, 2016 - <NAME> <<EMAIL>>
 * Copyright 2008, 2010 - <NAME> <<EMAIL>>
 * Copyright 2010 - <NAME>
 * Copyright 2013 - <NAME> <<EMAIL>>
 * Copyright 2015, 2016 - <NAME> <<EMAIL>>
 * Copyright 2016 - <NAME> <<EMAIL>>
 *
 * GtkSourceView is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * GtkSourceView is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"

#include "gtksourcespacedrawer.h"
#include "gtksourcespacedrawer-private.h"
#include "gtksourcebuffer.h"
#include "gtksourcebuffer-private.h"
#include "gtksourceiter-private.h"
#include "gtksourcestylescheme.h"
#include "gtksourcestylescheme-private.h"
#include "gtksourcetag.h"
#include "gtksourceview.h"

/**
 * SECTION:spacedrawer
 * @Short_description: Represent white space characters with symbols
 * @Title: GtkSourceSpaceDrawer
 * @See_also: #GtkSourceView
 *
 * #GtkSourceSpaceDrawer provides a way to visualize white spaces, by drawing
 * symbols.
 *
 * Call gtk_source_view_get_space_drawer() to get the #GtkSourceSpaceDrawer
 * instance of a certain #GtkSourceView.
 *
 * By default, no white spaces are drawn because the
 * #GtkSourceSpaceDrawer:enable-matrix is %FALSE.
 *
 * To draw white spaces, gtk_source_space_drawer_set_types_for_locations() can
 * be called to set the #GtkSourceSpaceDrawer:matrix property (by default all
 * space types are enabled at all locations). Then call
 * gtk_source_space_drawer_set_enable_matrix().
 *
 * For a finer-grained method, there is also the GtkSourceTag's
 * #GtkSourceTag:draw-spaces property.
 *
 * # Example
 *
 * To draw non-breaking spaces everywhere and draw all types of trailing spaces
 * except newlines:
 * |[
 * gtk_source_space_drawer_set_types_for_locations (space_drawer,
 *                                                  GTK_SOURCE_SPACE_LOCATION_ALL,
 *                                                  GTK_SOURCE_SPACE_TYPE_NBSP);
 *
 * gtk_source_space_drawer_set_types_for_locations (space_drawer,
 *                                                  GTK_SOURCE_SPACE_LOCATION_TRAILING,
 *                                                  GTK_SOURCE_SPACE_TYPE_ALL &
 *                                                  ~GTK_SOURCE_SPACE_TYPE_NEWLINE);
 *
 * gtk_source_space_drawer_set_enable_matrix (space_drawer, TRUE);
 * ]|
 *
 * # Use-case: draw unwanted white spaces
 *
 * A possible use-case is to draw only unwanted white spaces. Examples:
 * - Draw all trailing spaces.
 * - If the indentation and alignment must be done with spaces, draw tabs.
 *
 * And non-breaking spaces can always be drawn, everywhere, to distinguish them
 * from normal spaces.
 */

/* A drawer specially designed for the International Space Station. It comes by
 * default with a DVD of Matrix, in case the astronauts are bored.
 */

#if 0
# define ENABLE_PROFILE
#else
# undef ENABLE_PROFILE
#endif

typedef enum
{
	DRAW_TAB,
	DRAW_NARROW_NBSP,
	DRAW_NBSP,
	DRAW_SPACE,
	DRAW_NEWLINE,
	N_DRAW
} Draw;

typedef struct
{
	GskRenderNode *node;
	gint           width;
	gint           height;
} CachedNode;

struct _GtkSourceSpaceDrawer
{
	GObject                  parent_instance;

	GtkSourceSpaceTypeFlags *matrix;

	CachedNode               cached[N_DRAW];

	GdkRGBA                  color;

	guint                    color_set : 1;
	guint                    enable_matrix : 1;
};

enum
{
	PROP_0,
	PROP_ENABLE_MATRIX,
	PROP_MATRIX,
	N_PROPERTIES
};

static GParamSpec *properties[N_PROPERTIES];

G_DEFINE_TYPE (GtkSourceSpaceDrawer, gtk_source_space_drawer, G_TYPE_OBJECT)

static void
gtk_source_space_drawer_purge_cache (GtkSourceSpaceDrawer *drawer)
{
	guint i;

	g_return_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer));

	for (i = 0; i < G_N_ELEMENTS (drawer->cached); i++)
	{
		g_clear_pointer (&drawer->cached[i].node, gsk_render_node_unref);
	}
}

static gint
get_number_of_locations (void)
{
	gint num;
	gint flags;

	num = 0;
	flags = GTK_SOURCE_SPACE_LOCATION_ALL;

	while (flags != 0)
	{
		flags >>= 1;
		num++;
	}

	return num;
}

static GVariant *
get_default_matrix (void)
{
	GVariantBuilder builder;
	gint num_locations;
	gint i;

	g_variant_builder_init (&builder, G_VARIANT_TYPE ("au"));

	num_locations = get_number_of_locations ();

	for (i = 0; i < num_locations; i++)
	{
		GVariant *space_types;

		space_types = g_variant_new_uint32 (GTK_SOURCE_SPACE_TYPE_ALL);

		g_variant_builder_add_value (&builder, space_types);
	}

	return g_variant_builder_end (&builder);
}

static gboolean
is_zero_matrix (GtkSourceSpaceDrawer *drawer)
{
	gint num_locations;
	gint i;

	num_locations = get_number_of_locations ();

	for (i = 0; i < num_locations; i++)
	{
		if (drawer->matrix[i] != 0)
		{
			return FALSE;
		}
	}

	return TRUE;
}

static void
set_zero_matrix (GtkSourceSpaceDrawer *drawer)
{
	gint num_locations;
	gint i;
	gboolean changed = FALSE;

	num_locations = get_number_of_locations ();

	for (i = 0; i < num_locations; i++)
	{
		if (drawer->matrix[i] != 0)
		{
			drawer->matrix[i] = 0;
			changed = TRUE;
		}
	}

	if (changed)
	{
		g_object_notify_by_pspec (G_OBJECT (drawer), properties[PROP_MATRIX]);
	}
}

/* AND */
static GtkSourceSpaceTypeFlags
get_types_at_all_locations (GtkSourceSpaceDrawer        *drawer,
                            GtkSourceSpaceLocationFlags  locations)
{
	GtkSourceSpaceTypeFlags ret = GTK_SOURCE_SPACE_TYPE_ALL;
	gint index;
	gint num_locations;
	gboolean found;

	index = 0;
	num_locations = get_number_of_locations ();
	found = FALSE;

	while (locations != 0 && index < num_locations)
	{
		if ((locations & 1) == 1)
		{
			ret &= drawer->matrix[index];
			found = TRUE;
		}

		locations >>= 1;
		index++;
	}

	return found ? ret : GTK_SOURCE_SPACE_TYPE_NONE;
}

/* OR */
static GtkSourceSpaceTypeFlags
get_types_at_any_locations (GtkSourceSpaceDrawer        *drawer,
                            GtkSourceSpaceLocationFlags  locations)
{
	GtkSourceSpaceTypeFlags ret = GTK_SOURCE_SPACE_TYPE_NONE;
	gint index;
	gint num_locations;

	index = 0;
	num_locations = get_number_of_locations ();

	while (locations != 0 && index < num_locations)
	{
		if ((locations & 1) == 1)
		{
			ret |= drawer->matrix[index];
		}

		locations >>= 1;
		index++;
	}

	return ret;
}

static void
gtk_source_space_drawer_get_property (GObject    *object,
                                      guint       prop_id,
                                      GValue     *value,
                                      GParamSpec *pspec)
{
	GtkSourceSpaceDrawer *drawer = GTK_SOURCE_SPACE_DRAWER (object);

	switch (prop_id)
	{
		case PROP_ENABLE_MATRIX:
			g_value_set_boolean (value, gtk_source_space_drawer_get_enable_matrix (drawer));
			break;

		case PROP_MATRIX:
			g_value_set_variant (value, gtk_source_space_drawer_get_matrix (drawer));
			break;

		default:
			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
			break;
	}
}

static void
gtk_source_space_drawer_set_property (GObject      *object,
                                      guint         prop_id,
                                      const GValue *value,
                                      GParamSpec   *pspec)
{
	GtkSourceSpaceDrawer *drawer = GTK_SOURCE_SPACE_DRAWER (object);

	switch (prop_id)
	{
		case PROP_ENABLE_MATRIX:
			gtk_source_space_drawer_set_enable_matrix (drawer, g_value_get_boolean (value));
			break;

		case PROP_MATRIX:
			gtk_source_space_drawer_set_matrix (drawer, g_value_get_variant (value));
			break;

		default:
			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
			break;
	}
}

static void
gtk_source_space_drawer_finalize (GObject *object)
{
	GtkSourceSpaceDrawer *drawer = GTK_SOURCE_SPACE_DRAWER (object);

	gtk_source_space_drawer_purge_cache (drawer);
	g_free (drawer->matrix);

	G_OBJECT_CLASS (gtk_source_space_drawer_parent_class)->finalize (object);
}

static void
gtk_source_space_drawer_class_init (GtkSourceSpaceDrawerClass *klass)
{
	GObjectClass *object_class = G_OBJECT_CLASS (klass);

	object_class->get_property = gtk_source_space_drawer_get_property;
	object_class->set_property = gtk_source_space_drawer_set_property;
	object_class->finalize = gtk_source_space_drawer_finalize;

	/**
	 * GtkSourceSpaceDrawer:enable-matrix:
	 *
	 * Whether the #GtkSourceSpaceDrawer:matrix property is enabled.
	 *
	 * Since: 3.24
	 */
	properties[PROP_ENABLE_MATRIX] =
		g_param_spec_boolean ("enable-matrix",
				      "Enable Matrix",
				      "",
				      FALSE,
				      G_PARAM_READWRITE |
				      G_PARAM_CONSTRUCT |
				      G_PARAM_STATIC_STRINGS);

	/**
	 * GtkSourceSpaceDrawer:matrix:
	 *
	 * The :matrix property is a #GVariant property to specify where and
	 * what kind of white spaces to draw.
	 *
	 * The #GVariant is of type `"au"`, an array of unsigned integers. Each
	 * integer is a combination of #GtkSourceSpaceTypeFlags. There is one
	 * integer for each #GtkSourceSpaceLocationFlags, in the same order as
	 * they are defined in the enum (%GTK_SOURCE_SPACE_LOCATION_NONE and
	 * %GTK_SOURCE_SPACE_LOCATION_ALL are not taken into account).
	 *
	 * If the array is shorter than the number of locations, then the value
	 * for the missing locations will be %GTK_SOURCE_SPACE_TYPE_NONE.
	 *
	 * By default, %GTK_SOURCE_SPACE_TYPE_ALL is set for all locations.
	 *
	 * Since: 3.24
	 */
	properties[PROP_MATRIX] =
		g_param_spec_variant ("matrix",
				      "Matrix",
				      "",
				      G_VARIANT_TYPE ("au"),
				      get_default_matrix (),
				      G_PARAM_READWRITE |
				      G_PARAM_CONSTRUCT |
				      G_PARAM_STATIC_STRINGS);

	g_object_class_install_properties (object_class, N_PROPERTIES, properties);
}

static void
gtk_source_space_drawer_init (GtkSourceSpaceDrawer *drawer)
{
	drawer->matrix = g_new0 (GtkSourceSpaceTypeFlags, get_number_of_locations ());
}

/**
 * gtk_source_space_drawer_new:
 *
 * Creates a new #GtkSourceSpaceDrawer object. Useful for storing space drawing
 * settings independently of a #GtkSourceView.
 *
 * Returns: a new #GtkSourceSpaceDrawer.
 * Since: 3.24
 */
GtkSourceSpaceDrawer *
gtk_source_space_drawer_new (void)
{
	return g_object_new (GTK_SOURCE_TYPE_SPACE_DRAWER, NULL);
}

/**
 * gtk_source_space_drawer_get_types_for_locations:
 * @drawer: a #GtkSourceSpaceDrawer.
 * @locations: one or several #GtkSourceSpaceLocationFlags.
 *
 * If only one location is specified, this function returns what kind of
 * white spaces are drawn at that location. The value is retrieved from the
 * #GtkSourceSpaceDrawer:matrix property.
 *
 * If several locations are specified, this function returns the logical AND for
 * those locations. Which means that if a certain kind of white space is present
 * in the return value, then that kind of white space is drawn at all the
 * specified @locations.
 *
 * Returns: a combination of #GtkSourceSpaceTypeFlags.
 * Since: 3.24
 */
GtkSourceSpaceTypeFlags
gtk_source_space_drawer_get_types_for_locations (GtkSourceSpaceDrawer        *drawer,
                                                 GtkSourceSpaceLocationFlags  locations)
{
	g_return_val_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer), GTK_SOURCE_SPACE_TYPE_NONE);

	return get_types_at_all_locations (drawer, locations);
}

/**
 * gtk_source_space_drawer_set_types_for_locations:
 * @drawer: a #GtkSourceSpaceDrawer.
 * @locations: one or several #GtkSourceSpaceLocationFlags.
 * @types: a combination of #GtkSourceSpaceTypeFlags.
 *
 * Modifies the #GtkSourceSpaceDrawer:matrix property at the specified
 * @locations.
 *
 * Since: 3.24
 */
void
gtk_source_space_drawer_set_types_for_locations (GtkSourceSpaceDrawer        *drawer,
                                                 GtkSourceSpaceLocationFlags  locations,
                                                 GtkSourceSpaceTypeFlags      types)
{
	gint index;
	gint num_locations;
	gboolean changed = FALSE;

	g_return_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer));

	index = 0;
	num_locations = get_number_of_locations ();

	while (locations != 0 && index < num_locations)
	{
		if ((locations & 1) == 1 &&
		    drawer->matrix[index] != types)
		{
			drawer->matrix[index] = types;
			changed = TRUE;
		}

		locations >>= 1;
		index++;
	}

	if (changed)
	{
		g_object_notify_by_pspec (G_OBJECT (drawer), properties[PROP_MATRIX]);
	}
}

/**
 * gtk_source_space_drawer_get_matrix:
 * @drawer: a #GtkSourceSpaceDrawer.
 *
 * Gets the value of the #GtkSourceSpaceDrawer:matrix property, as a #GVariant.
 * An empty array can be returned in case the matrix is a zero matrix.
 *
 * The gtk_source_space_drawer_get_types_for_locations() function may be more
 * convenient to use.
 *
 * Returns: the #GtkSourceSpaceDrawer:matrix value as a new floating #GVariant
 *   instance.
 * Since: 3.24
 */
GVariant *
gtk_source_space_drawer_get_matrix (GtkSourceSpaceDrawer *drawer)
{
	GVariantBuilder builder;
	gint num_locations;
	gint i;

	g_return_val_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer), NULL);

	if (is_zero_matrix (drawer))
	{
		return g_variant_new ("au", NULL);
	}

	g_variant_builder_init (&builder, G_VARIANT_TYPE ("au"));

	num_locations = get_number_of_locations ();

	for (i = 0; i < num_locations; i++)
	{
		GVariant *space_types;

		space_types = g_variant_new_uint32 (drawer->matrix[i]);

		g_variant_builder_add_value (&builder, space_types);
	}

	return g_variant_builder_end (&builder);
}

/**
 * gtk_source_space_drawer_set_matrix:
 * @drawer: a #GtkSourceSpaceDrawer.
 * @matrix: (transfer floating) (nullable): the new matrix value, or %NULL.
 *
 * Sets a new value to the #GtkSourceSpaceDrawer:matrix property, as a
 * #GVariant. If @matrix is %NULL, then an empty array is set.
 *
 * If @matrix is floating, it is consumed.
 *
 * The gtk_source_space_drawer_set_types_for_locations() function may be more
 * convenient to use.
 *
 * Since: 3.24
 */
void
gtk_source_space_drawer_set_matrix (GtkSourceSpaceDrawer *drawer,
                                    GVariant             *matrix)
{
	gint num_locations;
	gint index;
	GVariantIter iter;
	gboolean changed = FALSE;

	g_return_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer));

	if (matrix == NULL)
	{
		set_zero_matrix (drawer);
		return;
	}

	g_return_if_fail (g_variant_is_of_type (matrix, G_VARIANT_TYPE ("au")));

	g_variant_iter_init (&iter, matrix);

	num_locations = get_number_of_locations ();
	index = 0;
	while (index < num_locations)
	{
		GVariant *child;
		guint32 space_types;

		child = g_variant_iter_next_value (&iter);
		if (child == NULL)
		{
			break;
		}

		space_types = g_variant_get_uint32 (child);

		if (drawer->matrix[index] != space_types)
		{
			drawer->matrix[index] = space_types;
			changed = TRUE;
		}

		g_variant_unref (child);
		index++;
	}

	while (index < num_locations)
	{
		if (drawer->matrix[index] != 0)
		{
			drawer->matrix[index] = 0;
			changed = TRUE;
		}

		index++;
	}

	if (changed)
	{
		g_object_notify_by_pspec (G_OBJECT (drawer), properties[PROP_MATRIX]);
	}

	if (g_variant_is_floating (matrix))
	{
		g_variant_ref_sink (matrix);
		g_variant_unref (matrix);
	}
}

/**
 * gtk_source_space_drawer_get_enable_matrix:
 * @drawer: a #GtkSourceSpaceDrawer.
 *
 * Returns: whether the #GtkSourceSpaceDrawer:matrix property is enabled.
 * Since: 3.24
 */
gboolean
gtk_source_space_drawer_get_enable_matrix (GtkSourceSpaceDrawer *drawer)
{
	g_return_val_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer), FALSE);

	return drawer->enable_matrix;
}

/**
 * gtk_source_space_drawer_set_enable_matrix:
 * @drawer: a #GtkSourceSpaceDrawer.
 * @enable_matrix: the new value.
 *
 * Sets whether the #GtkSourceSpaceDrawer:matrix property is enabled.
 *
 * Since: 3.24
 */
void
gtk_source_space_drawer_set_enable_matrix (GtkSourceSpaceDrawer *drawer,
                                           gboolean              enable_matrix)
{
	g_return_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer));

	enable_matrix = enable_matrix != FALSE;

	if (drawer->enable_matrix != enable_matrix)
	{
		drawer->enable_matrix = enable_matrix;
		g_object_notify_by_pspec (G_OBJECT (drawer), properties[PROP_ENABLE_MATRIX]);
	}
}

static gboolean
matrix_get_mapping (GValue   *value,
                    GVariant *variant,
                    gpointer  user_data)
{
	g_value_set_variant (value, variant);
	return TRUE;
}

static GVariant *
matrix_set_mapping (const GValue       *value,
                    const GVariantType *expected_type,
                    gpointer            user_data)
{
	return g_value_dup_variant (value);
}

/**
 * gtk_source_space_drawer_bind_matrix_setting:
 * @drawer: a #GtkSourceSpaceDrawer object.
 * @settings: a #GSettings object.
 * @key: the @settings key to bind.
 * @flags: flags for the binding.
 *
 * Binds the #GtkSourceSpaceDrawer:matrix property to a #GSettings key.
 *
 * The #GSettings key must be of the same type as the
 * #GtkSourceSpaceDrawer:matrix property, that is, `"au"`.
 *
 * The g_settings_bind() function cannot be used, because the default GIO
 * mapping functions don't support #GVariant properties (maybe it will be
 * supported by a future GIO version, in which case this function can be
 * deprecated).
 *
 * Since: 3.24
 */
void
gtk_source_space_drawer_bind_matrix_setting (GtkSourceSpaceDrawer *drawer,
                                             GSettings            *settings,
                                             const gchar          *key,
                                             GSettingsBindFlags    flags)
{
	GVariant *value;

	g_return_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer));
	g_return_if_fail (G_IS_SETTINGS (settings));
	g_return_if_fail (key != NULL);
	g_return_if_fail ((flags & G_SETTINGS_BIND_INVERT_BOOLEAN) == 0);

	value = g_settings_get_value (settings, key);
	if (!g_variant_is_of_type (value, G_VARIANT_TYPE ("au")))
	{
		g_warning ("%s(): the GSettings key must be of type \"au\".", G_STRFUNC);
		g_variant_unref (value);
		return;
	}
	g_variant_unref (value);

	g_settings_bind_with_mapping (settings, key,
				      drawer, "matrix",
				      flags,
				      matrix_get_mapping,
				      matrix_set_mapping,
				      NULL, NULL);
}

void
_gtk_source_space_drawer_update_color (GtkSourceSpaceDrawer *drawer,
                                       GtkSourceView        *view)
{
	GtkSourceBuffer *buffer;
	GtkSourceStyleScheme *style_scheme;

	g_return_if_fail (GTK_SOURCE_IS_SPACE_DRAWER (drawer));
	g_return_if_fail (GTK_SOURCE_IS_VIEW (view));

	gtk_source_space_drawer_purge_cache (drawer);

	drawer->color_set = FALSE;

	buffer = GTK_SOURCE_BUFFER (gtk_text_view_get_buffer (GTK_TEXT_VIEW (view)));
	style_scheme = gtk_source_buffer_get_style_scheme (buffer);

	if (style_scheme != NULL)
	{
		GtkSourceStyle *style;

		style = _gtk_source_style_scheme_get_draw_spaces_style (style_scheme);

		if (style != NULL)
		{
			gchar *color_str = NULL;
			gboolean color_set;
			GdkRGBA color;

			g_object_get (style,
				      "foreground", &color_str,
				      "foreground-set", &color_set,
				      NULL);

			if (color_set &&
			    color_str != NULL &&
			    gdk_rgba_parse (&color, color_str))
			{
				drawer->color = color;
				drawer->color_set = TRUE;
			}

			g_free (color_str);
		}
	}

	if (!drawer->color_set)
	{
		GtkStyleContext *context;

		context = gtk_widget_get_style_context (GTK_WIDGET (view));
		gtk_style_context_get_color (context, &drawer->color);
		drawer->color.alpha *= .5;
		drawer->color_set = TRUE;
	}
}

static inline gboolean
is_tab (gunichar ch)
{
{'fraction_non_alphanumeric': 0.09021861336664584, 'fraction_numerical': 0.0057713928794503435, 'mean_word_length': 3.434522490582761, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 112, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 64, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4423320', 'n_tokens_mistral': 14526, 'n_tokens_neox': 13436, 'n_words': 3185}