icosave.c 27.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* The GIMP -- an image manipulation program
 * Copyright (C) 1995-1997 Spencer Kimball and Peter Mattis
 *
 * GIMP Plug-in for Windows Icon files.
 * Copyright (C) 2002 Christian Kreibich <christian@whoop.org>.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "config.h"

#include <errno.h>
#include <string.h>

27 28
#include <glib/gstdio.h>

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#include <libgimp/gimp.h>
#include <libgimp/gimpui.h>

/* #define ICO_DBG */

#include "main.h"
#include "icoload.h"
#include "icodialog.h"

#include "libgimp/stdplugins-intl.h"


static gint     ico_write_int8         (FILE *fp, guint8 *data, gint count);
static gint     ico_write_int16        (FILE *fp, guint16 *data, gint count);
static gint     ico_write_int32        (FILE *fp, guint32 *data, gint count);

static gint *   ico_show_icon_dialog   (gint32 image_ID, gint *num_icons);

/* Helpers to set bits in a *cleared* data chunk */
static void     ico_set_bit_in_data    (guint8 *data, gint line_width,
                                        gint bit_num, gint bit_val);
static void     ico_set_nibble_in_data (guint8 *data, gint line_width,
                                        gint nibble_num, gint nibble_val);
static void     ico_set_byte_in_data   (guint8 *data, gint line_width,
                                        gint byte_num, gint byte_val);

55 56 57 58 59 60 61
static gint     ico_get_layer_num_colors  (gint32    layer,
					   gboolean *uses_alpha_levels);
static void     ico_image_get_reduced_buf (guint32   layer,
					   gint      bpp,
					   gint     *num_colors,
					   guchar  **cmap_out,
					   guchar  **buf_out);
62 63 64 65


static gint
ico_write_int32 (FILE     *fp,
66 67
                 guint32  *data,
                 gint      count)
68
{
69
  gint total;
70 71 72 73

  total = count;
  if (count > 0)
    {
74 75 76
#if (G_BYTE_ORDER == G_BIG_ENDIAN)
      gint i;

77
      for (i = 0; i < count; i++)
78 79
        data[i] = GUINT32_FROM_LE (data[i]);
#endif
80

81
      ico_write_int8 (fp, (guint8 *) data, count * 4);
82 83 84 85 86 87

#if (G_BYTE_ORDER == G_BIG_ENDIAN)
      /* Put it back like we found it */
      for (i = 0; i < count; i++)
        data[i] = GUINT32_FROM_LE (data[i]);
#endif
88 89 90 91 92 93 94 95
    }

  return total * 4;
}


static gint
ico_write_int16 (FILE     *fp,
96 97
                 guint16  *data,
                 gint      count)
98
{
99
  gint total;
100 101 102 103

  total = count;
  if (count > 0)
    {
104 105 106
#if (G_BYTE_ORDER == G_BIG_ENDIAN)
      gint i;

107
      for (i = 0; i < count; i++)
108 109
        data[i] = GUINT16_FROM_LE (data[i]);
#endif
110

111
      ico_write_int8 (fp, (guint8 *) data, count * 2);
112 113 114 115 116 117

#if (G_BYTE_ORDER == G_BIG_ENDIAN)
      /* Put it back like we found it */
      for (i = 0; i < count; i++)
        data[i] = GUINT16_FROM_LE (data[i]);
#endif
118 119 120 121 122 123 124 125
    }

  return total * 2;
}


static gint
ico_write_int8 (FILE     *fp,
126 127
                guint8   *data,
                gint      count)
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
{
  gint total;
  gint bytes;

  total = count;
  while (count > 0)
    {
      bytes = fwrite ((gchar *) data, sizeof (gchar), count, fp);
      if (bytes <= 0) /* something bad happened */
        break;
      count -= bytes;
      data += bytes;
    }

  return total;
}


