Blob Blame Raw
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <gtk/gtk.h>


void changed(GtkEditable *editable, gpointer data) {
  const char *text = gtk_entry_get_text(GTK_ENTRY(editable));
  double result = 0.0;
  for(const char *c = text; c; ++c) {
    if (*c == '+' || *c == '-' || *c == '*' || *c == '/') {
      char *end;
      double a = strtof(text, &end);
      double b = strtof(c + 1, &end);
      if (*c == '+') result = a + b;
      if (*c == '-') result = a - b;
      if (*c == '*') result = a * b;
      if (*c == '/') result = a / b;
    } else
    if (*c == '=') {
      int size = c - text + 1;
      char *new_text = malloc(size + 20);
      memcpy(new_text, text, size);
      sprintf(new_text + size, "%g", result);
      gtk_entry_set_text(GTK_ENTRY(editable), new_text);
      free(new_text);
      break;
    }
  }
}

void activate(GtkApplication* app, gpointer data) {
  GtkWidget *window = gtk_application_window_new(app);
  gtk_container_set_border_width(GTK_CONTAINER(window), 10);
  
  GtkWidget *vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);
  gtk_container_add(GTK_CONTAINER(window), vbox);

  GtkWidget *label = gtk_label_new("Enter simple expression like: 2+3=");
  gtk_container_add(GTK_CONTAINER(vbox), label);
  
  GtkWidget *entry = gtk_entry_new();
  g_signal_connect(entry, "changed", G_CALLBACK(changed), NULL);
  gtk_container_add(GTK_CONTAINER(vbox), entry);
  
  gtk_widget_show_all(window);
}

int main(int argc, char **argv) {
  GtkApplication *application = gtk_application_new(NULL, 0);
  g_signal_connect(application, "activate", G_CALLBACK(activate), NULL);
  int status = g_application_run(G_APPLICATION(application), argc, argv);
  g_object_unref(application);
  return status;
}