2 * $Id: ext.c 59 2005-06-08 16:13:15Z tilman $
4 * Copyright (c) 2005 Tilman Sauerbeck (tilman at code-monkey de)
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 #define CHECK_KEY(key) \
32 if (rb_funcall (key, id_include, 1, INT2FIX (0)) == Qtrue) \
33 rb_raise (rb_eArgError, "key must not contain binary zeroes");
35 #define CHECK_CLOSED(ef) \
37 rb_raise (rb_eIOError, "closed stream");
39 #ifdef WORDS_BIGENDIAN
41 ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | \
42 (((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24))
43 #else /* !WORDS_BIGENDIAN */
44 # define BSWAP32(x) (x)
45 #endif /* WORDS_BIGENDIAN */
47 static VALUE c_close (VALUE self);
49 static VALUE cStream, cChunk,
50 eEetError, eNameError, ePropError,
51 sym_lossy, sym_level, sym_quality, sym_double;
52 static ID id_include, id_serialize, id_push, id_keys,
53 id_to_eet_chunks, id_to_eet_name, id_to_eet_properties,
57 c_free (Eet_File **ef)
74 return Data_Make_Struct (klass, Eet_File *, NULL, c_free, ef);
79 * Eet::File.open(file [, mode] ) -> ef or nil
80 * Eet::File.open(file [, mode] ) { |ef| block } -> nil
82 * If a block isn't specified, Eet::File.open is a synonym for
84 * If a block is given, it will be invoked with the
85 * Eet::File object as a parameter, and the file will be
86 * automatically closed when the block terminates. The call always
87 * returns +nil+ in this case.
90 c_open (int argc, VALUE *argv, VALUE klass)
92 VALUE obj = rb_class_new_instance (argc, argv, klass);
94 if (rb_block_given_p ())
95 return rb_ensure (rb_yield, obj, c_close, obj);
102 * Eet::File.new(file [, mode] ) -> ef or nil
104 * Creates an Eet::File object for _file_.
106 * _file_ is opened with the specified mode (defaulting to "r").
107 * Possible values for _mode_ are "r" for read-only access,
108 * "w" for write-only access and "r+" for read/write access.
111 c_init (int argc, VALUE *argv, VALUE self)
113 VALUE file = Qnil, mode = Qnil;
114 Eet_File **ef = NULL;
115 Eet_File_Mode m = EET_FILE_MODE_READ;
116 const char *tmp, *cfile;
118 Data_Get_Struct (self, Eet_File *, ef);
120 rb_scan_args (argc, argv, "11", &file, &mode);
122 cfile = StringValuePtr (file);
125 tmp = StringValuePtr (mode);
126 if (!strcmp (tmp, "r+"))
127 m = EET_FILE_MODE_READ_WRITE;
128 else if (!strcmp (tmp, "w"))
129 m = EET_FILE_MODE_WRITE;
130 else if (strcmp (tmp, "r"))
131 rb_raise (rb_eArgError, "illegal access mode %s", tmp);
136 *ef = eet_open (cfile, m);
139 case EET_FILE_MODE_READ_WRITE:
140 case EET_FILE_MODE_WRITE:
141 tmp = "Permission denied - %s";
144 tmp = "File not found - %s";
148 rb_raise (rb_eRuntimeError, tmp, cfile);
158 * Closes _ef_ and flushes any pending writes.
159 * _ef_ is unavailable for any further data operations;
160 * an +IOError+ is raised if such an attempt is made.
162 * Eet::File objects are automatically closed when they
163 * are claimed by the garbage collector.
168 Eet_File **ef = NULL;
170 Data_Get_Struct (self, Eet_File *, ef);
183 * ef.list([glob]) -> array
185 * Returns an Array of entries in _ef_ that match the shell glob
186 * _glob_ (defaulting to "*").
189 c_list (int argc, VALUE *argv, VALUE self)
191 VALUE glob = Qnil, ret;
192 Eet_File **ef = NULL;
193 char **entries, *tmp = "*";
196 Data_Get_Struct (self, Eet_File *, ef);
199 switch (eet_mode_get (*ef)) {
200 case EET_FILE_MODE_READ:
201 case EET_FILE_MODE_READ_WRITE:
204 rb_raise (rb_eIOError, "cannot list entries");
207 rb_scan_args (argc, argv, "01", &glob);
210 tmp = StringValuePtr (glob);
214 entries = eet_list (*ef, tmp, &count);
216 for (i = 0; i < count; i++)
217 rb_ary_push (ret, rb_str_new2 (entries[i]));
226 * ef.delete(key) -> ef
228 * Deletes the entry from _ef_ that is stored as _key_.
229 * If the entry cannot be deleted, an +IOError+ is raised,
230 * otherwise _ef_ is returned.
233 c_delete (VALUE self, VALUE key)
235 Eet_File **ef = NULL;
238 Data_Get_Struct (self, Eet_File *, ef);
241 ckey = StringValuePtr (key);
244 if (!eet_delete (*ef, ckey))
245 rb_raise (rb_eIOError, "cannot delete entry - %s", ckey);
252 * ef.read(key) -> string
254 * Reads an entry from _ef_ that is stored as _key_.
255 * If the data cannot be read, an +IOError+ is raised,
256 * otherwise a String is returned that contains the data.
259 c_read (VALUE self, VALUE key)
262 Eet_File **ef = NULL;
267 Data_Get_Struct (self, Eet_File *, ef);
270 ckey = StringValuePtr (key);
273 data = eet_read (*ef, ckey, &size);
275 rb_raise (rb_eIOError, "cannot read entry - %s", ckey);
277 ret = rb_str_new (data, size);
286 * ef.write(key, data [, compress] ) -> integer
288 * Stores _data_ in _ef_ as _key_.
289 * If _compress_ is true (which is the default), the data will be
291 * If the data cannot be written, an +IOError+ is raised,
292 * otherwise a the number of bytes written is returned.
295 c_write (int argc, VALUE *argv, VALUE self)
297 VALUE key = Qnil, buf = Qnil, comp = Qnil;
298 Eet_File **ef = NULL;
302 Data_Get_Struct (self, Eet_File *, ef);
305 rb_scan_args (argc, argv, "21", &key, &buf, &comp);
310 ckey = StringValuePtr (key);
312 cbuf = StringValuePtr (buf);
314 n = eet_write (*ef, ckey,
315 cbuf, RSTRING (buf)->len,
318 rb_raise (rb_eIOError, "couldn't write to file");
325 * ef.read_image(key) -> array
327 * Reads an image entry from _ef_ that is stored as _key_.
328 * If the data cannot be read, an +IOError+ is raised,
329 * otherwise an Array is returned that contains the image data,
330 * the image width, the image height, a boolean that indicates
331 * whether the image has an alpha channel or not and a hash
332 * that contains the compression options that were used to store
333 * the image (see Eet::File#write_image).
336 c_read_image (VALUE self, VALUE key)
339 Eet_File **ef = NULL;
342 int w = 0, h = 0, has_alpha = 0, level = 0, quality = 0, lossy = 0;
344 Data_Get_Struct (self, Eet_File *, ef);
347 ckey = StringValuePtr (key);
350 data = eet_data_image_read (*ef, ckey, &w, &h,
351 &has_alpha, &level, &quality,
354 rb_raise (rb_eIOError, "cannot read entry - %s", ckey);
356 comp = rb_hash_new ();
357 rb_hash_aset (comp, sym_lossy, INT2FIX (lossy));
358 rb_hash_aset (comp, sym_level, INT2FIX (level));
359 rb_hash_aset (comp, sym_quality, INT2FIX (quality));
361 ret = rb_ary_new3 (5, rb_str_new (data, w * h * 4),
362 INT2FIX (w), INT2FIX (h),
363 has_alpha ? Qtrue : Qfalse, comp);
371 * ef.write_image(key, image_data, w, h [, alpha] [, comp] ) -> integer
373 * Stores _image_data_ with width _w_ and height _h_ in _ef_ as _key_.
374 * Pass true for _alpha_ if the image contains an alpha channel.
375 * You can control how the image is compressed by passing _comp_, which
376 * is a hash whose :lossy entry is true if the image should be
377 * compressed lossily. If :lossy is true, the :quality entry
378 * (0-100, default 100) sets the compression quality.
379 * If :lossy is false, the :level entry (0-9, default 9) sets the
380 * compression level. If _comp_ isn't passed, then the
381 * image is stored losslessly.
382 * If the data cannot be written, an +IOError+ is raised,
383 * otherwise a the number of bytes written is returned.
386 c_write_image (int argc, VALUE *argv, VALUE self)
388 VALUE key = Qnil, buf = Qnil, w = Qnil, h = Qnil, has_alpha = Qnil;
389 VALUE comp = Qnil, tmp;
390 Eet_File **ef = NULL;
392 int n, lossy = 0, level = 9, quality = 100;
394 Data_Get_Struct (self, Eet_File *, ef);
397 rb_scan_args (argc, argv, "42", &key, &buf, &w, &h, &has_alpha,
400 if (NIL_P (has_alpha))
403 ckey = StringValuePtr (key);
405 cbuf = StringValuePtr (buf);
406 Check_Type (w, T_FIXNUM);
407 Check_Type (h, T_FIXNUM);
410 Check_Type (comp, T_HASH);
412 tmp = rb_hash_aref (comp, sym_lossy);
414 lossy = FIX2INT (tmp);
416 tmp = rb_hash_aref (comp, sym_level);
418 level = FIX2INT (tmp);
420 tmp = rb_hash_aref (comp, sym_quality);
422 quality = FIX2INT (tmp);
425 if (!RSTRING (buf)->len)
428 n = eet_data_image_write (*ef, ckey, cbuf,
429 FIX2INT (w), FIX2INT (h),
431 level, quality, lossy);
433 rb_raise (rb_eIOError, "couldn't write to file");
439 stream_serialize (VALUE self)
442 struct RArray *stream;
445 ret = rb_str_new2 ("");
447 stream = RARRAY (self);
451 for (i = 0; i < stream->len; i++) {
452 VALUE str = rb_funcall (stream->ptr[i], id_serialize, 0, NULL);
454 rb_str_append (ret, str);
461 chunk_init (VALUE self, VALUE tag, VALUE data)
468 if (rb_funcall (tag, id_include, 1, INT2FIX (0)) == Qtrue) \
469 rb_raise (rb_eArgError, "tag must not contain binary zeroes");
471 /* libeet uses a signed 32bit integer to store the
472 * chunk size, so make sure we don't overflow it
474 len = RSTRING (tag)->len + 1 + RSTRING (data)->len;
475 if (len < 0 || len >= 2147483647L)
476 rb_raise (rb_eArgError, "tag or data too long");
478 rb_ivar_set (self, id_tag, rb_str_dup_frozen (tag));
479 rb_ivar_set (self, id_data, rb_str_dup_frozen (data));
485 chunk_serialize (VALUE self)
488 unsigned int size, buf_len;
490 struct RString *tag, *data;
492 tmp = rb_ivar_get (self, id_tag);
496 tmp = rb_ivar_get (self, id_data);
498 data = RSTRING (tmp);
500 buf_len = 9 + tag->len + data->len;
501 ret = rb_str_buf_new (buf_len);
503 buf = RSTRING (ret)->ptr;
504 RSTRING (ret)->len = buf_len;
506 memcpy (buf, "CHnK", 4);
509 size = tag->len + data->len + 1;
510 size = BSWAP32 (size);
511 memcpy (buf, &size, 4);
514 memcpy (buf, tag->ptr, tag->len);
519 memcpy (buf, data->ptr, data->len);
525 for_each_prop (VALUE tag, VALUE arg, VALUE stream)
527 VALUE value, type, chunks;
530 if (rb_obj_is_kind_of (arg, rb_cArray) == Qfalse)
531 rb_raise (ePropError, "hash value is not an array");
533 value = rb_ary_entry (arg, 0);
537 type = rb_ary_entry (arg, 1);
538 chunks = rb_funcall (value, id_to_eet_chunks, 2, tag, type);
540 len = RARRAY (chunks)->len;
542 for (i = 0; i < len; i++)
543 rb_funcall (stream, id_push, 1, rb_ary_entry (chunks, i));
550 * object.to_eet -> string
552 * Serializes the receiver to EET format.
555 c_to_eet (VALUE self)
557 VALUE props, name, stream, chunk, args[2];
558 #ifndef HAVE_RB_HASH_FOREACH
563 props = rb_funcall (self, id_to_eet_properties, 0);
565 if (rb_obj_is_kind_of (props, rb_cHash) == Qfalse ||
566 !RHASH (props)->tbl->num_entries)
567 rb_raise (ePropError, "invalid EET properties");
569 name = rb_funcall (self, id_to_eet_name, 0);
572 if (!RSTRING (name)->len ||
573 rb_funcall (name, id_include, 1, INT2FIX (0)))
574 rb_raise (eNameError, "invalid EET name");
576 stream = rb_class_new_instance (0, NULL, cStream);
578 #ifdef HAVE_RB_HASH_FOREACH
579 rb_hash_foreach (props, for_each_prop, stream);
581 keys = RARRAY (rb_funcall (props, id_keys, 0));
583 for (i = 0; i < keys->len; i++)
584 for_each_prop (keys->ptr[i],
585 rb_hash_aref (props, keys->ptr[i]),
590 args[1] = rb_funcall (stream, id_serialize, 0);
591 chunk = rb_class_new_instance (2, args, cChunk);
593 stream = rb_class_new_instance (1, &chunk, cStream);
595 return rb_funcall (stream, id_serialize, 0);
599 float_to_eet_chunks (int argc, VALUE *argv, VALUE self)
601 VALUE tag, type = Qnil, args[2], chunk;
606 rb_scan_args (argc, argv, "11", &tag, &type);
610 /* switch locale to make sure we get proper snprintf output */
611 loc = setlocale (LC_NUMERIC, "C");
613 len = snprintf (buf, sizeof (buf) - 1, "%a",
614 type == sym_double ? d : (float) d);
617 setlocale (LC_NUMERIC, loc);
622 args[1] = rb_str_new (buf, len);
623 chunk = rb_class_new_instance (2, args, cChunk);
625 return rb_ary_new3 (1, chunk);
633 m = rb_define_module ("Eet");
635 c = rb_define_class_under (m, "File", rb_cObject);
636 rb_define_alloc_func (c, c_alloc);
637 rb_define_singleton_method (c, "open", c_open, -1);
638 rb_define_method (c, "initialize", c_init, -1);
639 rb_define_method (c, "close", c_close, 0);
640 rb_define_method (c, "list", c_list, -1);
641 rb_define_method (c, "delete", c_delete, 1);
642 rb_define_method (c, "read", c_read, 1);
643 rb_define_method (c, "write", c_write, -1);
644 rb_define_method (c, "read_image", c_read_image, 1);
645 rb_define_method (c, "write_image", c_write_image, -1);
647 cStream = rb_define_class_under (m, "Stream", rb_cArray);
648 rb_define_method (cStream, "serialize", stream_serialize, 0);
650 cChunk = rb_define_class_under (m, "Chunk", rb_cObject);
651 rb_define_method (cChunk, "initialize", chunk_init, 2);
652 rb_define_method (cChunk, "serialize", chunk_serialize, 0);
654 rb_define_attr (cChunk, "tag", 1, 0);
655 rb_define_attr (cChunk, "data", 1, 0);
657 rb_define_method (rb_cObject, "to_eet", c_to_eet, 0);
659 rb_define_method (rb_cFloat, "to_eet_chunks", float_to_eet_chunks, -1);
661 eEetError = rb_define_class_under (m, "EetError", rb_eStandardError);
662 eNameError = rb_define_class_under (m, "NameError", eEetError);
663 ePropError = rb_define_class_under (m, "PropertyError", eEetError);
665 id_include = rb_intern ("include?");
666 id_serialize = rb_intern ("serialize");
667 id_push = rb_intern ("push");
668 id_keys = rb_intern ("keys");
669 id_to_eet_chunks = rb_intern ("to_eet_chunks");
670 id_to_eet_name = rb_intern ("to_eet_name");
671 id_to_eet_properties = rb_intern ("to_eet_properties");
672 id_tag = rb_intern ("@tag");
673 id_data = rb_intern ("@data");
674 sym_lossy = ID2SYM (rb_intern ("lossy"));
675 sym_level = ID2SYM (rb_intern ("level"));
676 sym_quality = ID2SYM (rb_intern ("quality"));
677 sym_double = ID2SYM (rb_intern ("double"));