static gint*
ico_show_icon_dialog (gint32  image_ID,
                      gint   *num_icons)
{
  GtkWidget *dialog, *hbox;
151
  GtkWidget *icon_menu;
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
  gint      *layers, *icon_depths = NULL;
  gint       num_layers, i, num_colors;
  gboolean   uses_alpha_values;
  gchar      key[MAXLEN];

  *num_icons = 0;

  gimp_ui_init ("winicon", TRUE);

  layers = gimp_image_get_layers (image_ID, &num_layers);
  dialog = ico_specs_dialog_new (num_layers);

  for (i = 0; i < num_layers; i++)
    {
      /* if (gimp_layer_get_visible(layers[i])) */
      ico_specs_dialog_add_icon (dialog, layers[i], i);
    }

  /* Scale the thing to approximately fit its content, but not too large ... */
  gtk_window_set_default_size (GTK_WINDOW (dialog),
172 173
                               -1,
                               120 + (num_layers > 4 ? 500 : num_layers * 120));
174 175 176 177 178 179 180 181 182 183 184 185 186

  icon_depths = g_object_get_data (G_OBJECT (dialog), "icon_depths");

  /* Limit the color depths to values that don't cause any color loss --
     the user should pick these anyway, so we can save her some time.
     If the user wants to lose some colors, the settings can always be changed
     in the dialog: */
  for (i = 0; i < num_layers; i++)
    {
      num_colors = ico_get_layer_num_colors (layers[i], &uses_alpha_values);

      g_snprintf (key, MAXLEN, "layer_%i_hbox", layers[i]);
      hbox = g_object_get_data (G_OBJECT (dialog), key);
187
      icon_menu = g_object_get_data (G_OBJECT (hbox), "icon_menu");
188 189

      if (!uses_alpha_values)
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
        {
          if (num_colors <= 2)
            {
              /* Let's suggest monochrome */
              icon_depths[i] = 1;
              icon_depths[num_layers + i] = 1;
              ico_specs_dialog_update_icon_preview (dialog, layers[i], 2);
              gtk_combo_box_set_active (GTK_COMBO_BOX (icon_menu), 0);
            }
          else if (num_colors <= 16)
            {
              /* Let's suggest 4bpp */
              icon_depths[i] = 4;
              icon_depths[num_layers + i] = 4;
              ico_specs_dialog_update_icon_preview (dialog, layers[i], 4);
              gtk_combo_box_set_active (GTK_COMBO_BOX (icon_menu), 1);
            }
          else if (num_colors <= 256)
            {
              /* Let's suggest 8bpp */
              icon_depths[i] = 8;
              icon_depths[num_layers + i] = 8;
              ico_specs_dialog_update_icon_preview (dialog, layers[i], 8);
              gtk_combo_box_set_active (GTK_COMBO_BOX (icon_menu), 2);
            }
        }
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239

      /* Otherwise, or if real alpha levels are used, stick with 32bpp */
    }

  g_free (layers);

  gtk_widget_show (dialog);

  if (gimp_dialog_run (GIMP_DIALOG (dialog)) == GTK_RESPONSE_OK)
    *num_icons = num_layers;
  else
    icon_depths = NULL;

  gtk_widget_destroy (dialog);

  return icon_depths;
}


static GimpPDBStatusType
ico_init (const gchar *filename,
          MsIcon      *ico,
          gint         num_icons)
{
240
  memset (ico, 0, sizeof (MsIcon));
241

242
  if (! (ico->fp = g_fopen (filename, "wb")))
243 244 245 246 247 248 249 250
    {
      g_message (_("Could not open '%s' for writing: %s"),
                 gimp_filename_to_utf8 (filename), g_strerror (errno));
      return GIMP_PDB_EXECUTION_ERROR;
    }

  ico->filename      = filename;
  ico->reserved      = 0;
251
  ico->resource_type = 1;
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
  ico->icon_count    = num_icons;
  ico->icon_dir      = g_new0 (MsIconEntry, num_icons);
  ico->icon_data     = g_new0 (MsIconData, num_icons);

  return GIMP_PDB_SUCCESS;
}


