JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
read stdin instead of polling a text file
[now-playing-d.git] / now-playing-d.c
index 7b2ec06..9ac043d 100644 (file)
 #include "eggtrayicon.h"
 
 
-char buf[1000];
-char* playing[2] = {&buf[0], &buf[500]};
+gchar* playing[2];
 int playing_i = 0;
 
 
 // this gets called regularly by gtk
-static gboolean
-ticker(GtkWidget *widget) {
-       FILE * fd;
-       int len;
+gboolean
+stdin_callback(GIOChannel *channel, GIOCondition cond, gpointer data) {
+       GtkWidget *widget;
+       GIOStatus ret;
+       gsize length;
+       gsize terminator_pos;
+       GError *error = NULL;
+
+       widget = GTK_WIDGET(data);
 
        if (widget->window == NULL) {
                return FALSE;
        }
 
-       fd = fopen(TMP_FILE, "r");
-       if(fd == NULL) {
-               return TRUE;
+       ret = g_io_channel_read_line(
+               channel,
+               &(playing[playing_i]),
+               &length,
+               &terminator_pos,
+               &error);
+
+       if (ret == G_IO_STATUS_ERROR) {
+               g_error ("Error reading: %s\n", error->message);
+               gtk_exit(2);
+       }
+       if (length == 0) {
+               gtk_exit(0);
        }
-       len = fread(playing[playing_i], 1, 499, fd);
-       fclose(fd);
-       playing[playing_i][len] = 0;
 
-       if(strcmp(playing[playing_i], playing[1 - playing_i])) {
+       // remove terminator
+       if(terminator_pos) {
+               playing[playing_i][terminator_pos] = 0;
+       }
+
+
+       if(strcmp(playing[0], playing[1])) {
                gtk_label_set_text(GTK_LABEL(widget), playing[playing_i]);
        }
 
        playing_i = 1 - playing_i;
+       g_free(playing[playing_i]);
 
        // gtk_widget_queue_draw(widget);
        return TRUE;
@@ -58,22 +76,27 @@ int
 main(int argc, char *argv[]) {
        GtkWidget *label;
        EggTrayIcon *egg;
+       GIOChannel *channel;
 
        // initialize GTK
        gtk_set_locale();
        gtk_init(&argc, &argv);
 
+       // initialize globals
+       playing_i = 0;
+       playing[1] = g_strdup("");
+
        // make the widget
-       label = gtk_label_new("initializing...");
+       label = gtk_label_new("");
        egg = egg_tray_icon_new("what's this string do?");
        // nest and display the widget
        gtk_container_add(GTK_CONTAINER(egg), label);
        gtk_widget_show_all(GTK_WIDGET(egg));
 
-       // initialize and start ticker
-       playing[0][0] = 0;
-       playing[1][0] = 0;
-       g_timeout_add(1000, (GSourceFunc) ticker, (gpointer) label);
+       // watch stdin
+       channel = g_io_channel_unix_new(fileno(stdin));
+       g_io_channel_set_encoding(channel, NULL, NULL); // kiss
+       g_io_add_watch(channel, G_IO_IN, stdin_callback, (gpointer)label);
 
        gtk_main();
 }