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