static void
ico_init_direntry (MsIconEntry *entry,
                   gint32       layer,
                   gint         bpp)
{
  /* Was calloc'd, so initialized to 0. */
  entry->width  = gimp_drawable_width (layer);
  entry->height = gimp_drawable_height (layer);

  if (bpp < 8)
    entry->num_colors = (1 << bpp);

  entry->num_planes = 1;
  entry->bpp        = bpp;

  D(("Initialized entry to w %i, h %i, bpp %i\n",
     gimp_drawable_width (layer), entry->width, entry->bpp));

  /* We'll set size and offset when writing things out */
}


static void
ico_set_bit_in_data (guint8 *data,
                     gint    line_width,
                     gint    bit_num,
                     gint    bit_val)
{
  gint line;
  gint width32;
  gint offset;

  /* width per line in multiples of 32 bits */
  width32 = (line_width % 32 == 0 ? line_width/32 : line_width/32 + 1);

  line = bit_num / line_width;
  offset = bit_num % line_width;
  bit_val = bit_val & 0x00000001;

299
  data[line * width32 * 4 + offset/8] |= (bit_val << (7 - (offset % 8)));
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
}


static void
ico_set_nibble_in_data (guint8 *data,
                        gint    line_width,
                        gint    nibble_num,
                        gint    nibble_val)
{
  gint line;
  gint width8;
  gint offset;

  /* width per line in multiples of 32 bits */
  width8 = (line_width % 8 == 0 ? line_width/8 : line_width/8 + 1);

  line = nibble_num / line_width;
  offset = nibble_num % line_width;
  nibble_val = nibble_val & 0x0000000F;

320
  data[line * width8 * 4 + offset/2] |= (nibble_val << (4 * (1 - (offset % 2))));
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
}


static void
ico_set_byte_in_data (guint8 *data,
                      gint    line_width,
                      gint    byte_num,
                      gint    byte_val)
{
  gint line;
  gint width4;
  gint offset;
  gint byte;

  /* width per line in multiples of 32 bits */
  width4 = (line_width % 4 == 0 ? line_width/4 : line_width/4 + 1);

  line = byte_num / line_width;
  offset = byte_num % line_width;
  byte = byte_val & 0x000000FF;

  data[line * width4 * 4 + offset] = byte;
}



/* Create a colormap from the given buffer data */
static guint32 *
ico_create_palette(guchar *cmap,
                   gint    num_colors,
                   gint    num_colors_used,
                   gint   *black_slot)
{
  guchar *palette;
  gint    i;

357
  g_return_val_if_fail (cmap != NULL || num_colors_used == 0, NULL);
358 359
  g_return_val_if_fail (num_colors_used <= num_colors, NULL);

360 361 362 363 364 365 366 367 368 369
  palette = g_new0 (guchar, num_colors * 4);
  *black_slot = -1;

  for (i = 0; i < num_colors_used; i++)
    {
      palette[i * 4 + 2] = cmap[i * 3];
      palette[i * 4 + 1] = cmap[i * 3 + 1];
      palette[i * 4]     = cmap[i * 3 + 2];

      if ((cmap[i*3]     == 0) &&
370 371 372 373 374
          (cmap[i*3 + 1] == 0) &&
          (cmap[i*3 + 2] == 0))
        {
          *black_slot = i;
        }
375 376 377 378 379
    }

  if (*black_slot == -1)
    {
      if (num_colors_used == num_colors)
380 381 382 383 384 385 386 387
        {
          D(("WARNING -- no room for black, this shouldn't happen.\n"));
          *black_slot = num_colors - 1;

          palette[(num_colors-1) * 4]     = 0;
          palette[(num_colors-1) * 4 + 1] = 0;
          palette[(num_colors-1) * 4 + 2] = 0;
        }
388
      else
389 390 391
        {
          *black_slot = num_colors_used;
        }
392 393
    }

394
  return (guint32 *) palette;
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
}


