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