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