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