static GHashTable *
ico_create_color_to_palette_map (guint32 *palette,
                                 gint     num_colors)
{
  GHashTable *hash;
  gint i;

  hash = g_hash_table_new (g_int_hash, g_int_equal);

  for (i = 0; i < num_colors; i++)
    {
      gint *color, *slot;
410
      guint8 *pixel = (guint8 *) &palette[i];
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466

      color = g_new (gint, 1);
      slot = g_new (gint, 1);

      *color = (pixel[2] << 16 | pixel[1] << 8 | pixel[0]);
      *slot = i;

      g_hash_table_insert (hash, color, slot);
    }

  return hash;
}


static void
ico_free_hash_item (gpointer data1,
                    gpointer data2,
                    gpointer data3)
{
  g_free (data1);
  g_free (data2);

  /* Shut up warnings: */
  data3 = NULL;
}


static gint
ico_get_palette_index (GHashTable *hash,
                       gint        red,
                       gint        green,
                       gint        blue)
{
  gint  color = 0;
  gint *slot;

  color = (red << 16 | green << 8 | blue);
  slot = g_hash_table_lookup (hash, &color);

  if (!slot)
    {
      return 0;
    }

  return *slot;
}

static void
ico_init_data (MsIcon *ico,
               gint    num_icon,
               gint32  layer,
               gint    bpp)
{
  MsIconEntry    *entry;
  MsIconData     *data;
  gint            and_len, xor_len, palette_index, x, y;
467
  gint            num_colors = 0, num_colors_used = 0, black_index = 0;
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
  guchar         *buffer = NULL, *pixel;
  guint32        *buffer32;
  guchar         *palette;
  GHashTable     *color_to_slot = NULL;

  D(("Creating data structures for icon %i ------------------------\n", num_icon));

  /* Shortcuts, for convenience */
  entry = &ico->icon_dir[num_icon];
  data  = &ico->icon_data[num_icon];

  /* Entries and data were calloc'd, so initialized to 0. */

  data->header_size = 40;
  data->width       = gimp_drawable_width (layer);
  data->height      = 2 * gimp_drawable_height (layer);
  data->planes      = 1;
  data->bpp         = bpp;

  num_colors = (1L << bpp);

  D(("  header size %i, w %i, h %i, planes %i, bpp %i\n",
     data->header_size, data->width, data->height, data->planes, data->bpp));

  /* Reduce colors in copy of image */
493
  ico_image_get_reduced_buf (layer, bpp, &num_colors_used, &palette, &buffer);
494
  buffer32 = (guint32 *) buffer;
495 496 497 498 499 500 501 502 503 504 505 506 507

  /* Set up colormap and andmap when necessary: */
  if (bpp <= 8)
    {
      /* Create a colormap */
      data->palette = ico_create_palette (palette,
                                          num_colors, num_colors_used,
                                          &black_index);
      data->palette_len = num_colors * 4;

      color_to_slot = ico_create_color_to_palette_map (data->palette,
                                                       num_colors_used);
      D(("  created %i-slot colormap with %i colors, black at slot %i\n",
508
         num_colors, num_colors_used, black_index));
509 510 511 512 513 514 515 516 517
    }

  /* Create and_map. It's padded out to 32 bits per line: */
  data->and_map = ico_alloc_map (entry->width, entry->height, 1, &and_len);
  data->and_len = and_len;

  for (y = 0; y < entry->height; y++)
    for (x = 0; x < entry->width; x++)
      {
518
        pixel = (guint8 *) &buffer32[y * entry->width + x];
519

520
        ico_set_bit_in_data (data->and_map, entry->width,
521 522 523 524 525 526 527 528 529 530 531 532
                             (entry->height-y-1) * entry->width + x,
                             (pixel[3] == 255 ? 0 : 1));
      }

  data->xor_map = ico_alloc_map(entry->width, entry->height, bpp, &xor_len);
  data->xor_len = xor_len;

  /* Now fill in the xor map */
  switch (bpp)
    {
    case 1:
      for (y = 0; y < entry->height; y++)
533 534 535 536
        for (x = 0; x < entry->width; x++)
          {
            pixel = (guint8 *) &buffer32[y * entry->width + x];
            palette_index = ico_get_palette_index (color_to_slot,
537 538
                                                   pixel[0], pixel[1], pixel[2]);

539
            if (ico_get_bit_from_data (data->and_map, entry->width,
540
                                       (entry->height-y-1) * entry->width + x))
541 542
              {
                ico_set_bit_in_data (data->xor_map, entry->width,
543 544
                                     (entry->height-y-1) * entry->width + x,
                                     black_index);
545 546 547 548
              }
            else
              {
                ico_set_bit_in_data (data->xor_map, entry->width,
549 550
                                     (entry->height-y-1) * entry->width + x,
                                     palette_index);
551 552
              }
          }
553 554 555 556
      break;

    case 4:
      for (y = 0; y < entry->height; y++)
557 558 559 560
        for (x = 0; x < entry->width; x++)
          {
            pixel = (guint8 *) &buffer32[y * entry->width + x];
            palette_index = ico_get_palette_index(color_to_slot,
561 562
                                                  pixel[0], pixel[1], pixel[2]);

563
            if (ico_get_bit_from_data (data->and_map, entry->width,
564
                                       (entry->height-y-1) * entry->width + x))
565 566
              {
                ico_set_nibble_in_data (data->xor_map, entry->width,
567 568
                                        (entry->height-y-1) * entry->width + x,
                                        black_index);
569 570 571 572
              }
            else
              {
                ico_set_nibble_in_data (data->xor_map, entry->width,
573 574
                                        (entry->height-y-1) * entry->width + x,
                                        palette_index);
575 576
              }
          }
577 578 579 580
      break;

    case 8:
      for (y = 0; y < entry->height; y++)
581 582 583 584
        for (x = 0; x < entry->width; x++)
          {
            pixel = (guint8 *) &buffer32[y * entry->width + x];
            palette_index = ico_get_palette_index (color_to_slot,
585 586 587
                                                   pixel[0],
                                                   pixel[1],
                                                   pixel[2]);
588

589
            if (ico_get_bit_from_data (data->and_map, entry->width,
590
                                       (entry->height-y-1) * entry->width + x))
591 592
              {
                ico_set_byte_in_data (data->xor_map, entry->width,
593 594
                                      (entry->height-y-1) * entry->width + x,
                                      black_index);
595 596 597 598
              }
            else
              {
                ico_set_byte_in_data (data->xor_map, entry->width,
599 600
                                      (entry->height-y-1) * entry->width + x,
                                      palette_index);
601
              }
602

603
          }
604 605 606 607
      break;

    default:
      for (y = 0; y < entry->height; y++)
608 609 610
        for (x = 0; x < entry->width; x++)
          {
            pixel = (guint8 *) &buffer32[y * entry->width + x];
611

612 613
            ((guint32 *) data->xor_map)[(entry->height-y-1) * entry->width + x] =
              GUINT32_TO_LE ((pixel[0] << 16) |
614 615 616
                             (pixel[1] << 8)  |
                             (pixel[2])       |
                             (pixel[3] << 24));
617
          }
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
    }

  D(("  filled and_map of length %i, xor_map of length %i\n",
     data->and_len, data->xor_len));

  if (color_to_slot)
    {
      g_hash_table_foreach (color_to_slot, ico_free_hash_item, NULL);
      g_hash_table_destroy (color_to_slot);
    }

  g_free(palette);
  g_free(buffer);
}


