Gtk Entry Date auto formatting

Hello people.

I am trying to develop an algorithm that implements date data entry.
I’m posting the code for you to take a look at, and ask what you think of the idea. Some criticism, suggestion, opinion.
It is very easy to use just connect to the insert_text signal

static void
on_format_date (GtkEditable *editable,
                const gchar *text,
                gint        length,
                gint        *position,
                gpointer    user_data)
{
  if (gtk_entry_get_text_length (GTK_ENTRY (user_data)) > 9)
    {
      g_signal_stop_emission_by_name (editable, "insert_text");

      return;
    }

  if (g_unichar_isdigit (g_utf8_get_char (text)))
    {
      g_signal_handlers_block_by_func (editable,
                                       (gpointer) on_format_date,
                                       user_data);

      if ((*position == 2) || (*position == 5))
        {
          gtk_editable_insert_text (editable, "//", length, position);
        }

      gtk_editable_insert_text (editable,
                                text,
                                length,
                                position);

      g_signal_handlers_unblock_by_func (editable,
                                         (gpointer) on_format_date,
                                         user_data);
    }
  else if ((g_strcmp0 (text, "/") == 0) && ((*position == 2) || (*position == 5)))
    {
      g_signal_handlers_block_by_func (editable,
                                       (gpointer) on_format_date,
                                       user_data);

      gchar *check = gtk_editable_get_chars (editable, *position, *position + 1);

      if (!(g_strcmp0 (check, "/") == 0))
        gtk_editable_insert_text (editable,
                                  text,
                                  length,
                                  position);


      g_free (check);

      g_signal_handlers_unblock_by_func (editable,
                                         (gpointer) on_format_date,
                                         user_data);
    }

  g_signal_stop_emission_by_name (editable, "insert_text");
}
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.