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