static void
ico_setup (MsIcon *ico,
           gint32  image,
           gint   *icon_depths,
           gint    num_icons)
{
  gint *layers;
  gint  i;
  gint  offset;

644
  layers = gimp_image_get_layers (image, &num_icons);
645 646 647 648 649

  /* Set up icon entries */
  for (i = 0; i < num_icons; i++)
    {
      ico_init_direntry (&ico->icon_dir[i], layers[i], icon_depths[i]);
650
      gimp_progress_update ((gdouble) i / (gdouble) num_icons * 0.3);
651 652 653 654 655 656 657 658
    }

  /* Set up data entries (the actual icons), and calculate each one's size */
  for (i = 0; i < num_icons; i++)
    {
      ico_init_data (ico, i, layers[i], icon_depths[i]);

      ico->icon_dir[i].size =
659 660 661 662
        ico->icon_data[i].header_size +
        ico->icon_data[i].palette_len +
        ico->icon_data[i].xor_len +
        ico->icon_data[i].and_len;
663

664
      gimp_progress_update (0.3 + (gdouble) i / (gdouble) num_icons * 0.3);
665 666 667 668 669 670 671 672 673 674
    }

  /* Finally, calculate offsets for each icon and store them in each entry */
  offset = 3 * sizeof (guint16) + ico->icon_count * sizeof (MsIconEntry);

  for (i = 0; i < num_icons; i++)
    {
      ico->icon_dir[i].offset = offset;
      offset += ico->icon_dir[i].size;

675
      gimp_progress_update (0.6 + (gdouble) i / (gdouble) num_icons * 0.3);
676 677
    }

678
  gimp_progress_update (1.0);
679

680
  g_free (layers);
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
}


