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