Change color using cairo instead of deprecated gdk functions
[darcs-mirror-screen-message.git] / sm.c
1 /*
2 #     sm.c
3 #     Copyright (C) 2006 - 2014 Joachim Breitner
4 #
5 #     This program is free software; you can redistribute it and/or modify
6 #     it under the terms of the GNU General Public License as published by
7 #     the Free Software Foundation; either version 2 of the License, or
8 #     (at your option) any later version.
9 #
10 #     This program is distributed in the hope that it will be useful,
11 #     but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 #     GNU General Public License for more details.
14 #
15 #     You should have received a copy of the GNU General Public License
16 #     along with this program; if not, write to the Free Software
17 #     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18 */
19
20 #include <gtk/gtk.h>
21 #include <gdk/gdk.h>
22 #include <pango/pango.h>
23 #include <cairo.h>
24 #include <string.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <math.h>
28
29 #include "config.h"
30
31 #ifndef _GNU_SOURCE
32 #define _GNU_SOURCE                             /* for getopt_long */
33 #endif
34 #include <getopt.h>
35
36 #define min(x,y) ((x) < (y) ? (x) : (y))
37
38 #define AUTOHIDE_TIMEOUT 3
39
40 static int timeout_id=0;
41
42 static GtkWidget* window;
43 static GtkWidget* draw;
44 static GdkCursor *cursor;
45 static GtkWidget* quit;
46 static GtkWidget* tv;
47 static GtkWidget* entry_widget;
48 static GtkTextBuffer* tb;
49 static PangoFontDescription *font;
50 static char *foreground = NULL;
51 static char *background = NULL;
52 static GdkRGBA  white, black;
53 static char *fontdesc = NULL;
54 static int rotation = 0; // 0 = normal, 1 = left, 2 = inverted, 3 = right
55 static int alignment = 0; // 0 = centered, 1 = left-aligned, 2 = right-aligned
56 static GString *partial_input;
57 static gulong text_change_handler;
58
59 gboolean hide_entry(gpointer *user_data) {
60         timeout_id = 0;
61         gtk_widget_hide(entry_widget);
62         gtk_widget_grab_focus(draw);
63         gtk_widget_queue_draw(draw);
64         gdk_window_set_cursor(gtk_widget_get_window(GTK_WIDGET(draw)), cursor);
65         return FALSE;
66 }
67
68 static void show_entry() {
69         if (timeout_id) {
70                 g_source_remove(timeout_id);
71                 timeout_id = 0;
72         }
73         gtk_widget_show(entry_widget);
74         gtk_widget_grab_focus(tv);
75         gdk_window_set_cursor(gtk_widget_get_window(GTK_WIDGET(draw)), NULL);
76
77         timeout_id = g_timeout_add_seconds (AUTOHIDE_TIMEOUT, (GSourceFunc)hide_entry, NULL);
78 }
79
80 static void clear_text(GtkAccelGroup *accel, GObject *window, guint keyval,  GdkModifierType modifier) {
81         if( gtk_text_buffer_get_char_count(tb) ) {
82                 gtk_text_buffer_set_text(tb,"",-1);
83                 show_entry();
84         } else {
85                 gtk_main_quit();
86         }
87 }
88
89 static char *get_text() {
90         GtkTextIter start, end;
91         gtk_text_buffer_get_start_iter(tb,&start);
92         gtk_text_buffer_get_end_iter(tb,&end);
93         return gtk_text_buffer_get_text(tb, &start, &end, FALSE);
94 }
95
96
97 static void redraw(GtkWidget *draw, cairo_t *cr, gpointer data) {
98         int q;
99
100         gdk_cairo_set_source_rgba(cr, &white);
101         cairo_paint(cr);
102
103         const char *text = get_text();
104         if (strlen(text) > 0) {
105                 int w1, h1;
106                 static PangoLayout* layout;
107
108                 layout = gtk_widget_create_pango_layout(draw, get_text());
109                 pango_layout_set_font_description(layout, font);
110
111                 switch(alignment){
112                         case 0: // center
113                                 pango_layout_set_alignment(layout,PANGO_ALIGN_CENTER);
114                                 break;
115                         case 1: // left
116                                 pango_layout_set_alignment(layout,PANGO_ALIGN_LEFT);
117                                 break;
118                         case 2: // left
119                                 pango_layout_set_alignment(layout,PANGO_ALIGN_RIGHT);
120                                 break;
121                         default:
122                                 // we propably don't want to annoy the user, so default to
123                                 // the old default-behaviour:
124                                 pango_layout_set_alignment(layout,PANGO_ALIGN_CENTER);
125                 }
126
127
128                 pango_layout_get_pixel_size(layout, &w1, &h1);
129                 if (w1>0 && h1>0) {
130                         int w2 = gtk_widget_get_allocated_width(draw);
131                         int h2 = gtk_widget_get_allocated_height(draw);
132
133                         int rw1, rh1;
134                         if (rotation == 0 || rotation == 2) {
135                                 rw1 = w1;
136                                 rh1 = h1;
137                         } else {
138                                 rw1 = h1;
139                                 rh1 = w1;
140                         }
141
142                         double s = min ((double)w2/rw1, (double)h2/rh1);
143
144                         if (alignment == 1) { // left align
145                                 cairo_translate(cr, (s * rw1)/2, h2/2);
146                         } else if (alignment == 2) { // right align
147                                 cairo_translate(cr, w2 - (s * rw1)/2, h2/2);
148                         } else {
149                                 cairo_translate(cr, w2/2, h2/2);
150                         }
151                         cairo_rotate(cr, rotation * M_PI_2);
152                         cairo_scale(cr, s, s);
153                         cairo_translate(cr, -w1/2, -h1/2);
154                         gdk_cairo_set_source_rgba(cr, &black);
155                         pango_cairo_show_layout (cr, layout);
156                 }
157                 g_object_unref(layout);
158         }
159 }
160
161 static gboolean text_keypress(GtkWidget *widget, GdkEventButton *event, gpointer *user_data) {
162         // forward signal to the text view
163         gboolean ret;
164         g_signal_emit_by_name(tv, "key-press-event", event, &ret);
165         gtk_widget_grab_focus(tv);
166         return ret;
167 }
168
169 static gboolean text_clicked(GtkWidget *widget, GdkEventButton *event, gpointer *user_data) {
170         show_entry();
171         if (event->type == GDK_BUTTON_PRESS && event->button == 2) {
172                 GtkClipboard *cb = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
173
174                 gchar *txt = gtk_clipboard_wait_for_text(cb);
175                 if (txt != NULL) {
176                         gtk_text_buffer_set_text(tb,txt,-1);
177                         g_free(txt);
178                 }
179
180         }
181         return FALSE;
182 }
183
184 static gboolean read_chan(GIOChannel *chan, GIOCondition condition, gpointer data){
185         gchar buf[1024];
186         GString *input;
187         GIOStatus stat = G_IO_STATUS_NORMAL;
188         gsize read;
189         GError *err = NULL;
190
191         while ((stat = g_io_channel_read_chars(chan, buf, sizeof(buf), &read, &err)) == G_IO_STATUS_NORMAL && err == NULL) {
192                 g_string_append_len(partial_input, buf, read);
193         }
194
195         if (err != NULL)
196         {
197             fprintf (stderr, "Unable to read stdin: %s\n", err->message);
198             g_error_free (err);
199             return TRUE;
200         }
201
202
203         if (stat == G_IO_STATUS_EOF) {
204                 // There is an end of file, so use the whole input
205                 input = g_string_new_len(partial_input->str, partial_input->len);
206                 g_string_truncate(partial_input, 0);
207         } else {
208                 // There is no end of file. Check for form feed characters.
209                 // Use from the second-to-last to the last.
210                 char *last_ff = strrchr(partial_input->str, '\f');
211                 if (last_ff) {
212                         *last_ff = '\0';
213                         char *snd_last_ff = strrchr(partial_input->str, '\f');
214                         if (snd_last_ff == NULL) snd_last_ff = partial_input->str;
215                         input = g_string_new_len(snd_last_ff, last_ff - snd_last_ff);
216                         g_string_erase(partial_input, 0, last_ff - partial_input->str + 1);
217                 } else {
218                         return TRUE;
219                 }
220         }
221
222         // remove beginning and trailing newlines, if any
223         gssize cnt = 0;
224         while ((input->len > cnt) && (input->str[cnt] == '\n')) {
225                 cnt++;
226         }
227         g_string_erase(input, 0, cnt);
228
229         while ((input->len > 0) && (input->str[input->len - 1] == '\n')) {
230                 g_string_truncate(input, input->len - 1);
231         }
232
233         g_signal_handler_block (tb, text_change_handler);
234         gtk_text_buffer_set_text (tb, input->str, input->len);
235         g_signal_handler_unblock (tb, text_change_handler);
236
237         g_string_free(input, TRUE);
238
239         if (stat == G_IO_STATUS_AGAIN)
240                 return TRUE;
241         else
242                 return FALSE;
243 }
244
245 static void newtext() {
246         gtk_widget_queue_draw(draw);
247 }
248
249 static void newtext_show_input() {
250         show_entry();
251 }
252
253 static void move_cursor(GtkTextView* tv, GtkMovementStep step, gint count, gboolean extend_selection, gpointer user_data) {
254         show_entry();
255 }
256
257 static struct option const long_options[] =
258 {
259         {"help",       no_argument,       NULL, 'h'},
260         {"version",    no_argument,       NULL, 'V'},
261         {"foreground", required_argument, NULL, 'f'},
262         {"background", required_argument, NULL, 'b'},
263         {"font",       required_argument, NULL, 'n'},
264         {"rotate",     required_argument, NULL, 'r'},
265         {"align",      required_argument, NULL, 'a'},
266         {0,0,0,0}
267 };
268
269 static void usage(char *cmd) {
270         printf("Usage: %s [-h|--help] [-V|--version] [-f|--foreground=colordesc] [-b|--background=colordesc] [-n|--font=fontdesc] [-r|--rotate=0,1,2,3] [-a|--align=0,1,2]\n", cmd);
271 }
272
273 static void version() {
274         printf("%s\n", PACKAGE_STRING);
275 }
276
277 gboolean my_gdk_rgba_parse (GdkRGBA *rgba, const gchar *spec) {
278         gboolean ret = gdk_rgba_parse(rgba, spec);
279         if (!ret)  {
280             fprintf (stderr, "Failed to parse color specification %s\n", spec);
281         }
282 }
283
284 int main(int argc, char **argv) {
285         GString *input;
286         int c;
287         int input_provided = 0;
288
289         while ((c = getopt_long (argc, argv, "hVf:b:n:r:a:", long_options, (int *) 0)) != EOF) {
290                 switch (c) {
291                         case 'h':
292                                 usage(argv[0]);
293                                 return 0;
294                                 break;
295
296                         case 'V':
297                                 version();
298                                 return 0;
299                                 break;
300
301                         case 'f':
302                                 foreground = optarg;
303                                 break;
304
305                         case 'b':
306                                 background = optarg;
307                                 break;
308
309                         case 'n':
310                                 fontdesc = optarg;
311                                 break;
312                         case 'r':
313                                 rotation = atoi(optarg);
314                                 break;
315                         case 'a':
316                                 alignment = atoi(optarg);
317                                 break;
318                         default:
319                                 /* unknown switch received - at least
320                                  * give usage but continue and use the
321                                  * data */
322                                 usage(argv[0]);
323                                 break;
324                 }
325         }
326
327         gtk_init(&argc, &argv);
328
329         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
330         gtk_window_set_icon_name (GTK_WINDOW (window), "sm");
331         gtk_window_fullscreen(GTK_WINDOW(window));
332
333         g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
334
335         if (foreground != NULL) {
336                 my_gdk_rgba_parse(&black, foreground);
337         } else {
338                 my_gdk_rgba_parse(&black, "black");
339         }
340         if (background != NULL) {
341                 my_gdk_rgba_parse(&white, background);
342         } else {
343                 my_gdk_rgba_parse(&white, "white");
344         }
345
346         draw = gtk_drawing_area_new();
347         gtk_widget_set_events(draw, GDK_BUTTON_PRESS_MASK|GDK_KEY_PRESS_MASK);
348         gtk_widget_set_size_request(draw,400,400);
349         g_signal_connect(G_OBJECT(draw), "button-press-event", G_CALLBACK(text_clicked), NULL);
350         g_signal_connect(G_OBJECT(draw), "key-press-event", G_CALLBACK(text_keypress), NULL);
351         gtk_widget_set_can_focus(draw, TRUE);
352
353         cursor = gdk_cursor_new_for_display(gtk_widget_get_display(GTK_WIDGET(draw)), GDK_BLANK_CURSOR);
354
355         tv = gtk_text_view_new();
356         tb = gtk_text_view_get_buffer(GTK_TEXT_VIEW(tv));
357
358         partial_input = g_string_new("");
359
360         if (argc > optind)
361                 if (!strcmp(argv[optind], "-") ) {
362                         // read from stdin
363                         GIOChannel *chan = g_io_channel_unix_new(0);
364                         g_io_channel_set_flags(chan, G_IO_FLAG_NONBLOCK, NULL);
365                         g_io_add_watch (chan, G_IO_IN | G_IO_HUP, &read_chan, NULL);
366
367                         input = g_string_new("");
368                         input_provided++;
369                 } else {
370                         int i;
371
372                         input = g_string_new("");
373
374                         for (i = optind; i < argc; i++) {
375                                 g_string_append(input, argv[i]);
376
377                                 if (i < argc - 1) {
378                                         g_string_append(input, " ");
379                                 }
380                         }
381                         input_provided++;
382                 }
383         else
384                 input = g_string_new(":-)");
385
386         gtk_text_buffer_set_text(tb, input->str, input->len);
387         g_string_free(input, TRUE);
388         GtkTextIter start, end;
389         gtk_text_buffer_get_bounds(tb, &start, &end);
390         gtk_text_buffer_select_range(tb, &start, &end);
391
392         quit = gtk_button_new_from_icon_name("application-exit", GTK_ICON_SIZE_BUTTON);
393         g_signal_connect(G_OBJECT(quit), "clicked", G_CALLBACK(gtk_main_quit), NULL);
394
395         GtkWidget *vbox_button = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
396         gtk_box_pack_end(GTK_BOX(vbox_button), quit, FALSE, FALSE, 0);
397
398         GtkWidget *hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL,0);
399         entry_widget = hbox;
400         gtk_box_pack_start(GTK_BOX(hbox), tv,   TRUE,  TRUE,  0);
401         gtk_box_pack_start(GTK_BOX(hbox), vbox_button, FALSE, FALSE, 0);
402
403         GtkWidget *vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL,0);
404         gtk_box_pack_start(GTK_BOX(vbox), draw, TRUE, TRUE, 0);
405         gtk_box_pack_end(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
406
407         gtk_container_add(GTK_CONTAINER(window), vbox);
408
409         font = pango_font_description_new();
410         if (fontdesc != NULL) {
411                 pango_font_description_set_family(font, fontdesc);
412         } else {
413                 pango_font_description_set_family(font, "sans-serif");
414         }
415         pango_font_description_set_size(font, 200*PANGO_SCALE);
416
417         GtkAccelGroup *accel = gtk_accel_group_new();
418         guint key;
419         GdkModifierType mod;
420         gtk_accelerator_parse("<Ctrl>Q", &key, &mod);
421         gtk_accel_group_connect(accel, key, mod, 0, g_cclosure_new(G_CALLBACK(gtk_main_quit), NULL, NULL));
422         gtk_accelerator_parse("Escape", &key, &mod);
423         gtk_accel_group_connect(accel, key, mod, 0, g_cclosure_new(G_CALLBACK(clear_text), NULL, NULL));
424         gtk_window_add_accel_group(GTK_WINDOW(window), accel);
425         gtk_widget_show_all(window);
426
427         g_signal_connect_after(G_OBJECT(draw), "draw", G_CALLBACK(redraw), NULL);
428         text_change_handler = g_signal_connect(G_OBJECT(tb), "changed", G_CALLBACK(newtext_show_input), NULL);
429         g_signal_connect(G_OBJECT(tb), "changed", G_CALLBACK(newtext), NULL);
430         g_signal_connect(G_OBJECT(tv), "move-cursor", G_CALLBACK(move_cursor), NULL);
431
432         if (input_provided)
433                 hide_entry(NULL);
434         else
435                 show_entry();
436
437         gtk_main();
438
439         return 0;
440 }