static GimpPDBStatusType
ico_save (MsIcon *ico)
{
  MsIconEntry *entry;
  MsIconData *data;
  int i;

  ico->cp += ico_write_int16 (ico->fp, &ico->reserved, 3);

  for (i = 0; i < ico->icon_count; i++)
    {
      entry = &ico->icon_dir[i];

697
      ico->cp += ico_write_int8 (ico->fp, (guint8 *) entry, 4);
698 699 700 701 702 703 704 705
      ico->cp += ico_write_int16 (ico->fp, &entry->num_planes, 2);
      ico->cp += ico_write_int32 (ico->fp, &entry->size, 2);
    }

  for (i = 0; i < ico->icon_count; i++)
    {
      data  = &ico->icon_data[i];

706
      ico->cp += ico_write_int32 (ico->fp, (guint32 *) data, 3);
707 708 709 710
      ico->cp += ico_write_int16 (ico->fp, &data->planes, 2);
      ico->cp += ico_write_int32 (ico->fp, &data->compression, 6);

      if (data->palette)
711
        ico->cp += ico_write_int8 (ico->fp,
712
                                   (guint8 *) data->palette, data->palette_len);
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731

      ico->cp += ico_write_int8 (ico->fp, data->xor_map, data->xor_len);
      ico->cp += ico_write_int8 (ico->fp, data->and_map, data->and_len);
    }

  return GIMP_PDB_SUCCESS;
}

static gboolean
ico_layers_too_big (gint32 image)
{
  gint *layers;
  gint  i, num_layers;

  layers = gimp_image_get_layers (image, &num_layers);

  for (i = 0; i < num_layers; i++)
    {
      if ((gimp_drawable_width (layers[i])  > 255) ||
732 733 734 735 736
          (gimp_drawable_height (layers[i]) > 255))
        {
          g_free (layers);
          return TRUE;
        }
737 738 739 740 741 742
    }

  g_free (layers);
  return FALSE;
}

743 744 745 746 747
static gint
ico_get_layer_num_colors (gint32    layer,
                          gboolean *uses_alpha_levels)
{
  GimpPixelRgn    pixel_rgn;
748 749 750 751 752 753 754 755
  gint            w, h;
  gint            bpp;
  gint            num_colors = 0;
  guint           num_pixels;
  guchar         *buffer;
  guchar         *src;
  guint32        *colors;
  guint32        *c;
756 757 758 759 760
  GHashTable     *hash;
  GimpDrawable   *drawable = gimp_drawable_get (layer);

  w = gimp_drawable_width (layer);
  h = gimp_drawable_height (layer);
761 762 763 764 765 766

  num_pixels = w * h;

  bpp = gimp_drawable_bpp (layer);

  buffer = src = g_new (guchar, num_pixels * bpp);
767 768

  gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, w, h, FALSE, FALSE);
769
  gimp_pixel_rgn_get_rect (&pixel_rgn, buffer, 0, 0, w, h);
