No need to include empty default signal handlers
[projects/chimara/chimara.git] / libchimara / graphics.c
1 #include "graphics.h"
2 #include "chimara-glk-private.h"
3 #include "magic.h"
4
5 #define BUFFER_SIZE (1024)
6
7 extern GPrivate glk_data_key;
8 void on_size_prepared(GdkPixbufLoader *loader, gint width, gint height, struct image_info *info);
9 void on_pixbuf_closed(GdkPixbufLoader *loader, gpointer data);
10 glui32 draw_image_common(winid_t win, GdkPixbuf *pixbuf, glsi32 val1, glsi32 val2);
11
12 static gboolean image_loaded;
13 static gboolean size_determined;
14
15 static struct image_info*
16 load_image_from_blorb(giblorb_result_t resource, glui32 image, gint width, gint height)
17 {
18         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
19         GError *pixbuf_error = NULL;
20         guchar *buffer;
21
22         struct image_info *info = g_new0(struct image_info, 1);
23         info->resource_number = image;
24
25         /* Load the resource */
26         GdkPixbufLoader *loader = gdk_pixbuf_loader_new();
27         g_signal_connect( loader, "size-prepared", G_CALLBACK(on_size_prepared), info ); 
28         g_signal_connect( loader, "closed", G_CALLBACK(on_pixbuf_closed), NULL ); 
29
30         /* Scale image if necessary */
31         if(width > 0 && height > 0) {
32                 gdk_pixbuf_loader_set_size(loader, width, height);
33                 info->scaled = TRUE;
34         }
35
36         glk_stream_set_position(glk_data->resource_file, resource.data.startpos, seekmode_Start);
37         buffer = g_malloc( BUFFER_SIZE * sizeof(guchar) );
38
39         guint32 total_read = 0;
40         image_loaded = FALSE;
41         while(total_read < resource.length && !image_loaded) {
42                 guint32 num_read = glk_get_buffer_stream(glk_data->resource_file, (char *) buffer, BUFFER_SIZE);
43
44                 if( !gdk_pixbuf_loader_write(loader, buffer, MIN(BUFFER_SIZE, num_read), &pixbuf_error) ) {
45                         WARNING_S("Cannot read image", pixbuf_error->message);
46                         giblorb_unload_chunk(glk_data->resource_map, image);
47                         gdk_pixbuf_loader_close(loader, &pixbuf_error);
48                         g_free(buffer);
49                         return NULL;
50                 }
51
52                 total_read += num_read;
53         }
54         gdk_pixbuf_loader_close(loader, &pixbuf_error);
55         giblorb_unload_chunk(glk_data->resource_map, resource.chunknum);
56         g_free(buffer);
57
58         /* Wait for the PixbufLoader to finish loading the image */
59         g_mutex_lock(&glk_data->resource_lock);
60         while(!image_loaded) {
61                 g_cond_wait(&glk_data->resource_loaded, &glk_data->resource_lock);
62         }
63         g_mutex_unlock(&glk_data->resource_lock);
64
65         info->pixbuf = gdk_pixbuf_loader_get_pixbuf(loader);
66         g_object_ref(info->pixbuf);
67
68         g_object_unref(loader);
69         return info;
70 }
71
72 static struct image_info *
73 load_image_from_file(const gchar *filename, glui32 image, gint width, gint height)
74 {
75         GError *err = NULL;
76         
77         struct image_info *info = g_new0(struct image_info, 1);
78         info->resource_number = image;
79         
80         if(width > 0 && height > 0) {
81                 info->scaled = TRUE;
82                 info->pixbuf = gdk_pixbuf_new_from_file_at_size(filename, width, height, &err);
83         } else {
84                 info->pixbuf = gdk_pixbuf_new_from_file(filename, &err);
85         }
86         if(!info->pixbuf) {
87                 IO_WARNING("Error loading resource from alternative location", filename, err->message);
88                 g_error_free(err);
89                 g_free(info);
90                 return NULL;
91         }
92         g_object_ref(info->pixbuf);
93
94         return info;
95 }
96
97 static struct image_info*
98 load_image_in_cache(glui32 image, gint width, gint height)
99 {
100         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
101         struct image_info *info = NULL;
102         
103         /* Lookup the proper resource */
104         if(!glk_data->resource_map) {
105                 if(!glk_data->resource_load_callback) {
106                         WARNING("No resource map has been loaded yet.");
107                         return NULL;
108                 }
109                 gchar *filename = glk_data->resource_load_callback(CHIMARA_RESOURCE_IMAGE, image, glk_data->resource_load_callback_data);
110                 if(!filename) {
111                         WARNING("Error loading resource from alternative location");
112                         return NULL;
113                 }
114                 info = load_image_from_file(filename, image, width, height);
115                 g_free(filename);
116         } else {
117                 giblorb_result_t resource;
118                 giblorb_err_t blorb_error = giblorb_load_resource(glk_data->resource_map, giblorb_method_FilePos, &resource, giblorb_ID_Pict, image);
119                 if(blorb_error != giblorb_err_None) {
120                         WARNING_S( "Error loading resource", giblorb_get_error_message(blorb_error) );
121                         return NULL;
122                 }
123                 info = load_image_from_blorb(resource, image, width, height);
124         }
125
126         if(info == NULL)
127                 return NULL;
128
129         /* Store the image in the cache */
130         gdk_threads_enter();
131
132         if( g_slist_length(glk_data->image_cache) >= IMAGE_CACHE_MAX_NUM ) {
133                 struct image_info *head = (struct image_info*) glk_data->image_cache->data;
134                 g_object_unref(head->pixbuf);
135                 g_free(head);
136                 glk_data->image_cache = g_slist_remove_link(glk_data->image_cache, glk_data->image_cache);
137         }
138         info->width = gdk_pixbuf_get_width(info->pixbuf);
139         info->height = gdk_pixbuf_get_height(info->pixbuf);
140         glk_data->image_cache = g_slist_prepend(glk_data->image_cache, info);
141
142         gdk_threads_leave();
143         return info;
144 }
145
146 void
147 on_size_prepared(GdkPixbufLoader *loader, gint width, gint height, struct image_info *info)
148 {
149         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
150
151         g_mutex_lock(&glk_data->resource_lock);
152         info->width = width;
153         info->height = height;
154         size_determined = TRUE;
155         g_cond_broadcast(&glk_data->resource_info_available);
156         g_mutex_unlock(&glk_data->resource_lock);
157 }
158
159 void
160 on_pixbuf_closed(GdkPixbufLoader *loader, gpointer data)
161 {
162         gdk_threads_enter();
163
164         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
165
166         g_mutex_lock(&glk_data->resource_lock);
167         image_loaded = TRUE;
168         g_cond_broadcast(&glk_data->resource_loaded);
169         g_mutex_unlock(&glk_data->resource_lock);
170
171         gdk_threads_leave();
172 }
173
174
175 void
176 clear_image_cache(struct image_info *data, gpointer user_data)
177 {
178         g_object_unref(data->pixbuf);
179         g_free(data);
180 }
181
182 static struct image_info*
183 image_cache_find(struct image_info* to_find)
184 {
185         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
186         GSList *link = glk_data->image_cache;
187
188         gdk_threads_enter();
189
190         /* Empty cache */
191         if(link == NULL) {
192                 gdk_threads_leave();
193                 return NULL;
194         }
195
196         /* Iterate over the cache to find the correct image and size */
197         struct image_info *match = NULL;
198         do {
199                 struct image_info *info = (struct image_info*) link->data;
200                 if(info->resource_number == to_find->resource_number) {
201                         /* Check size: are we looking for a scaled version or the original one? */
202                         if(to_find->scaled) {
203
204                                 if(info->width == to_find->width && info->height == to_find->height) {
205                                         /* Prescaled image found */
206                                         gdk_threads_leave();
207                                         return info;
208                                 }
209                                 else if(info->width >= to_find->width && info->height >= to_find->height) {
210                                         /* Larger image found, needs to be scaled down in order to work */
211                                         gdk_threads_leave();
212                                         match = info;
213                                 }
214                         } else {
215                                 if(!info->scaled) {
216                                         gdk_threads_leave();
217                                         return info; /* Found a match */
218                                 }
219                         }
220                 }
221         } while( (link = g_slist_next(link)) );
222
223         gdk_threads_leave();
224
225         return match;
226 }
227
228 /**
229  * glk_image_get_info:
230  * @image: An image resource number.
231  * @width: Pointer to a location at which to store the image's width.
232  * @height: Pointer to a location at which to store the image's height.
233  *
234  * This gets information about the image resource with the given identifier. It
235  * returns %TRUE (1) if there is such an image, and %FALSE (0) if not. You can
236  * also pass pointers to width and height variables; if the image exists, the
237  * variables will be filled in with the width and height of the image, in
238  * pixels. (You can pass %NULL for either width or height if you don't care
239  * about that information.)
240  * 
241  * <note><para>
242  *   You should always use this function to measure the size of images when you 
243  *   are creating your display. Do this even if you created the images, and you
244  *   know how big they <quote>should</quote> be. This is because images may be 
245  *   scaled in translating from one platform to another, or even from one 
246  *   machine to another. A Glk library might display all images larger than 
247  *   their original size, because of screen resolution or player preference. 
248  *   Images will be scaled proportionally, but you still need to call 
249  *   glk_image_get_info() to determine their absolute size.
250  * </para></note>
251  * 
252  * Returns: %TRUE if @image is a valid identifier, %FALSE if not.
253  */
254 glui32
255 glk_image_get_info(glui32 image, glui32 *width, glui32 *height)
256 {
257         struct image_info *to_find = g_new0(struct image_info, 1);
258         struct image_info *found;
259         to_find->resource_number = image;
260         to_find->scaled = FALSE; /* we want the original image size */
261
262         if( !(found = image_cache_find(to_find)) ) {
263                 found = load_image_in_cache(image, 0, 0);
264                 if(found == NULL)
265                         return FALSE;
266         }
267
268         if(width != NULL)
269                 *width = found->width;
270         if(height != NULL)
271                 *height = found->height;
272         return TRUE;
273 }
274
275 /**
276  * glk_image_draw:
277  * @win: A graphics or text buffer window.
278  * @image: An image resource number.
279  * @val1: The x coordinate at which to draw the image (if @win is a graphics 
280  * window); or, an <link linkend="chimara-imagealign-InlineUp">image 
281  * alignment</link> constant (if @win is a text window).
282  * @val2: The y coordinate at which to draw the image (if @win is a graphics
283  * window); this parameter is ignored if @win is a text buffer window.
284  *
285  * This draws the given image resource in the given window. The position of the
286  * image is given by @val1 and @val2, but their meaning varies depending on what
287  * kind of window you are drawing in. See <link 
288  * linkend="chimara-Graphics-in-Graphics-Windows">Graphics in Graphics 
289  * Windows</link> and <link linkend="Graphics-in-Text-Buffer-Windows">Graphics 
290  * in Text Buffer Windows</link>.
291  * 
292  * This function returns a flag indicating whether the drawing operation 
293  * succeeded.
294  * <note><para>
295  *   A %FALSE result can occur for many reasons. The image data might be 
296  *   corrupted; the library may not have enough memory to operate; there may be 
297  *   no image with the given identifier; the window might not support image 
298  *   display; and so on.
299  * </para></note>
300  *
301  * Returns: %TRUE if the operation succeeded, %FALSE if not.
302  */
303 glui32
304 glk_image_draw(winid_t win, glui32 image, glsi32 val1, glsi32 val2)
305 {
306         VALID_WINDOW(win, return FALSE);
307         g_return_val_if_fail(win->type == wintype_Graphics || win->type == wintype_TextBuffer, FALSE);
308
309         struct image_info *to_find = g_new0(struct image_info, 1);
310         struct image_info *info;
311
312         /* Lookup the proper resource */
313         to_find->resource_number = image;
314         to_find->scaled = FALSE; /* we want the original image size */
315
316         if( !(info = image_cache_find(to_find)) ) {
317                 info = load_image_in_cache(image, 0, 0);
318                 if(info == NULL)
319                         return FALSE;
320         }
321
322         return draw_image_common(win, info->pixbuf, val1, val2);
323 }
324
325 /**
326  * glk_image_draw_scaled:
327  * @win: A graphics or text buffer window.
328  * @image: An image resource number.
329  * @val1: The x coordinate at which to draw the image (if @win is a graphics 
330  * window); or, an <link linkend="chimara-imagealign-InlineUp">image 
331  * alignment</link> constant (if @win is a text window).
332  * @val2: The y coordinate at which to draw the image (if @win is a graphics
333  * window); this parameter is ignored if @win is a text buffer window.
334  * @width: The width of the image.
335  * @height: The height of the image.
336  *
337  * This is similar to glk_image_draw(), but it scales the image to the given 
338  * @width and @height, instead of using the image's standard size. (You can 
339  * measure the standard size with glk_image_get_info().)
340  * 
341  * If @width or @height is zero, nothing is drawn. Since those arguments are 
342  * unsigned integers, they cannot be negative. If you pass in a negative number,
343  * it will be interpreted as a very large positive number, which is almost 
344  * certain to end badly. 
345  *
346  * Returns: %TRUE if the operation succeeded, %FALSE otherwise.
347  */
348 glui32
349 glk_image_draw_scaled(winid_t win, glui32 image, glsi32 val1, glsi32 val2, glui32 width, glui32 height)
350 {
351         VALID_WINDOW(win, return FALSE);
352         g_return_val_if_fail(win->type == wintype_Graphics || win->type == wintype_TextBuffer, FALSE);
353
354         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
355         struct image_info *to_find = g_new0(struct image_info, 1);
356         struct image_info *info;
357         struct image_info *scaled_info;
358
359         /* Lookup the proper resource */
360         to_find->resource_number = image;
361         to_find->scaled = TRUE; /* any image size equal or larger than requested will do */
362
363         if( !(info = image_cache_find(to_find)) ) {
364                 info = load_image_in_cache(image, width, height);
365                 if(info == NULL)
366                         return FALSE;
367         }
368
369         /* Scale the image if necessary */
370         if(info->width != width || info->height != height) {
371                 GdkPixbuf *scaled = gdk_pixbuf_scale_simple(info->pixbuf, width, height, GDK_INTERP_BILINEAR);
372
373                 /* Add the scaled image into the image cache */
374                 scaled_info = g_new0(struct image_info, 1);
375                 scaled_info->resource_number = info->resource_number;
376                 scaled_info->width = gdk_pixbuf_get_width(scaled);
377                 scaled_info->height = gdk_pixbuf_get_width(scaled);
378                 scaled_info->pixbuf = scaled;
379                 scaled_info->scaled = TRUE;
380                 glk_data->image_cache = g_slist_prepend(glk_data->image_cache, scaled_info);
381
382                 /* Continue working with the scaled version */
383                 info = scaled_info;
384         }
385
386         return draw_image_common(win, info->pixbuf, val1, val2);
387 }
388
389 /* Internal function: draws a pixbuf to a graphics window or text buffer */
390 glui32
391 draw_image_common(winid_t win, GdkPixbuf *pixbuf, glsi32 val1, glsi32 val2)
392 {
393         switch(win->type) {
394         case wintype_Graphics:
395         {
396                 gdk_threads_enter();
397
398                 cairo_t *cr = cairo_create(win->backing_store);
399                 gdk_cairo_set_source_pixbuf(cr, pixbuf, val1, val2);
400                 cairo_paint(cr);
401                 cairo_destroy(cr);
402
403                 /* Update the screen */
404                 gtk_widget_queue_draw(win->widget);
405
406                 gdk_threads_leave();
407         }
408                 break;
409
410         case wintype_TextBuffer:
411         {
412                 flush_window_buffer(win);
413
414                 gdk_threads_enter();
415
416                 GtkTextBuffer *buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
417                 GtkTextIter end, start;
418                 gtk_text_buffer_get_end_iter(buffer, &end);
419
420                 gtk_text_buffer_insert_pixbuf(buffer, &end, pixbuf);
421                 start = end;
422                 gtk_text_iter_forward_char(&end);
423
424                 gint height = 0;
425                 switch(val1) {
426                 case imagealign_InlineDown:
427                         height -= win->unit_height;
428                         break;
429                 case imagealign_InlineCenter:
430                         height = -win->unit_height / 2;
431                         break;
432                 case imagealign_InlineUp:
433                 default:
434                         height = 0;
435                 }
436
437                 if(height != 0) {
438                         GtkTextTag *tag = gtk_text_buffer_create_tag(buffer, NULL, "rise", PANGO_SCALE * (-height), NULL);
439                         gtk_text_buffer_apply_tag(buffer, tag, &start, &end);
440                 }
441
442                 gdk_threads_leave();
443         }
444                 break;
445         }
446         return TRUE;
447 }
448
449 /**
450  * glk_window_set_background_color:
451  * @win: A graphics window.
452  * @color: a 32-bit RGB color value.
453  *
454  * This sets the window's background color. It does not change what is currently
455  * displayed; it only affects subsequent clears and resizes. The initial 
456  * background color of each window is white.
457  * 
458  * Colors are encoded in a 32-bit value: the top 8 bits must be zero, the next 8
459  * bits are the red value, the next 8 bits are the green value, and the bottom 8
460  * bits are the blue value. Color values range from 0 to 255.
461  * <note><para>
462  *   So <code>0x00000000</code> is black, <code>0x00FFFFFF</code> is white, and 
463  *   <code>0x00FF0000</code> is bright red.
464  * </para></note>
465  * 
466  * <note><para>
467  *   This function may only be used with graphics windows. To set background 
468  *   colors in a text window, use text styles with color hints; see <link 
469  *   linkend="chimara-Styles">Styles</link>.
470  * </para></note>
471  */
472 void
473 glk_window_set_background_color(winid_t win, glui32 color) 
474 {
475         VALID_WINDOW(win, return);
476         g_return_if_fail(win->type == wintype_Graphics);
477         
478         win->background_color = color;
479 }
480
481 static void
482 glkcairo_set_source_glkcolor(cairo_t *cr, glui32 val)
483 {
484         double r, g, b;
485         r = ((val & 0xff0000) >> 16) / 256.0;
486         g = ((val & 0x00ff00) >> 8) / 256.0;
487         b = (val & 0x0000ff) / 256.0;
488         cairo_set_source_rgb(cr, r, g, b);
489 }
490
491 /**
492  * glk_window_fill_rect:
493  * @win: A graphics window.
494  * @color: A 32-bit RGB color value, see glk_window_set_background_color().
495  * @left: The x coordinate of the top left corner of the rectangle.
496  * @top: The y coordinate of the top left corner of the rectangle.
497  * @width: The width of the rectangle.
498  * @height: The height of the rectangle.
499  *
500  * This fills the given rectangle with the given color. It is legitimate for
501  * part of the rectangle to fall outside the window. If width or height is zero,
502  * nothing is drawn. 
503  */
504 void
505 glk_window_fill_rect(winid_t win, glui32 color, glsi32 left, glsi32 top, glui32 width, glui32 height)
506 {
507         VALID_WINDOW(win, return);
508         g_return_if_fail(win->type == wintype_Graphics);
509
510         gdk_threads_enter();
511
512         cairo_t *cr = cairo_create(win->backing_store);
513         glkcairo_set_source_glkcolor(cr, color);
514         cairo_rectangle(cr, (double)left, (double)top, (double)width, (double)height);
515         cairo_fill(cr);
516         gtk_widget_queue_draw(win->widget);
517         cairo_destroy(cr);
518
519         gdk_threads_leave();
520 }
521
522 /**
523  * glk_window_erase_rect:
524  * @win: A graphics window.
525  * @left: The x coordinate of the top left corner of the rectangle.
526  * @top: The y coordinate of the top left corner of the rectangle.
527  * @width: The width of the rectangle.
528  * @height: The height of the rectangle.
529  *
530  * This fills the given rectangle with the window's background color.
531  * 
532  * You can also fill an entire graphics window with its background color by 
533  * calling glk_window_clear().
534  */
535 void
536 glk_window_erase_rect(winid_t win, glsi32 left, glsi32 top, glui32 width, glui32 height)
537 {
538         glk_window_fill_rect(win, win->background_color, left, top, width, height);
539 }
540
541 /**
542  * glk_window_flow_break:
543  * @win: A window.
544  *
545  * You may wish to <quote>break</quote> the stream of text down below the 
546  * current margin image. Since lines of text can be in any font and size, you 
547  * cannot do this by counting newlines. Instead, use this function.
548  *
549  * If the current point in the text is indented around a margin-aligned image, 
550  * this acts like the correct number of newlines to start a new line below the 
551  * image. (If there are several margin-aligned images, it goes below all of 
552  * them.) If the current point is not beside a margin-aligned image, this call 
553  * has no effect.
554  *
555  * When a text buffer window is resized, a flow-break behaves cleverly; it may 
556  * become active or inactive as necessary. You can consider this function to 
557  * insert an invisible mark in the text stream. The mark works out how many 
558  * newlines it needs to be whenever the text is formatted for display.
559  * 
560  * An example of the use of glk_window_flow_break(): If you display a 
561  * left-margin image at the start of every line, they can stack up in a strange 
562  * diagonal way that eventually squeezes all the text off the screen. 
563  * <note><para>
564  *   If you can't picture this, draw some diagrams. Make the margin images more 
565  *   than one line tall, so that each line starts already indented around the 
566  *   last image.
567  * </para></note>
568  * To avoid this problem, call glk_window_flow_break() immediately before 
569  * glk_image_draw() for every margin-aligned image.
570  * 
571  * In all windows other than text buffers, glk_window_flow_break() has no 
572  * effect. 
573  *
574  * <warning><para>
575  *   This function is not implemented yet.
576  * </para></warning>
577  */
578 void glk_window_flow_break(winid_t win)
579 {
580         VALID_WINDOW(win, return);
581 }
582
583 /* Called when the graphics window is resized, restacked, or moved. Resize the
584 backing store if necessary. */
585 gboolean
586 on_graphics_configure(GtkWidget *widget, GdkEventConfigure *event, winid_t win)
587 {
588         int oldwidth = 0, oldheight = 0;
589
590         /* Determine whether the backing store can stay the same size */
591         gboolean needs_resize = FALSE;
592         if(win->backing_store == NULL)
593                 needs_resize = TRUE;
594         else {
595                 oldwidth = cairo_image_surface_get_width(win->backing_store);
596                 oldheight = cairo_image_surface_get_height(win->backing_store);
597                 if(oldwidth != event->width || oldheight != event->height)
598                         needs_resize = TRUE;
599         }
600
601         if(needs_resize) {
602                 /* Create a new backing store */
603                 cairo_surface_t *new_backing_store = gdk_window_create_similar_surface( gtk_widget_get_window(widget), CAIRO_CONTENT_COLOR, gtk_widget_get_allocated_width(widget), gtk_widget_get_allocated_height(widget) );
604                 cairo_t *cr = cairo_create(new_backing_store);
605
606                 /* Clear to background color */
607                 glkcairo_set_source_glkcolor(cr, win->background_color);
608                 cairo_paint(cr);
609
610                 if(win->backing_store != NULL) {
611                         /* Copy the contents of the old backing store */
612                         cairo_set_source_surface(cr, win->backing_store, 0, 0);
613                         cairo_paint(cr);
614                         cairo_surface_destroy(win->backing_store);
615                 }
616
617                 cairo_destroy(cr);
618                 /* Use the new backing store */
619                 win->backing_store = new_backing_store;
620         }
621
622         return TRUE; /* Event handled, stop processing */
623 }
624
625 /* Draw the backing store to the screen. Called whenever the drawing area is
626 exposed. */
627 gboolean
628 on_graphics_draw(GtkWidget *widget, cairo_t *cr, winid_t win)
629 {
630         cairo_set_source_surface(cr, win->backing_store, 0, 0);
631         cairo_paint(cr);
632         return FALSE;
633 }