770 771 772 773 774 775

  gimp_drawable_detach (drawable);

  hash = g_hash_table_new (g_int_hash, g_int_equal);
  *uses_alpha_levels = FALSE;

776 777 778 779 780 781 782 783 784 785 786 787 788
  colors = c = g_new (guint32, num_pixels);

  switch (bpp)
    {
    case 1:
      while (num_pixels--)
        {
          *c = *src;
          g_hash_table_insert (hash, c, c);
          src++;
          c++;
        }
      break;
789

790 791 792 793 794 795 796 797 798 799 800
    case 2:
      while (num_pixels--)
        {
          *c = (src[1] << 8) | src[0];
          if (src[1] != 0 && src[1] != 255)
            *uses_alpha_levels = TRUE;
          g_hash_table_insert (hash, c, c);
          src += 2;
          c++;
        }
      break;
801

802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
    case 3:
      while (num_pixels--)
        {
          *c = (src[2] << 16) | (src[1] << 8) | src[0];
          g_hash_table_insert (hash, c, c);
          src += 3;
          c++;
        }
      break;

    case 4:
      while (num_pixels--)
        {
          *c = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
          if (src[3] != 0 && src[3] != 255)
            *uses_alpha_levels = TRUE;
          g_hash_table_insert (hash, c, c);
          src += 4;
          c++;
        }
      break;
    }
824 825 826 827 828

  num_colors = g_hash_table_size (hash);

  g_hash_table_destroy (hash);

829
  g_free (colors);
830 831 832 833 834 835 836 837 838 839 840 841 842
  g_free (buffer);

  return num_colors;
}

static gboolean
ico_cmap_contains_black (guchar *cmap,
                         gint    num_colors)
{
  gint i;

  for (i = 0; i < num_colors; i++)
    {
843 844 845
      if ((cmap[3 * i    ] == 0) &&
          (cmap[3 * i + 1] == 0) &&
          (cmap[3 * i + 2] == 0))
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
        {
          return TRUE;
        }
    }

  return FALSE;
}

static void
ico_image_get_reduced_buf (guint32   layer,
                           gint      bpp,
                           gint     *num_colors,
                           guchar  **cmap_out,
                           guchar  **buf_out)
{
  GimpPixelRgn    src_pixel_rgn, dst_pixel_rgn;
  gint32          tmp_image;
  gint32          tmp_layer;
  gint            w, h;
  guchar         *buffer;
Sven Neumann's avatar
Sven Neumann committed
866
  guchar         *cmap = NULL;
867 868 869 870
  GimpDrawable   *drawable = gimp_drawable_get (layer);

  w = gimp_drawable_width (layer);
  h = gimp_drawable_height (layer);
Sven Neumann's avatar
Sven Neumann committed
871

872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
  *num_colors = 0;

  buffer = g_new (guchar, w * h * 4);

  if (bpp <= 8 || drawable->bpp != 4)
    {
      gint32        image = gimp_drawable_get_image (layer);
      GimpDrawable *tmp;

      tmp_image = gimp_image_new (gimp_drawable_width (layer),
                                  gimp_drawable_height (layer),
                                  gimp_image_base_type (image));
      gimp_image_undo_disable (tmp_image);

      tmp_layer = gimp_layer_new (tmp_image, "tmp", w, h,
                                  gimp_drawable_type (layer),
                                  100, GIMP_NORMAL_MODE);
      gimp_image_add_layer (tmp_image, tmp_layer, 0);

      tmp = gimp_drawable_get (tmp_layer);

      gimp_pixel_rgn_init (&src_pixel_rgn, drawable, 0, 0, w, h, FALSE, FALSE);
      gimp_pixel_rgn_init (&dst_pixel_rgn, tmp,      0, 0, w, h, TRUE, FALSE);
      gimp_pixel_rgn_get_rect (&src_pixel_rgn, buffer, 0, 0, w, h);
      gimp_pixel_rgn_set_rect (&dst_pixel_rgn, buffer, 0, 0, w, h);
      gimp_drawable_detach (tmp);

      if (! gimp_drawable_is_rgb (tmp_layer))
        gimp_image_convert_rgb (tmp_image);

      if (bpp <= 8)
        {
          gimp_image_convert_indexed (tmp_image,
905 906
                                      GIMP_FS_DITHER, GIMP_MAKE_PALETTE,
                                      1 << bpp, TRUE, FALSE, "dummy");
907 908 909 910

          cmap = gimp_image_get_colormap (tmp_image, num_colors);

          if (*num_colors == (1 << bpp) &&
911
              !ico_cmap_contains_black (cmap, *num_colors))
912 913 914 915 916 917 918 919 920 921 922 923 924 925
            {
              /* Windows icons with color maps need the color black.
               * We need to eliminate one more color to make room for black.
               */

              gimp_image_convert_rgb (tmp_image);

              tmp = gimp_drawable_get (tmp_layer);
              gimp_pixel_rgn_init (&dst_pixel_rgn,
                                   tmp, 0, 0, w, h, TRUE, FALSE);
              gimp_pixel_rgn_set_rect (&dst_pixel_rgn, buffer, 0, 0, w, h);
              gimp_drawable_detach (tmp);

              gimp_image_convert_indexed (tmp_image,
926 927
                                          GIMP_FS_DITHER, GIMP_MAKE_PALETTE,
                                          (1 << bpp) - 1, TRUE, FALSE, "dummy");
Sven Neumann's avatar
Sven Neumann committed
928
              g_free (cmap);
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
              cmap = gimp_image_get_colormap (tmp_image, num_colors);
            }

          gimp_image_convert_rgb (tmp_image);
        }

      gimp_layer_add_alpha (tmp_layer);

      tmp = gimp_drawable_get (tmp_layer);
      gimp_pixel_rgn_init (&src_pixel_rgn, tmp, 0, 0, w, h, FALSE, FALSE);
      gimp_pixel_rgn_get_rect (&src_pixel_rgn, buffer, 0, 0, w, h);
      gimp_drawable_detach (tmp);

      gimp_image_delete (tmp_image);
    }
  else
    {
      gimp_pixel_rgn_init (&src_pixel_rgn, drawable, 0, 0, w, h, FALSE, FALSE);
      gimp_pixel_rgn_get_rect (&src_pixel_rgn, buffer, 0, 0, w, h);
    }

  gimp_drawable_detach (drawable);

Sven Neumann's avatar
Sven Neumann committed
952
  *cmap_out = cmap;
953 954 955
  *buf_out = buffer;
}

956 957 958 959
GimpPDBStatusType
SaveICO (const gchar *filename,
         gint32       image)
{
960 961 962 963
  MsIcon             ico;
  gint              *icon_depths = NULL;
  gint               num_icons;
  GimpPDBStatusType  exit_state;
964 965 966

  D(("*** Saving Microsoft icon file %s\n", filename));

967
  if (ico_layers_too_big (image))
968 969 970 971 972 973
    {
      g_message (_("Windows icons cannot be higher or wider than 255 pixels."));
      return GIMP_PDB_EXECUTION_ERROR;
    }

  /* First, set up the icon specs dialog and show it: */
974
  if ((icon_depths = ico_show_icon_dialog (image, &num_icons)) == NULL)
975 976
    return GIMP_PDB_CANCEL;

977
  gimp_progress_init_printf (_("Saving '%s'"),
978
                             gimp_filename_to_utf8 (filename));
979 980 981 982 983 984 985 986 987 988 989 990 991

  /* Okay, let's actually save the thing with the depths the
     user specified. */

  if ((exit_state = ico_init (filename, &ico, num_icons) != GIMP_PDB_SUCCESS))
    return exit_state;

  D(("icon initialized ...\n"));

  ico_setup (&ico, image, icon_depths, num_icons);

  D(("icon data created ...\n"));

992
  exit_state = ico_save(&ico);
993 994 995 996 997 998 999 1000

  D(("*** icon saved, exit status %i.\n\n", exit_state));

  ico_cleanup (&ico);
  g_free (icon_depths);

  return exit_state;
}