Skip to main content
summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to 'bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image')
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/FileFormat.java108
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/GIFFileFormat.java522
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGAppn.java24
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGArithmeticConditioningTable.java17
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGComment.java21
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGEndOfImage.java25
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGFileFormat.java1891
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGFixedSizeSegment.java38
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGFrameHeader.java203
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGHuffmanTable.java262
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGQuantizationTable.java159
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGRestartInterval.java25
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGScanHeader.java117
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGSegment.java54
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGStartOfImage.java29
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGVariableSizeSegment.java32
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LEDataInputStream.java88
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LEDataOutputStream.java54
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LZWCodec.java479
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LZWNode.java13
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PNGFileFormat.java525
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngChunk.java333
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngChunkReader.java64
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngDecodingDataStream.java131
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngFileReadState.java20
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngHuffmanTable.java122
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngHuffmanTables.java156
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngIdatChunk.java36
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngIendChunk.java39
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngIhdrChunk.java372
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngLzBlockReader.java169
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngPlteChunk.java87
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngTrnsChunk.java133
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/WinBMPFileFormat.java667
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/WinICOFileFormat.java284
-rwxr-xr-xbundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/package.html18
36 files changed, 7317 insertions, 0 deletions
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/FileFormat.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/FileFormat.java
new file mode 100755
index 0000000000..1bf2ae1d80
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/FileFormat.java
@@ -0,0 +1,108 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * WebSphere Studio Workbench
+ * (c) Copyright IBM Corp 2000
+ */
+
+/* Imports */
+import java.io.*;
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+
+/* Class Definition */
+public abstract class FileFormat {
+ LEDataInputStream inputStream;
+ LEDataOutputStream outputStream;
+ ImageLoader loader;
+byte[] bitInvertData(byte[] data, int startIndex, int endIndex) {
+ // Destructively bit invert data in the given byte array.
+ for (int i = startIndex; i < endIndex; i++) {
+ data[i] = (byte)(255 - data[i - startIndex]);
+ }
+ return data;
+}
+
+abstract ImageData[] loadFromByteStream();
+
+public ImageData[] loadFromStream(LEDataInputStream stream) {
+ try {
+ inputStream = stream;
+ return loadFromByteStream();
+ } catch (Exception e) {
+ SWT.error(SWT.ERROR_IO, e);
+ return null;
+ }
+}
+public static ImageData[] load(InputStream is, ImageLoader loader) {
+ FileFormat fileFormat = null;
+ LEDataInputStream stream = new LEDataInputStream(is);
+ if (GIFFileFormat.isGIFFile(stream)) {
+ fileFormat = new GIFFileFormat();
+ } else if (WinBMPFileFormat.isBMPFile(stream)) {
+ fileFormat = new WinBMPFileFormat();
+ } else if (WinICOFileFormat.isICOFile(stream)) {
+ fileFormat = new WinICOFileFormat();
+ } else if (JPEGFileFormat.isJPEGFile(stream)) {
+ fileFormat = new JPEGFileFormat();
+ } else if (PNGFileFormat.isPNGFile(stream)) {
+ fileFormat = new PNGFileFormat();
+ } else {
+ SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT);
+ }
+ fileFormat.loader = loader;
+ return fileFormat.loadFromStream(stream);
+}
+public static void save(OutputStream os, int format, ImageLoader loader) {
+ /* We do not currently support writing multi-image files,
+ * so we use the first image data in the loader's array. */
+ ImageData data = loader.data[0];
+ LEDataOutputStream stream = new LEDataOutputStream(os);
+ switch (format) {
+ case SWT.IMAGE_BMP:
+ WinBMPFileFormat f = new WinBMPFileFormat();
+ f.unloadIntoStream(data, stream);
+ break;
+ case SWT.IMAGE_BMP_RLE:
+ f = new WinBMPFileFormat();
+ if (data.depth == 8)
+ f.compression = 1;
+ if (data.depth == 4)
+ f.compression = 2;
+ f.unloadIntoStream(data, stream);
+ break;
+ case SWT.IMAGE_GIF:
+ GIFFileFormat g = new GIFFileFormat();
+ g.unloadIntoStream(data, stream);
+ break;
+ case SWT.IMAGE_ICO:
+ WinICOFileFormat i = new WinICOFileFormat();
+ i.unloadIntoStream(data, stream);
+ break;
+ case SWT.IMAGE_JPEG:
+ JPEGFileFormat j = new JPEGFileFormat();
+ j.unloadIntoStream(data, stream);
+ break;
+ case SWT.IMAGE_PNG:
+ PNGFileFormat p = new PNGFileFormat();
+ p.unloadIntoStream(data, stream);
+ break;
+ default:
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+}
+
+abstract void unloadIntoByteStream(ImageData image);
+
+public void unloadIntoStream(ImageData image, LEDataOutputStream stream) {
+ try {
+ outputStream = stream;
+ unloadIntoByteStream(image);
+ outputStream.close();
+ } catch (Exception e) {
+ try {outputStream.close();} catch (Exception f) {}
+ SWT.error(SWT.ERROR_IO, e);
+ }
+}
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/GIFFileFormat.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/GIFFileFormat.java
new file mode 100755
index 0000000000..5951beb747
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/GIFFileFormat.java
@@ -0,0 +1,522 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * WebSphere Studio Workbench
+ * (c) Copyright IBM Corp 2000
+ */
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+import java.io.*;
+
+final class GIFFileFormat extends FileFormat {
+ String signature, version;
+ boolean sorted;
+ int screenWidth, screenHeight, backgroundPixel, aspect, bitsPerPixel;
+ boolean userInput = false;
+ int disposalMethod = 0;
+ int delayTime = 0;
+ int transparentPixel = -1;
+ int repeatCount = 1;
+
+ static final int GIF_APPLICATION_EXTENSION_BLOCK_ID = 0xFF;
+ static final int GIF_GRAPHICS_CONTROL_BLOCK_ID = 0xF9;
+ static final int GIF_PLAIN_TEXT_BLOCK_ID = 0x01;
+ static final int GIF_COMMENT_BLOCK_ID = 0xFE;
+ static final int GIF_EXTENSION_BLOCK_ID = 0x21;
+ static final int GIF_IMAGE_BLOCK_ID = 0x2C;
+ static final int GIF_TRAILER_ID = 0x3B;
+
+ /**
+ * Return whether or not the specified input stream
+ * represents a GIF file.
+ */
+ public static boolean isGIFFile(LEDataInputStream stream) {
+ try {
+ byte[] signature = new byte[3];
+ stream.read(signature);
+ stream.unread(signature);
+ return new String(signature).equals("GIF");
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ /**
+ * Answer a palette containing numGrays
+ * shades of gray, ranging from black to white.
+ */
+ static PaletteData grayRamp(int numGrays) {
+ int n = numGrays - 1;
+ RGB[] colors = new RGB[numGrays];
+ for (int i = 0; i < numGrays; i++) {
+ int intensity = (byte)((i * 3) * 256 / n);
+ colors[i] = new RGB(intensity, intensity, intensity);
+ }
+ return new PaletteData(colors);
+ }
+
+ /**
+ * Load the GIF image(s) stored in the input stream.
+ * Return an array of ImageData representing the image(s).
+ */
+ ImageData[] loadFromByteStream() {
+ byte[] signatureBytes = new byte[3];
+ byte[] versionBytes = new byte[3];
+ byte[] block = new byte[7];
+ try {
+ inputStream.read(signatureBytes);
+ signature = new String(signatureBytes);
+ if (!signature.equals("GIF"))
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+
+ inputStream.read(versionBytes);
+ version = new String(versionBytes);
+
+ inputStream.read(block);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ screenWidth = (block[0] & 0xFF) | ((block[1] & 0xFF) << 8);
+ loader.logicalScreenWidth = screenWidth;
+ screenHeight = (block[2] & 0xFF) | ((block[3] & 0xFF) << 8);
+ loader.logicalScreenHeight = screenHeight;
+ byte bitField = block[4];
+ backgroundPixel = block[5] & 0xFF;
+ aspect = block[6] & 0xFF;
+ bitsPerPixel = ((bitField >> 4) & 0x07) + 1;
+ int depth = (bitField & 0x7) + 1;
+ PaletteData palette = null;
+ if ((bitField & 0x80) != 0) {
+ // Global palette.
+ sorted = (bitField & 0x8) != 0;
+ palette = readPalette(1 << depth);
+ } else {
+ // No global palette.
+ sorted = false;
+ backgroundPixel = -1;
+ depth = bitsPerPixel;
+ }
+ loader.backgroundPixel = backgroundPixel;
+
+ getExtensions();
+ int id = readID();
+ ImageData[] images = new ImageData[0];
+ while (id == GIF_IMAGE_BLOCK_ID) {
+ ImageData image = readImageBlock(depth, palette);
+ if (loader.hasListeners()) {
+ loader.notifyListeners(new ImageLoaderEvent(loader, image, 3, true));
+ }
+ ImageData[] oldImages = images;
+ images = new ImageData[oldImages.length + 1];
+ System.arraycopy(oldImages, 0, images, 0, oldImages.length);
+ images[images.length - 1] = image;
+ try {
+ /* Read the 0-byte terminator at the end of the image. */
+ id = inputStream.read();
+ if (id > 0) {
+ /* We read the terminator earlier. */
+ inputStream.unread(new byte[] {(byte)id});
+ }
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ getExtensions();
+ id = readID();
+ }
+ return images;
+ }
+
+ /**
+ * Read and return the next block or extension identifier from the file.
+ */
+ int readID() {
+ try {
+ return inputStream.read();
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ return -1;
+ }
+
+ /**
+ * Read extensions until an image descriptor appears.
+ * In the future, if we care about the extensions, they
+ * should be properly grouped with the image data before
+ * which they appeared. Right now, the interesting parts
+ * of some extensions are kept, but the rest is discarded.
+ * Throw an error if an error occurs.
+ */
+ void getExtensions() {
+ int id = readID();
+ while (id != GIF_IMAGE_BLOCK_ID && id != GIF_TRAILER_ID && id > 0) {
+ if (id == GIF_EXTENSION_BLOCK_ID) {
+ readExtension();
+ } else {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ id = readID();
+ }
+ if (id == GIF_IMAGE_BLOCK_ID) {
+ try {
+ inputStream.unread(new byte[] {(byte)id});
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ }
+ }
+
+ /**
+ * Read a control extension.
+ * Return the extension block data.
+ */
+ byte[] readExtension() {
+ int extensionID = readID();
+ if (extensionID == GIF_COMMENT_BLOCK_ID)
+ return readCommentExtension();
+ if (extensionID == GIF_PLAIN_TEXT_BLOCK_ID)
+ return readPlainTextExtension();
+ if (extensionID == GIF_GRAPHICS_CONTROL_BLOCK_ID)
+ return readGraphicsControlExtension();
+ if (extensionID == GIF_APPLICATION_EXTENSION_BLOCK_ID)
+ return readApplicationExtension();
+ // Otherwise, we don't recognize the block. If the
+ // field size is correct, we can just skip over
+ // the block contents.
+ try {
+ int extSize = inputStream.read();
+ if (extSize < 0) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ byte[] ext = new byte[extSize];
+ inputStream.read(ext, 0, extSize);
+ return ext;
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ return null;
+ }
+ }
+
+ /**
+ * We have just read the Comment extension identifier
+ * from the input stream. Read in the rest of the comment
+ * and return it. GIF comment blocks are variable size.
+ */
+ byte[] readCommentExtension() {
+ try {
+ byte[] comment = new byte[0];
+ byte[] block = new byte[255];
+ int size = inputStream.read();
+ while ((size > 0) && (inputStream.read(block, 0, size) != -1)) {
+ byte[] oldComment = comment;
+ comment = new byte[oldComment.length + size];
+ System.arraycopy(oldComment, 0, comment, 0, oldComment.length);
+ System.arraycopy(block, 0, comment, oldComment.length, size);
+ size = inputStream.read();
+ }
+ return comment;
+ } catch (Exception e) {
+ SWT.error(SWT.ERROR_IO, e);
+ return null;
+ }
+ }
+
+ /**
+ * We have just read the PlainText extension identifier
+ * from the input stream. Read in the plain text info and text,
+ * and return the text. GIF plain text blocks are variable size.
+ */
+ byte[] readPlainTextExtension() {
+ try {
+ // Read size of block = 0x0C.
+ inputStream.read();
+ // Read the text information (x, y, width, height, colors).
+ byte[] info = new byte[12];
+ inputStream.read(info);
+ // Read the text.
+ byte[] text = new byte[0];
+ byte[] block = new byte[255];
+ int size = inputStream.read();
+ while ((size > 0) && (inputStream.read(block, 0, size) != -1)) {
+ byte[] oldText = text;
+ text = new byte[oldText.length + size];
+ System.arraycopy(oldText, 0, text, 0, oldText.length);
+ System.arraycopy(block, 0, text, oldText.length, size);
+ size = inputStream.read();
+ }
+ return text;
+ } catch (Exception e) {
+ SWT.error(SWT.ERROR_IO, e);
+ return null;
+ }
+ }
+
+ /**
+ * We have just read the GraphicsControl extension identifier
+ * from the input stream. Read in the control information, store
+ * it, and return it.
+ */
+ byte[] readGraphicsControlExtension() {
+ try {
+ // Read size of block = 0x04.
+ inputStream.read();
+ // Read the control block.
+ byte[] controlBlock = new byte[4];
+ inputStream.read(controlBlock);
+ byte bitField = controlBlock[0];
+ // Store the user input field.
+ userInput = (bitField & 0x02) != 0;
+ // Store the disposal method.
+ disposalMethod = (bitField >> 2) & 0x07;
+ // Store the delay time.
+ delayTime = (controlBlock[1] & 0xFF) | ((controlBlock[2] & 0xFF) << 8);
+ // Store the transparent color.
+ if ((bitField & 0x01) != 0)
+ transparentPixel = controlBlock[3] & 0xFF;
+ else
+ transparentPixel = -1;
+ // Read block terminator.
+ inputStream.read();
+ return controlBlock;
+ } catch (Exception e) {
+ SWT.error(SWT.ERROR_IO, e);
+ return null;
+ }
+ }
+
+ /**
+ * We have just read the Application extension identifier
+ * from the input stream. Read in the rest of the extension,
+ * look for and store 'number of repeats', and return the data.
+ */
+ byte[] readApplicationExtension() {
+ try {
+ // Read size of block = 0x0B.
+ inputStream.read();
+ // Read application identifier.
+ byte[] applicationBytes = new byte[8];
+ inputStream.read(applicationBytes);
+ String application = new String(applicationBytes);
+ // Read authentication code.
+ byte[] authenticationBytes = new byte[3];
+ inputStream.read(authenticationBytes);
+ String authentication = new String(authenticationBytes);
+ // Read application data.
+ byte[] data = new byte[0];
+ byte[] block = new byte[255];
+ int size = inputStream.read();
+ while ((size > 0) && (inputStream.read(block, 0, size) != -1)) {
+ byte[] oldData = data;
+ data = new byte[oldData.length + size];
+ System.arraycopy(oldData, 0, data, 0, oldData.length);
+ System.arraycopy(block, 0, data, oldData.length, size);
+ size = inputStream.read();
+ }
+ // Look for the NETSCAPE 'repeat count' field for an animated GIF.
+ if (application.equals("NETSCAPE") && authentication.equals("2.0") && data[0] == 01) {
+ repeatCount = (data[1] & 0xFF) | ((data[2] & 0xFF) << 8);
+ loader.repeatCount = repeatCount;
+ }
+ return data;
+ } catch (Exception e) {
+ SWT.error(SWT.ERROR_IO, e);
+ return null;
+ }
+ }
+
+ /**
+ * Return a DeviceIndependentImage representing the
+ * image block at the current position in the input stream.
+ * Throw an error if an error occurs.
+ */
+ ImageData readImageBlock(int defaultDepth, PaletteData defaultPalette) {
+ int depth;
+ PaletteData palette;
+ byte[] block = new byte[9];
+ try {
+ inputStream.read(block);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ int left = (block[0] & 0xFF) | ((block[1] & 0xFF) << 8);
+ int top = (block[2] & 0xFF) | ((block[3] & 0xFF) << 8);
+ int width = (block[4] & 0xFF) | ((block[5] & 0xFF) << 8);
+ int height = (block[6] & 0xFF) | ((block[7] & 0xFF) << 8);
+ byte bitField = block[8];
+ boolean interlaced = (bitField & 0x40) != 0;
+ boolean sorted = (bitField & 0x20) != 0;
+ if ((bitField & 0x80) != 0) {
+ // Local palette.
+ depth = (bitField & 0x7) + 1;
+ palette = readPalette(1 << depth);
+ } else {
+ // No local palette.
+ depth = defaultDepth;
+ palette = defaultPalette;
+ }
+ // Promote depth to next highest supported value.
+ if (!(depth == 1 || depth == 4 || depth == 8)) {
+ if (depth < 4)
+ depth = 4;
+ else
+ depth = 8;
+ }
+ if (palette == null) {
+ palette = grayRamp(1 << depth);
+ }
+ int initialCodeSize = -1;
+ try {
+ initialCodeSize = inputStream.read();
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ if (initialCodeSize < 0) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ ImageData image = ImageData.internal_new(
+ width,
+ height,
+ depth,
+ palette,
+ 4,
+ null,
+ 0,
+ null,
+ null,
+ -1,
+ transparentPixel,
+ SWT.IMAGE_GIF,
+ left,
+ top,
+ disposalMethod,
+ delayTime);
+ LZWCodec codec = new LZWCodec();
+ codec.decode(inputStream, loader, image, interlaced, initialCodeSize);
+ return image;
+ }
+
+ /**
+ * Read a palette from the input stream.
+ */
+ PaletteData readPalette(int numColors) {
+ byte[] bytes = new byte[numColors * 3];
+ try {
+ if (inputStream.read(bytes) != bytes.length)
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ RGB[] colors = new RGB[numColors];
+ for (int i = 0; i < numColors; i++)
+ colors[i] = new RGB(bytes[i*3] & 0xFF,
+ bytes[i*3+1] & 0xFF, bytes[i*3+2] & 0xFF);
+ return new PaletteData(colors);
+ }
+
+ /**
+ * Write the specified device independent image
+ * to the output stream.
+ */
+ void unloadIntoByteStream(ImageData image) {
+ if (!((image.depth == 1) || (image.depth == 4) || (image.depth == 8))) {
+ SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH);
+ }
+ byte bitField = (byte)((0x80 & 0xF8 & 0xF7 & 0x8F) + (image.depth - 1) + ((image.depth - 1) * 16));
+ try {
+ outputStream.write(new byte[] { (byte)'G', (byte)'I', (byte)'F' });
+ outputStream.write(new byte[] { (byte)'8', (byte)'9', (byte)'a' });
+ outputStream.writeShort((short)image.width);
+ outputStream.writeShort((short)image.height);
+ outputStream.writeByte(bitField);
+ outputStream.writeByte((byte)0);
+ outputStream.writeByte((byte)0);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ writePalette(image.palette, image.depth);
+ if (image.transparentPixel != -1 || image.disposalMethod != 0 || image.delayTime != 0) {
+ writeGraphicsControlBlock(image);
+ }
+ writeImageBlock(image);
+ }
+
+ /**
+ * Write out a GraphicsControlBlock to describe
+ * the specified device independent image.
+ */
+ void writeGraphicsControlBlock(ImageData image) {
+ try {
+ outputStream.write(GIF_EXTENSION_BLOCK_ID);
+ outputStream.write(GIF_GRAPHICS_CONTROL_BLOCK_ID);
+ outputStream.write(0x04); // size of block
+ byte[] gcBlock = new byte[4];
+ gcBlock[0] = (byte)0xFD;
+ gcBlock[1] = 0;
+ gcBlock[2] = 0;
+ gcBlock[3] = 0;
+ if (image.transparentPixel == -1) {
+ gcBlock[0] = (byte)(gcBlock[0] & 0xFE);
+ } else {
+ gcBlock[0] = (byte)(gcBlock[0] | 0x01);
+ gcBlock[3] = (byte)image.transparentPixel;
+ }
+ if (image.disposalMethod != 0) {
+ gcBlock[0] = (byte)(gcBlock[0] | ((image.disposalMethod & 0x07) << 2));
+ }
+ if (image.delayTime != 0) {
+ gcBlock[1] = (byte)(image.delayTime & 0xFF);
+ gcBlock[2] = (byte)((image.delayTime >> 8) & 0xFF);
+ }
+ outputStream.write(gcBlock);
+ outputStream.write(0); // block terminator
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ }
+
+ /**
+ * Write the specified device independent image
+ * to the current position in the output stream.
+ */
+ void writeImageBlock(ImageData image) {
+ try {
+ outputStream.write(GIF_IMAGE_BLOCK_ID);
+ byte[] block = new byte[9];
+ block[0] = (byte)(image.x & 0xFF);
+ block[1] = (byte)((image.x >> 8) & 0xFF);
+ block[2] = (byte)(image.y & 0xFF);
+ block[3] = (byte)((image.y >> 8) & 0xFF);
+ block[4] = (byte)(image.width & 0xFF);
+ block[5] = (byte)((image.width >> 8) & 0xFF);
+ block[6] = (byte)(image.height & 0xFF);
+ block[7] = (byte)((image.height >> 8) & 0xFF);
+ block[8] = 0; // no interlace, no sort, no local palette
+ outputStream.write(block);
+ outputStream.write(image.depth);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ new LZWCodec().encode(outputStream, image);
+ }
+
+ /**
+ * Write the specified palette to the output stream.
+ */
+ void writePalette(PaletteData palette, int depth) {
+ byte[] bytes = new byte[(1 << depth) * 3];
+ int offset = 0;
+ for (int i = 0; i < palette.colors.length; i++) {
+ RGB color = palette.colors[i];
+ bytes[offset] = (byte)color.red;
+ bytes[offset + 1] = (byte)color.green;
+ bytes[offset + 2] = (byte)color.blue;
+ offset += 3;;
+ }
+ try {
+ outputStream.write(bytes);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ }
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGAppn.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGAppn.java
new file mode 100755
index 0000000000..f211bfd3ca
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGAppn.java
@@ -0,0 +1,24 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+import org.eclipse.swt.*;
+
+final class JPEGAppn extends JPEGVariableSizeSegment {
+
+ public JPEGAppn(byte[] reference) {
+ super(reference);
+ }
+
+ public JPEGAppn(LEDataInputStream byteStream) {
+ super(byteStream);
+ }
+
+ public boolean verify() {
+ int marker = getSegmentMarker();
+ return marker >= JPEGFileFormat.APP0 && marker <= JPEGFileFormat.APP15;
+ }
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGArithmeticConditioningTable.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGArithmeticConditioningTable.java
new file mode 100755
index 0000000000..689ba2c5a8
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGArithmeticConditioningTable.java
@@ -0,0 +1,17 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+final class JPEGArithmeticConditioningTable extends JPEGVariableSizeSegment {
+
+ public JPEGArithmeticConditioningTable(LEDataInputStream byteStream) {
+ super(byteStream);
+ }
+
+ public int signature() {
+ return JPEGFileFormat.DAC;
+ }
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGComment.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGComment.java
new file mode 100755
index 0000000000..7c2e186df0
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGComment.java
@@ -0,0 +1,21 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+final class JPEGComment extends JPEGVariableSizeSegment {
+
+ public JPEGComment(byte[] reference) {
+ super(reference);
+ }
+
+ public JPEGComment(LEDataInputStream byteStream) {
+ super(byteStream);
+ }
+
+ public int signature() {
+ return JPEGFileFormat.COM;
+ }
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGEndOfImage.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGEndOfImage.java
new file mode 100755
index 0000000000..2937a7cbe2
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGEndOfImage.java
@@ -0,0 +1,25 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+final class JPEGEndOfImage extends JPEGFixedSizeSegment {
+
+ public JPEGEndOfImage() {
+ super();
+ }
+
+ public JPEGEndOfImage(byte[] reference) {
+ super(reference);
+ }
+
+ public int signature() {
+ return JPEGFileFormat.EOI;
+ }
+
+ public int fixedSize() {
+ return 2;
+ }
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGFileFormat.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGFileFormat.java
new file mode 100755
index 0000000000..6650760172
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGFileFormat.java
@@ -0,0 +1,1891 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * WebSphere Studio Workbench
+ * (c) Copyright IBM Corp 2000
+ */
+
+/* Imports */
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+import java.io.*;
+
+/* Class Definition */
+final class JPEGFileFormat extends FileFormat {
+ int restartInterval;
+ JPEGFrameHeader frameHeader;
+ int imageWidth, imageHeight;
+ int interleavedMcuCols, interleavedMcuRows;
+ int maxV, maxH;
+ boolean progressive;
+ int samplePrecision;
+ int nComponents;
+ int[][] frameComponents;
+ byte[][] imageComponents;
+ int[] dataUnit;
+ int[][][] dataUnits;
+ int[] precedingDCs;
+ JPEGScanHeader scanHeader;
+ byte[] dataBuffer;
+ int currentBitCount;
+ int bufferCurrentPosition;
+ int restartsToGo;
+ int nextRestartNumber;
+ JPEGArithmeticConditioningTable arithmeticTables;
+ JPEGHuffmanTable[] acHuffmanTables;
+ JPEGHuffmanTable[] dcHuffmanTables;
+ int[][] quantizationTables;
+ int currentByte;
+ int decoderQFactor;
+ int encoderQFactor = 75;
+ int eobrun = 0;
+ /* JPEGConstants */
+ public static final int DCTSIZE = 8;
+ public static final int DCTSIZESQR = 64;
+ /* JPEGFixedPointConstants */
+ public static final int FIX_0_899976223 = 7373;
+ public static final int FIX_1_961570560 = 16069;
+ public static final int FIX_2_053119869 = 16819;
+ public static final int FIX_0_298631336 = 2446;
+ public static final int FIX_1_847759065 = 15137;
+ public static final int FIX_1_175875602 = 9633;
+ public static final int FIX_3_072711026 = 25172;
+ public static final int FIX_0_765366865 = 6270;
+ public static final int FIX_2_562915447 = 20995;
+ public static final int FIX_0_541196100 = 4433;
+ public static final int FIX_0_390180644 = 3196;
+ public static final int FIX_1_501321110 = 12299;
+ /* JPEGMarkerCodes */
+ public static final int APP0 = 0xFFE0;
+ public static final int APP15 = 0xFFEF;
+ public static final int COM = 0xFFFE;
+ public static final int DAC = 0xFFCC;
+ public static final int DHP = 0xFFDE;
+ public static final int DHT = 0xFFC4;
+ public static final int DNL = 0xFFDC;
+ public static final int DRI = 0xFFDD;
+ public static final int DQT = 0xFFDB;
+ public static final int EOI = 0xFFD9;
+ public static final int EXP = 0xFFDF;
+ public static final int JPG = 0xFFC8;
+ public static final int JPG0 = 0xFFF0;
+ public static final int JPG13 = 0xFFFD;
+ public static final int RST0 = 0xFFD0;
+ public static final int RST1 = 0xFFD1;
+ public static final int RST2 = 0xFFD2;
+ public static final int RST3 = 0xFFD3;
+ public static final int RST4 = 0xFFD4;
+ public static final int RST5 = 0xFFD5;
+ public static final int RST6 = 0xFFD6;
+ public static final int RST7 = 0xFFD7;
+ public static final int SOF0 = 0xFFC0;
+ public static final int SOF1 = 0xFFC1;
+ public static final int SOF2 = 0xFFC2;
+ public static final int SOF3 = 0xFFC3;
+ public static final int SOF5 = 0xFFC5;
+ public static final int SOF6 = 0xFFC6;
+ public static final int SOF7 = 0xFFC7;
+ public static final int SOF9 = 0xFFC9;
+ public static final int SOF10 = 0xFFCA;
+ public static final int SOF11 = 0xFFCB;
+ public static final int SOF13 = 0xFFCD;
+ public static final int SOF14 = 0xFFCE;
+ public static final int SOF15 = 0xFFCF;
+ public static final int SOI = 0xFFD8;
+ public static final int SOS = 0xFFDA;
+ public static final int TEM = 0xFF01;
+ /* JPEGFrameComponentParameterConstants */
+ public static final int TQI = 0;
+ public static final int HI = 1;
+ public static final int VI = 2;
+ public static final int CW = 3;
+ public static final int CH = 4;
+ /* JPEGScanComponentParameterConstants */
+ public static final int DC = 0;
+ public static final int AC = 1;
+
+ public static final int[] ExtendTest = {
+ 0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048,
+ 4096, 8192, 16384, 32768, 65536, 131072, 262144
+ };
+ public static final int[] ExtendOffset = new int[] {
+ 0, -1, -3, -7, -15, -31, -63, -127, -255, -511, -1023, -2047,
+ -4095, -8191, -16383, -32767, -65535, -131071, -262143
+ };
+ public static final int[] ZigZag8x8 = {
+ 0, 1, 8, 16, 9, 2, 3, 10,
+ 17, 24, 32, 25, 18, 11, 4, 5,
+ 12, 19, 26, 33, 40, 48, 41, 34,
+ 27, 20, 13, 6, 7, 14, 21, 28,
+ 35, 42, 49, 56, 57, 50, 43, 36,
+ 29, 22, 15, 23, 30, 37, 44, 51,
+ 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63
+ };
+ public static int[] CrRTable, CbBTable, CrGTable, CbGTable;
+ public static int[] RYTable, GYTable, BYTable,
+ RCbTable, GCbTable, BCbTable, RCrTable, GCrTable, BCrTable, NBitsTable;
+ static {
+ initialize();
+ }
+void compress(ImageData image, byte[] dataYComp, byte[] dataCbComp, byte[] dataCrComp) {
+ int srcWidth = image.width;
+ int srcHeight = image.height;
+ int vhFactor = maxV * maxH;
+ int[] frameComponent;
+ byte[][] imageComponents = new byte[nComponents][];
+ for (int i = 0; i < nComponents; i++) {
+ frameComponent = frameComponents[i];
+ imageComponents[i] = new byte[frameComponent[CW] * frameComponent[CH]];
+ }
+ frameComponent = frameComponents[0];
+ for (int yPos = 0; yPos < srcHeight; yPos++) {
+ int srcOfs = yPos * srcWidth;
+ int dstOfs = yPos * frameComponent[CW];
+ System.arraycopy(dataYComp, srcOfs, imageComponents[0], dstOfs, srcWidth);
+ }
+ frameComponent = frameComponents[1];
+ for (int yPos = 0; yPos < srcHeight / maxV; yPos++) {
+ int destRowIndex = yPos * frameComponent[CW];
+ for (int xPos = 0; xPos < srcWidth / maxH; xPos++) {
+ int sum = 0;
+ for (int iv = 0; iv < maxV; iv++) {
+ int srcIndex = (yPos * maxV + iv) * srcWidth + (xPos * maxH);
+ for (int ih = 0; ih < maxH; ih++) {
+ sum += dataCbComp[srcIndex + ih] & 0xFF;
+ }
+ }
+ imageComponents[1][destRowIndex + xPos] = (byte)(sum / vhFactor);
+ }
+ }
+ frameComponent = frameComponents[2];
+ for (int yPos = 0; yPos < srcHeight / maxV; yPos++) {
+ int destRowIndex = yPos * frameComponent[CW];
+ for (int xPos = 0; xPos < srcWidth / maxH; xPos++) {
+ int sum = 0;
+ for (int iv = 0; iv < maxV; iv++) {
+ int srcIndex = (yPos * maxV + iv) * srcWidth + (xPos * maxH);
+ for (int ih = 0; ih < maxH; ih++) {
+ sum += dataCrComp[srcIndex + ih] & 0xFF;
+ }
+ }
+ imageComponents[2][destRowIndex + xPos] = (byte)(sum / vhFactor);
+ }
+ }
+ for (int iComp = 0; iComp < nComponents; iComp++) {
+ byte[] imageComponent = imageComponents[iComp];
+ frameComponent = frameComponents[iComp];
+ int hFactor = frameComponent[HI];
+ int vFactor = frameComponent[VI];
+ int componentWidth = frameComponent[CW];
+ int componentHeight = frameComponent[CH];
+ int compressedWidth = srcWidth / (maxH / hFactor);
+ int compressedHeight = srcHeight / (maxV / vFactor);
+ if (compressedWidth < componentWidth) {
+ int delta = componentWidth - compressedWidth;
+ for (int yPos = 0; yPos < compressedHeight; yPos++) {
+ int dstOfs = ((yPos + 1) * componentWidth - delta);
+ int dataValue = imageComponent[dstOfs - 1] & 0xFF;
+ for (int i = 0; i < delta; i++) {
+ imageComponent[dstOfs + i] = (byte)dataValue;
+ }
+ }
+ }
+ if (compressedHeight < componentHeight) {
+ int srcOfs = (compressedHeight - 1) * componentWidth;
+ for (int yPos = compressedHeight; yPos <= componentHeight; yPos++) {
+ int dstOfs = (yPos - 1) * componentWidth;
+ System.arraycopy(imageComponent, srcOfs, imageComponent, dstOfs, componentWidth);
+ }
+ }
+ }
+}
+void convert4BitRGBToYCbCr(ImageData image) {
+ RGB[] rgbs = image.getRGBs();
+ int paletteSize = rgbs.length;
+ byte[] yComp = new byte[paletteSize];
+ byte[] cbComp = new byte[paletteSize];
+ byte[] crComp = new byte[paletteSize];
+ int srcWidth = image.width;
+ int srcHeight = image.height;
+ for (int i = 0; i < paletteSize; i++) {
+ RGB color = rgbs[i];
+ int r = color.red;
+ int g = color.green;
+ int b = color.blue;
+ int n = RYTable[r] + GYTable[g] + BYTable[b];
+ yComp[i] = (byte)(n / 65536);
+ if ((n < 0) && (n % 65536 != 0)) yComp[i]--;
+ n = RCbTable[r] + GCbTable[g] + BCbTable[b];
+ cbComp[i] = (byte)(n / 65536);
+ if ((n < 0) && (n % 65536 != 0)) cbComp[i]--;
+ n = RCrTable[r] + GCrTable[g] + BCrTable[b];
+ crComp[i] = (byte)(n / 65536);
+ if ((n < 0) && (n % 65536 != 0)) crComp[i]--;
+ }
+ int bSize = srcWidth * srcHeight;
+ byte[] dataYComp = new byte[bSize];
+ byte[] dataCbComp = new byte[bSize];
+ byte[] dataCrComp = new byte[bSize];
+ byte[] origData = image.data;
+ for (int yPos = 0; yPos < srcHeight; yPos++) {
+ for (int xPos = 0; xPos < srcWidth / 2; xPos++) {
+ int srcIndex = yPos * (srcWidth / 2) + xPos;
+ int dstIndex = yPos * srcWidth + (xPos * 2);
+ int value2 = origData[srcIndex] & 0xFF;
+ int value1 = value2 / 16;
+ value2 = value2 % 16;
+ dataYComp[dstIndex] = yComp[value1];
+ dataCbComp[dstIndex] = cbComp[value1];
+ dataCrComp[dstIndex] = crComp[value1];
+ dataYComp[dstIndex + 1] = yComp[value2];
+ dataCbComp[dstIndex + 1] = cbComp[value2];
+ dataCrComp[dstIndex + 1] = crComp[value2];
+ }
+ }
+ compress(image, dataYComp, dataCbComp, dataCrComp);
+}
+void convert8BitRGBToYCbCr(ImageData image) {
+ RGB[] rgbs = image.getRGBs();
+ int paletteSize = rgbs.length;
+ byte[] yComp = new byte[paletteSize];
+ byte[] cbComp = new byte[paletteSize];
+ byte[] crComp = new byte[paletteSize];
+ int srcWidth = image.width;
+ int srcHeight = image.height;
+ for (int i = 0; i < paletteSize; i++) {
+ RGB color = rgbs[i];
+ int r = color.red;
+ int g = color.green;
+ int b = color.blue;
+ int n = RYTable[r] + GYTable[g] + BYTable[b];
+ yComp[i] = (byte)(n / 65536);
+ if ((n < 0) && (n % 65536 != 0)) yComp[i]--;
+ n = RCbTable[r] + GCbTable[g] + BCbTable[b];
+ cbComp[i] = (byte)(n / 65536);
+ if ((n < 0) && (n % 65536 != 0)) cbComp[i]--;
+ n = RCrTable[r] + GCrTable[g] + BCrTable[b];
+ crComp[i] = (byte)(n / 65536);
+ if ((n < 0) && (n % 65536 != 0)) crComp[i]--;
+ }
+ int dstWidth = image.width;
+ int dstHeight = srcHeight;
+ int stride = (srcWidth + 3) / 4 * 4;
+ int bSize = dstWidth * dstHeight;
+ byte[] dataYComp = new byte[bSize];
+ byte[] dataCbComp = new byte[bSize];
+ byte[] dataCrComp = new byte[bSize];
+ byte[] origData = image.data;
+ for (int yPos = 0; yPos < srcHeight; yPos++) {
+ int srcRowIndex = yPos * stride;
+ int dstRowIndex = yPos * dstWidth;
+ for (int xPos = 0; xPos < srcWidth; xPos++) {
+ int value = origData[srcRowIndex + xPos] & 0xFF;
+ int dstIndex = dstRowIndex + xPos;
+ dataYComp[dstIndex] = yComp[value];
+ dataCbComp[dstIndex] = cbComp[value];
+ dataCrComp[dstIndex] = crComp[value];
+ }
+ }
+ compress(image, dataYComp, dataCbComp, dataCrComp);
+}
+byte[] convertCMYKToRGB() {
+ /* Unsupported CMYK format. Answer an empty byte array. */
+ return new byte[0];
+}
+void convertImageToYCbCr(ImageData image) {
+ switch (image.depth) {
+ case 4:
+ convert4BitRGBToYCbCr(image);
+ return;
+ case 8:
+ convert8BitRGBToYCbCr(image);
+ return;
+ case 16:
+ case 24:
+ convertMultiRGBToYCbCr(image);
+ return;
+ default:
+ SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH);
+ }
+ return;
+}
+void convertMultiRGBToYCbCr(ImageData image) {
+ int srcWidth = image.width;
+ int srcHeight = image.height;
+ int bSize = srcWidth * srcHeight;
+ byte[] dataYComp = new byte[bSize];
+ byte[] dataCbComp = new byte[bSize];
+ byte[] dataCrComp = new byte[bSize];
+ byte[] origData = image.data;
+ PaletteData palette = image.palette;
+ int[] buffer = new int[srcWidth];
+ if (palette.isDirect) {
+ int redMask = palette.redMask;
+ int greenMask = palette.greenMask;
+ int blueMask = palette.blueMask;
+ int redShift = palette.redShift;
+ int greenShift = palette.greenShift;
+ int blueShift = palette.blueShift;
+ for (int yPos = 0; yPos < srcHeight; yPos++) {
+ image.getPixels(0, yPos, srcWidth, buffer, 0);
+ int dstRowIndex = yPos * srcWidth;
+ for (int xPos = 0; xPos < srcWidth; xPos++) {
+ int pixel = buffer[xPos];
+ int dstDataIndex = dstRowIndex + xPos;
+ int r = pixel & redMask;
+ r = (redShift < 0) ? r >> -redShift : r << redShift;
+ int g = pixel & greenMask;
+ g = (greenShift < 0) ? g >> -greenShift : g << greenShift;
+ int b = pixel & blueMask;
+ b = (blueShift < 0) ? b >> -blueShift : b << blueShift;
+ dataYComp[dstDataIndex] = (byte)((RYTable[r] + GYTable[g] + BYTable[b]) / 65536);
+ dataCbComp[dstDataIndex] = (byte)((RCbTable[r] + GCbTable[g] + BCbTable[b]) / 65536);
+ dataCrComp[dstDataIndex] = (byte)((RCrTable[r] + GCrTable[g] + BCrTable[b]) / 65536);
+ }
+ }
+ } else {
+ for (int yPos = 0; yPos < srcHeight; yPos++) {
+ image.getPixels(0, yPos, srcWidth, buffer, 0);
+ int dstRowIndex = yPos * srcWidth;
+ for (int xPos = 0; xPos < srcWidth; xPos++) {
+ int pixel = buffer[xPos];
+ int dstDataIndex = dstRowIndex + xPos;
+ RGB rgb = palette.getRGB(pixel);
+ int r = rgb.red;
+ int g = rgb.green;
+ int b = rgb.blue;
+ dataYComp[dstDataIndex] = (byte)((RYTable[r] + GYTable[g] + BYTable[b]) / 65536);
+ dataCbComp[dstDataIndex] = (byte)((RCbTable[r] + GCbTable[g] + BCbTable[b]) / 65536);
+ dataCrComp[dstDataIndex] = (byte)((RCrTable[r] + GCrTable[g] + BCrTable[b]) / 65536);
+ }
+ }
+ }
+ compress(image, dataYComp, dataCbComp, dataCrComp);
+}
+byte[] convertYToRGB() {
+ int compWidth = frameHeader.componentParameters[0][3];
+ int bytesPerLine = (((imageWidth * 8 + 7) / 8) + 3) / 4 * 4;
+ byte[] data = new byte[bytesPerLine * imageHeight];
+ byte[] yComp = imageComponents[0];
+ int destIndex = 0;
+ for (int i = 0; i < imageHeight; i++) {
+ int srcIndex = i * compWidth;
+ for (int j = 0; j < bytesPerLine; j++) {
+ int y = yComp[srcIndex] & 0xFF;
+ if (y < 0) {
+ y = 0;
+ } else {
+ if (y > 255) y = 255;
+ }
+ if (j >= imageWidth) {
+ y = 0;
+ }
+ data[destIndex] = (byte)y;
+ srcIndex++;
+ destIndex++;
+ }
+ }
+ return data;
+}
+byte[] convertYCbCrToRGB() {
+ /**
+ * Convert existing image components into an RGB format.
+ * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
+ * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
+ * The conversion equations to be implemented are therefore
+ * R = Y + 1.40200 * Cr
+ * G = Y - 0.34414 * Cb - 0.71414 * Cr
+ * B = Y + 1.77200 * Cb
+ * where Cb and Cr represent the incoming values less MAXJSAMPLE/2.
+ * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
+ *
+ * To avoid floating-point arithmetic, we represent the fractional constants
+ * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
+ * the products by 2^16, with appropriate rounding, to get the correct answer.
+ * Notice that Y, being an integral input, does not contribute any fraction
+ * so it need not participate in the rounding.
+ *
+ * For even more speed, we avoid doing any multiplications in the inner loop
+ * by precalculating the constants times Cb and Cr for all possible values.
+ * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
+ * for 12-bit samples it is still acceptable. It's not very reasonable for
+ * 16-bit samples, but if you want lossless storage you shouldn't be changing
+ * colorspace anyway.
+ * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
+ * values for the G calculation are left scaled up, since we must add them
+ * together before rounding.
+ */
+ int bSize = imageWidth * imageHeight * nComponents;
+ byte[] rgbData = new byte[bSize];
+ int destIndex = 0;
+ expandImageComponents();
+ byte[] yComp = imageComponents[0];
+ byte[] cbComp = imageComponents[1];
+ byte[] crComp = imageComponents[2];
+ int compWidth = frameHeader.componentParameters[0][3];
+ for (int v = 0; v < imageHeight; v++) {
+ int srcIndex = v * compWidth;
+ for (int i = 0; i < imageWidth; i++) {
+ int y = yComp[srcIndex] & 0xFF;
+ int cb = cbComp[srcIndex] & 0xFF;
+ int cr = crComp[srcIndex] & 0xFF;
+ int r = y + CrRTable[cr];
+ int g = y + ((CbGTable[cb] + CrGTable[cr]) / 65536);
+ int b = y + CbBTable[cb];
+ if (r < 0) {
+ r = 0;
+ } else {
+ if (r > 255) r = 255;
+ }
+ if (g < 0) {
+ g = 0;
+ } else {
+ if (g > 255) g = 255;
+ }
+ if (b < 0) {
+ b = 0;
+ } else {
+ if (b > 255) b = 255;
+ }
+ rgbData[destIndex] = (byte)b;
+ rgbData[destIndex + 1] = (byte)g;
+ rgbData[destIndex + 2] = (byte)r;
+ destIndex += 3;
+ srcIndex++;
+ }
+ }
+ return rgbData;
+}
+byte[] convertYIQToRGB() {
+ /* Unsupported CMYK format. Answer an empty byte array. */
+ return new byte[0];
+}
+void decodeACCoefficients(int[] dataUnit, int iComp) {
+ int[] sParams = scanHeader.componentParameters[iComp];
+ JPEGHuffmanTable acTable = acHuffmanTables[sParams[AC]];
+ int k = 1;
+ while (k < 64) {
+ int rs = decodeUsingTable(acTable);
+ int r = rs >> 4;
+ int s = rs & 0xF;
+ if (s == 0) {
+ if (r == 15) {
+ k += 16;
+ } else {
+ break;
+ }
+ } else {
+ k += r;
+ int bits = receive(s);
+ dataUnit[ZigZag8x8[k]] = extendBy(bits, s);
+ k++;
+ }
+ }
+}
+void decodeACFirstCoefficients(int[] dataUnit, int iComp, int start, int end, int approxBit) {
+ if (eobrun > 0) {
+ eobrun--;
+ return;
+ }
+ int[] sParams = scanHeader.componentParameters[iComp];
+ JPEGHuffmanTable acTable = acHuffmanTables[sParams[AC]];
+ int k = start;
+ while (k <= end) {
+ int rs = decodeUsingTable(acTable);
+ int r = rs >> 4;
+ int s = rs & 0xF;
+ if (s == 0) {
+ if (r == 15) {
+ k += 16;
+ } else {
+ eobrun = (1 << r) + receive(r) - 1;
+ break;
+ }
+ } else {
+ k += r;
+ int bits = receive(s);
+ dataUnit[ZigZag8x8[k]] = extendBy(bits, s) << approxBit;
+ k++;
+ }
+ }
+}
+void decodeACRefineCoefficients(int[] dataUnit, int iComp, int start, int end, int approxBit) {
+ int[] sParams = scanHeader.componentParameters[iComp];
+ JPEGHuffmanTable acTable = acHuffmanTables[sParams[AC]];
+ int k = start;
+ while (k <= end) {
+ if (eobrun > 0) {
+ while (k <= end) {
+ int zzIndex = ZigZag8x8[k];
+ if (dataUnit[zzIndex] != 0) {
+ dataUnit[zzIndex] = refineAC(dataUnit[zzIndex], approxBit);
+ }
+ k++;
+ }
+ eobrun--;
+ } else {
+ int rs = decodeUsingTable(acTable);
+ int r = rs >> 4;
+ int s = rs & 0xF;
+ if (s == 0) {
+ if (r == 15) {
+ int zeros = 0;
+ while (zeros < 16 && k <= end) {
+ int zzIndex = ZigZag8x8[k];
+ if (dataUnit[zzIndex] != 0) {
+ dataUnit[zzIndex] = refineAC(dataUnit[zzIndex], approxBit);
+ } else {
+ zeros++;
+ }
+ k++;
+ }
+ } else {
+ eobrun = (1 << r) + receive(r);
+ }
+ } else {
+ int bit = receive(s);
+ int zeros = 0;
+ int zzIndex = ZigZag8x8[k];
+ while ((zeros < r || dataUnit[zzIndex] != 0) && k <= end) {
+ if (dataUnit[zzIndex] != 0) {
+ dataUnit[zzIndex] = refineAC(dataUnit[zzIndex], approxBit);
+ } else {
+ zeros++;
+ }
+ k++;
+ zzIndex = ZigZag8x8[k];
+ }
+ if (bit != 0) {
+ dataUnit[zzIndex] = 1 << approxBit;
+ } else {
+ dataUnit[zzIndex] = -1 << approxBit;
+ }
+ k++;
+ }
+ }
+ }
+}
+int refineAC(int ac, int approxBit) {
+ if (ac > 0) {
+ int bit = nextBit();
+ if (bit != 0) {
+ ac = ac + (1 << approxBit);
+ }
+ } else if (ac < 0) {
+ int bit = nextBit();
+ if (bit != 0) {
+ ac = ac + (-1 << approxBit);
+ }
+ }
+ return ac;
+}
+void decodeDCCoefficient(int[] dataUnit, int iComp, boolean first, int approxBit) {
+ int[] sParams = scanHeader.componentParameters[iComp];
+ JPEGHuffmanTable dcTable = dcHuffmanTables[sParams[DC]];
+ int lastDC = 0;
+ if (progressive && !first) {
+ int bit = nextBit();
+ lastDC = dataUnit[0] + (bit << approxBit);
+ } else {
+ lastDC = precedingDCs[iComp];
+ int nBits = decodeUsingTable(dcTable);
+ if (nBits != 0) {
+ int bits = receive(nBits);
+ int diff = extendBy(bits, nBits);
+ lastDC = lastDC + diff;
+ precedingDCs[iComp] = lastDC;
+ }
+ if (progressive) {
+ lastDC = lastDC << approxBit;
+ }
+ }
+ dataUnit[0] = lastDC;
+}
+void dequantize(int[] dataUnit, int iComp) {
+ int[] qTable = quantizationTables[frameComponents[iComp][TQI]];
+ for (int i = 0; i < dataUnit.length; i++) {
+ int zzIndex = ZigZag8x8[i];
+ dataUnit[zzIndex] = dataUnit[zzIndex] * qTable[i];
+ }
+}
+byte[] decodeImageComponents() {
+ int[] compIds = new int[nComponents];
+ int compIdsIndex = 0;
+ for (int i = 0; i < nComponents; i++) {
+ compIds[compIdsIndex] = i + 1;
+ compIdsIndex++;
+ }
+ if ((compIds.length == 3) &&
+ (compIds[0] == 1) &&
+ (compIds[1] == 2) &&
+ (compIds[2] == 3)) {
+ return convertYCbCrToRGB();
+ }
+ if ((compIds.length == 3) &&
+ (compIds[0] == 1) &&
+ (compIds[1] == 4) &&
+ (compIds[2] == 5)) {
+ return convertYIQToRGB();
+ }
+ if (compIds.length == 4) {
+ return convertCMYKToRGB();
+ }
+ return convertYToRGB();
+}
+void decodeMCUAtXAndY(int xmcu, int ymcu, int nComponentsInScan, boolean first, int start, int end, int approxBit) {
+ for (int iComp = 0; iComp < nComponentsInScan; iComp++) {
+ int scanComponent = iComp;
+ while (scanHeader.componentParameters[scanComponent] == null) {
+ scanComponent++;
+ }
+ int[] frameComponent = frameComponents[scanComponent];
+ int hi = frameComponent[HI];
+ int vi = frameComponent[VI];
+ if (nComponentsInScan == 1) {
+ hi = 1;
+ vi = 1;
+ }
+ int compWidth = frameComponent[CW];
+ for (int ivi = 0; ivi < vi; ivi++) {
+ for (int ihi = 0; ihi < hi; ihi++) {
+ if (progressive) {
+ // Progressive: First scan - create a new data unit.
+ // Subsequent scans - refine the existing data unit.
+ int index = (ymcu * vi + ivi) * compWidth + xmcu * hi + ihi;
+ dataUnit = dataUnits[scanComponent][index];
+ if (dataUnit == null) {
+ dataUnit = new int[64];
+ dataUnits[scanComponent][index] = dataUnit;
+ }
+ } else {
+ // Sequential: Clear and reuse the data unit buffer.
+ for (int i = 0; i < dataUnit.length; i++) {
+ dataUnit[i] = 0;
+ }
+ }
+ if (!progressive || scanHeader.isDCProgressiveScan()) {
+ decodeDCCoefficient(dataUnit, scanComponent, first, approxBit);
+ }
+ if (!progressive) {
+ decodeACCoefficients(dataUnit, scanComponent);
+ } else {
+ if (scanHeader.isACProgressiveScan()) {
+ if (first) {
+ decodeACFirstCoefficients(dataUnit, scanComponent, start, end, approxBit);
+ } else {
+ decodeACRefineCoefficients(dataUnit, scanComponent, start, end, approxBit);
+ }
+ }
+ if (loader.hasListeners()) {
+ // Dequantization, IDCT, up-sampling and color conversion
+ // are done on a copy of the coefficient data in order to
+ // display the image incrementally.
+ int[] temp = dataUnit;
+ dataUnit = new int[64];
+ System.arraycopy(temp, 0, dataUnit, 0, 64);
+ }
+ }
+ if (!progressive || (progressive && loader.hasListeners())) {
+ dequantize(dataUnit, scanComponent);
+ inverseDCT(dataUnit);
+ storeData(dataUnit, scanComponent, xmcu, ymcu, hi, ihi, vi, ivi);
+ }
+ }
+ }
+ }
+}
+void decodeScan() {
+ if (progressive && !scanHeader.verifyProgressiveScan()) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ int nComponentsInScan = scanHeader.getNumberOfImageComponents();
+ int mcuRowsInScan = interleavedMcuRows;
+ int mcusPerRow = interleavedMcuCols;
+ if (nComponentsInScan == 1) {
+ // Non-interleaved.
+ int iComp = 0;
+ while (scanHeader.componentParameters[iComp] == null) {
+ iComp++;
+ }
+ int[] frameComponent = frameComponents[iComp];
+ int hi = frameComponent[HI];
+ int vi = frameComponent[VI];
+ int mcuWidth = DCTSIZE * maxH / hi;
+ int mcuHeight = DCTSIZE * maxV / vi;
+ mcusPerRow = (imageWidth + mcuWidth - 1) / mcuWidth;
+ mcuRowsInScan = (imageHeight + mcuHeight - 1) / mcuHeight;
+ }
+ boolean first = scanHeader.isFirstScan();
+ int start = scanHeader.getStartOfSpectralSelection();
+ int end = scanHeader.getEndOfSpectralSelection();
+ int approxBit = scanHeader.getApproxBitPositionLow();
+ restartsToGo = restartInterval;
+ nextRestartNumber = 0;
+ for (int ymcu = 0; ymcu < mcuRowsInScan; ymcu++) {
+ for (int xmcu = 0; xmcu < mcusPerRow; xmcu++) {
+ if (restartInterval != 0) {
+ if (restartsToGo == 0) processRestartInterval();
+ restartsToGo--;
+ }
+ decodeMCUAtXAndY(xmcu, ymcu, nComponentsInScan, first, start, end, approxBit);
+ }
+ }
+}
+int decodeUsingTable(JPEGHuffmanTable huffmanTable) {
+ int i = 0;
+ int[] maxCodes = huffmanTable.getDhMaxCodes();
+ int[] minCodes = huffmanTable.getDhMinCodes();
+ int[] valPtrs = huffmanTable.getDhValPtrs();
+ int[] huffVals = huffmanTable.getDhValues();
+ int code = nextBit();
+ while (code > maxCodes[i]) {
+ code = code * 2 + nextBit();
+ i++;
+ }
+ int j = valPtrs[i];
+ j = j + code - minCodes[i];
+ return huffVals[j];
+}
+void emit(int huffCode, int nBits) {
+ if (nBits == 0) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ int[] power2m1 = new int[] {
+ 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191,
+ 16383, 32767, 65535, 131125
+ };
+ int code = (huffCode & power2m1[nBits - 1]) << (24 - nBits - currentBitCount);
+ byte[] codeBuffer = new byte[4];
+ codeBuffer[0] = (byte)(code % 256);
+ codeBuffer[1] = (byte)((code / 256) % 256);
+ codeBuffer[2] = (byte)((code / 65536) % 256);
+ codeBuffer[3] = (byte)((code / 16777216) % 256);
+ int abs = nBits - (8 - currentBitCount);
+ if (abs < 0) abs = -abs;
+ if ((abs / 8) > 0) {
+ currentByte += codeBuffer[2];
+ emitByte((byte)currentByte);
+ emitByte((byte)codeBuffer[1]);
+ currentByte = codeBuffer[0];
+ currentBitCount += nBits - 16;
+ } else {
+ currentBitCount += nBits;
+ if (currentBitCount >= 8) {
+ currentByte += codeBuffer[2];
+ emitByte((byte)currentByte);
+ currentByte = codeBuffer[1];
+ currentBitCount -= 8;
+ } else {
+ currentByte += codeBuffer[2];
+ }
+ }
+}
+void emitByte(byte byteValue) {
+ if (bufferCurrentPosition >= 512) {
+ resetOutputBuffer();
+ }
+ dataBuffer[bufferCurrentPosition] = byteValue;
+ bufferCurrentPosition++;
+ if (byteValue == -1) {
+ emitByte((byte)0);
+ }
+}
+void encodeACCoefficients(int[] dataUnit, int iComp) {
+ int[] sParams = scanHeader.componentParameters[iComp];
+ JPEGHuffmanTable acTable = acHuffmanTables[sParams[AC]];
+ int[] ehCodes = acTable.ehCodes;
+ byte[] ehSizes = acTable.ehCodeLengths;
+ int r = 0;
+ int k = 1;
+ while (k < 64) {
+ k++;
+ int acValue = dataUnit[ZigZag8x8[k - 1]];
+ if (acValue == 0) {
+ if (k == 64) {
+ emit(ehCodes[0], ehSizes[0] & 0xFF);
+ } else {
+ r++;
+ }
+ } else {
+ while (r > 15) {
+ emit(ehCodes[0xF0], ehSizes[0xF0] & 0xFF);
+ r -= 16;
+ }
+ if (acValue < 0) {
+ int absACValue = acValue;
+ if (absACValue < 0) absACValue = -absACValue;
+ int nBits = NBitsTable[absACValue];
+ int rs = r * 16 + nBits;
+ emit(ehCodes[rs], ehSizes[rs] & 0xFF);
+ emit(0xFFFFFF - absACValue, nBits);
+ } else {
+ int nBits = NBitsTable[acValue];
+ int rs = r * 16 + nBits;
+ emit(ehCodes[rs], ehSizes[rs] & 0xFF);
+ emit(acValue, nBits);
+ }
+ r = 0;
+ }
+ }
+}
+void encodeDCCoefficients(int[] dataUnit, int iComp) {
+ int[] sParams = scanHeader.componentParameters[iComp];
+ JPEGHuffmanTable dcTable = dcHuffmanTables[sParams[DC]];
+ int lastDC = precedingDCs[iComp];
+ int dcValue = dataUnit[0];
+ int diff = dcValue - lastDC;
+ precedingDCs[iComp] = dcValue;
+ if (diff < 0) {
+ int absDiff = 0 - diff;
+ int nBits = NBitsTable[absDiff];
+ emit(dcTable.ehCodes[nBits], dcTable.ehCodeLengths[nBits]);
+ emit(0xFFFFFF - absDiff, nBits);
+ } else {
+ int nBits = NBitsTable[diff];
+ emit(dcTable.ehCodes[nBits], dcTable.ehCodeLengths[nBits]);
+ if (nBits != 0) {
+ emit(diff, nBits);
+ }
+ }
+}
+void encodeMCUAtXAndY(int xmcu, int ymcu) {
+ int nComponentsInScan = scanHeader.getNumberOfImageComponents();
+ dataUnit = new int[64];
+ for (int iComp = 0; iComp < nComponentsInScan; iComp++) {
+ int[] frameComponent = frameComponents[iComp];
+ int hi = frameComponent[HI];
+ int vi = frameComponent[VI];
+ for (int ivi = 0; ivi < vi; ivi++) {
+ for (int ihi = 0; ihi < hi; ihi++) {
+ extractData(dataUnit, iComp, xmcu, ymcu, ihi, ivi);
+ forwardDCT(dataUnit);
+ quantizeData(dataUnit, iComp);
+ encodeDCCoefficients(dataUnit, iComp);
+ encodeACCoefficients(dataUnit, iComp);
+ }
+ }
+ }
+}
+void encodeScan() {
+ for (int ymcu = 0; ymcu < interleavedMcuRows; ymcu++) {
+ for (int xmcu = 0; xmcu < interleavedMcuCols; xmcu++) {
+ encodeMCUAtXAndY(xmcu, ymcu);
+ }
+ }
+ if (currentBitCount != 0) {
+ emitByte((byte)currentByte);
+ }
+ resetOutputBuffer();
+}
+void expandImageComponents() {
+ for (int iComp = 0; iComp < nComponents; iComp++) {
+ int[] frameComponent = frameComponents[iComp];
+ int hi = frameComponent[HI];
+ int vi = frameComponent[VI];
+ int upH = maxH / hi;
+ int upV = maxV / vi;
+ if ((upH * upV) > 1) {
+ byte[] component = imageComponents[iComp];
+ int compWidth = frameComponent[CW];
+ int compHeight = frameComponent[CH];
+ int upCompWidth = compWidth * upH;
+ int upCompHeight = compHeight * upV;
+ RGB[] rgbs = new RGB[] {
+ new RGB(0,0,0),
+ new RGB(0x80,0,0),
+ new RGB(0,0x80,0),
+ new RGB(0x80,0x80,0),
+ new RGB(0,0,0x80),
+ new RGB(0x80,0,0x80),
+ new RGB(0,0x80,0x80),
+ new RGB(0xC0,0xC0,0xC0),
+ new RGB(0x80,0x80,0x80),
+ new RGB(0xFF,0,0),
+ new RGB(0,0xFF,0),
+ new RGB(0xFF,0xFF,0),
+ new RGB(0,0,0xFF),
+ new RGB(0xFF,0,0xFF),
+ new RGB(0,0xFF,0xFF),
+ new RGB(0xFF,0xFF,0xFF),
+ };
+ ImageData src = new ImageData(compWidth, compHeight, 8, new PaletteData(rgbs), 4, component);
+ ImageData dest = src.scaledTo(upCompWidth, upCompHeight);
+ imageComponents[iComp] = dest.data;
+ }
+ }
+}
+int extendBy(int diff, int t) {
+ if (diff < ExtendTest[t]) {
+ return diff + ExtendOffset[t];
+ } else {
+ return diff;
+ }
+}
+void extractData(int[] dataUnit, int iComp, int xmcu, int ymcu, int ihi, int ivi) {
+ byte[] compImage = imageComponents[iComp];
+ int[] frameComponent = frameComponents[iComp];
+ int hi = frameComponent[HI];
+ int vi = frameComponent[VI];
+ int compWidth = frameComponent[CW];
+ int srcIndex = ((ymcu * vi + ivi) * compWidth * DCTSIZE) + ((xmcu * hi + ihi) * DCTSIZE);
+ int destIndex = 0;
+ for (int i = 0; i < DCTSIZE; i++) {
+ for (int col = 0; col < DCTSIZE; col++) {
+ dataUnit[destIndex] = (compImage[srcIndex + col] & 0xFF) - 128;
+ destIndex++;
+ }
+ srcIndex += compWidth;
+ }
+}
+void forwardDCT(int[] dataUnit) {
+ for (int row = 0; row < 8; row++) {
+ int rIndex = row * DCTSIZE;
+ int tmp0 = dataUnit[rIndex] + dataUnit[rIndex + 7];
+ int tmp7 = dataUnit[rIndex] - dataUnit[rIndex + 7];
+ int tmp1 = dataUnit[rIndex + 1] + dataUnit[rIndex + 6];
+ int tmp6 = dataUnit[rIndex + 1] - dataUnit[rIndex + 6];
+ int tmp2 = dataUnit[rIndex + 2] + dataUnit[rIndex + 5];
+ int tmp5 = dataUnit[rIndex + 2] - dataUnit[rIndex + 5];
+ int tmp3 = dataUnit[rIndex + 3] + dataUnit[rIndex + 4];
+ int tmp4 = dataUnit[rIndex + 3] - dataUnit[rIndex + 4];
+
+ /**
+ * Even part per LL&M figure 1 --- note that published figure
+ * is faulty; rotator 'sqrt(2)*c1' should be 'sqrt(2)*c6'.
+ */
+ int tmp10 = tmp0 + tmp3;
+ int tmp13 = tmp0 - tmp3;
+ int tmp11 = tmp1 + tmp2;
+ int tmp12 = tmp1 - tmp2;
+
+ dataUnit[rIndex] = (tmp10 + tmp11) * 4;
+ dataUnit[rIndex + 4] = (tmp10 - tmp11) * 4;
+
+ int z1 = (tmp12 + tmp13) * FIX_0_541196100;
+ int scaleFactor1 = ExtendTest[11];
+ int scaleFactor2 = ExtendTest[12];
+ int n = z1 + (tmp13 * FIX_0_765366865) + scaleFactor1;
+ dataUnit[rIndex + 2] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[rIndex + 2]--;
+ n = z1 + (tmp12 * (0 - FIX_1_847759065)) + scaleFactor1;
+ dataUnit[rIndex + 6] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[rIndex + 6]--;
+
+ /**
+ * Odd part per figure 8 --- note paper omits factor of sqrt(2).
+ * cK represents cos(K*pi/16).
+ * i0..i3 in the paper are tmp4..tmp7 here.
+ */
+ z1 = tmp4 + tmp7;
+ int z2 = tmp5 + tmp6;
+ int z3 = tmp4 + tmp6;
+ int z4 = tmp5 + tmp7;
+ int z5 = (z3 + z4) * FIX_1_175875602; // sqrt(2) * c3
+
+ tmp4 = tmp4 * FIX_0_298631336; // sqrt(2) * (-c1+c3+c5-c7)
+ tmp5 = tmp5 * FIX_2_053119869; // sqrt(2) * ( c1+c3-c5+c7)
+ tmp6 = tmp6 * FIX_3_072711026; // sqrt(2) * ( c1+c3+c5-c7)
+ tmp7 = tmp7 * FIX_1_501321110; // sqrt(2) * ( c1+c3-c5-c7)
+ z1 = z1 * (0 - FIX_0_899976223); // sqrt(2) * (c7-c3)
+ z2 = z2 * (0 - FIX_2_562915447); // sqrt(2) * (-c1-c3)
+ z3 = z3 * (0 - FIX_1_961570560); // sqrt(2) * (-c3-c5)
+ z4 = z4 * (0 - FIX_0_390180644); // sqrt(2) * (c5-c3)
+
+ z3 = z3 + z5;
+ z4 = z4 + z5;
+
+ n = tmp4 + z1 + z3 + scaleFactor1;
+ dataUnit[rIndex + 7] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[rIndex + 7]--;
+ n = tmp5 + z2 + z4 + scaleFactor1;
+ dataUnit[rIndex + 5] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[rIndex + 5]--;
+ n = tmp6 + z2 + z3 + scaleFactor1;
+ dataUnit[rIndex + 3] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[rIndex + 3]--;
+ n = tmp7 + z1 + z4 + scaleFactor1;
+ dataUnit[rIndex + 1] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[rIndex + 1]--;
+ }
+
+ /**
+ * Pass 2: process columns.
+ * Note that we must descale the results by a factor of 8 == 2**3,
+ * and also undo the PASS1_BITS scaling.
+ */
+ for (int col = 0; col < 8; col++) {
+ int c0 = col;
+ int c1 = col + 8;
+ int c2 = col + 16;
+ int c3 = col + 24;
+ int c4 = col + 32;
+ int c5 = col + 40;
+ int c6 = col + 48;
+ int c7 = col + 56;
+ int tmp0 = dataUnit[c0] + dataUnit[c7];
+ int tmp7 = dataUnit[c0] - dataUnit[c7];
+ int tmp1 = dataUnit[c1] + dataUnit[c6];
+ int tmp6 = dataUnit[c1] - dataUnit[c6];
+ int tmp2 = dataUnit[c2] + dataUnit[c5];
+ int tmp5 = dataUnit[c2] - dataUnit[c5];
+ int tmp3 = dataUnit[c3] + dataUnit[c4];
+ int tmp4 = dataUnit[c3] - dataUnit[c4];
+
+ /**
+ * Even part per LL&M figure 1 --- note that published figure
+ * is faulty; rotator 'sqrt(2)*c1' should be 'sqrt(2)*c6'.
+ */
+ int tmp10 = tmp0 + tmp3;
+ int tmp13 = tmp0 - tmp3;
+ int tmp11 = tmp1 + tmp2;
+ int tmp12 = tmp1 - tmp2;
+
+ int scaleFactor1 = ExtendTest[5];
+ int scaleFactor2 = ExtendTest[6];
+ int n = tmp10 + tmp11 + scaleFactor1;
+ dataUnit[c0] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[c0]--;
+ n = tmp10 - tmp11 + scaleFactor1;
+ dataUnit[c4] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[c4]--;
+
+ int z1 = (tmp12 + tmp13) * FIX_0_541196100;
+ scaleFactor1 = ExtendTest[18];
+ scaleFactor2 = ExtendTest[19];
+ n = z1 + (tmp13 * FIX_0_765366865) + scaleFactor1;
+ dataUnit[c2] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[c2]--;
+ n = z1 + (tmp12 * (0 - FIX_1_847759065)) + scaleFactor1;
+ dataUnit[c6] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[c6]--;
+
+ /**
+ * Odd part per figure 8 --- note paper omits factor of sqrt(2).
+ * cK represents cos(K*pi/16).
+ * i0..i3 in the paper are tmp4..tmp7 here.
+ */
+ z1 = tmp4 + tmp7;
+ int z2 = tmp5 + tmp6;
+ int z3 = tmp4 + tmp6;
+ int z4 = tmp5 + tmp7;
+ int z5 = (z3 + z4) * FIX_1_175875602; // sqrt(2) * c3
+
+ tmp4 = tmp4 * FIX_0_298631336; // sqrt(2) * (-c1+c3+c5-c7)
+ tmp5 = tmp5 * FIX_2_053119869; // sqrt(2) * ( c1+c3-c5+c7)
+ tmp6 = tmp6 * FIX_3_072711026; // sqrt(2) * ( c1+c3+c5-c7)
+ tmp7 = tmp7 * FIX_1_501321110; // sqrt(2) * ( c1+c3-c5-c7)
+ z1 = z1 * (0 - FIX_0_899976223); // sqrt(2) * (c7-c3)
+ z2 = z2 * (0 - FIX_2_562915447); // sqrt(2) * (-c1-c3)
+ z3 = z3 * (0 - FIX_1_961570560); // sqrt(2) * (-c3-c5)
+ z4 = z4 * (0 - FIX_0_390180644); // sqrt(2) * (c5-c3)
+
+ z3 = z3 + z5;
+ z4 = z4 + z5;
+
+ n = tmp4 + z1 + z3 + scaleFactor1;
+ dataUnit[c7] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[c7]--;
+ n = tmp5 + z2 + z4 + scaleFactor1;
+ dataUnit[c5] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[c5]--;
+ n = tmp6 + z2 + z3 + scaleFactor1;
+ dataUnit[c3] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[c3]--;
+ n = tmp7 + z1 + z4 + scaleFactor1;
+ dataUnit[c1] = n / scaleFactor2;
+ if ((n < 0) && (n % scaleFactor2 != 0)) dataUnit[c1]--;
+ }
+}
+void getAPP0() {
+ JPEGAppn appn = new JPEGAppn(inputStream);
+ if (!appn.verify()) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+}
+void getCOM() {
+ new JPEGComment(inputStream);
+}
+void getDAC() {
+ JPEGArithmeticConditioningTable dac = new JPEGArithmeticConditioningTable(inputStream);
+ arithmeticTables = dac;
+}
+void getDHT() {
+ JPEGHuffmanTable dht = new JPEGHuffmanTable(inputStream);
+ if (!dht.verify()) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ if (acHuffmanTables == null) {
+ acHuffmanTables = new JPEGHuffmanTable[4];
+ }
+ if (dcHuffmanTables == null) {
+ dcHuffmanTables = new JPEGHuffmanTable[4];
+ }
+ JPEGHuffmanTable[] dhtTables = dht.getAllTables();
+ for (int i = 0; i < dhtTables.length; i++) {
+ JPEGHuffmanTable dhtTable = dhtTables[i];
+ if (dhtTable.getTableClass() == 0) {
+ dcHuffmanTables[dhtTable.getTableIdentifier()] = dhtTable;
+ } else {
+ acHuffmanTables[dhtTable.getTableIdentifier()] = dhtTable;
+ }
+ }
+}
+void getDNL() {
+ new JPEGRestartInterval(inputStream);
+}
+void getDQT() {
+ JPEGQuantizationTable dqt = new JPEGQuantizationTable(inputStream);
+ int[][] currentTables = quantizationTables;
+ if (currentTables == null) {
+ currentTables = new int[4][];
+ }
+ int[] dqtTablesKeys = dqt.getQuantizationTablesKeys();
+ int[][] dqtTablesValues = dqt.getQuantizationTablesValues();
+ for (int i = 0; i < dqtTablesKeys.length; i++) {
+ int index = dqtTablesKeys[i];
+ currentTables[index] = dqtTablesValues[i];
+ }
+ quantizationTables = currentTables;
+}
+void getDRI() {
+ JPEGRestartInterval dri = new JPEGRestartInterval(inputStream);
+ if (!dri.verify()) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ restartInterval = dri.getRestartInterval();
+}
+static void initialize() {
+ initializeRGBYCbCrTables();
+ initializeYCbCrRGBTables();
+ initializeBitCountTable();
+}
+static void initializeBitCountTable() {
+ int nBits = 1;
+ int count = 0;
+ int power2 = 2;
+ NBitsTable = new int[2048];
+ NBitsTable[0] = 0;
+ for (int i = 1; i < NBitsTable.length; i++) {
+ if (!(i < power2)) {
+ nBits++;
+ power2 *= 2;
+ }
+ NBitsTable[i] = nBits;
+ }
+}
+static void initializeRGBYCbCrTables() {
+ RYTable = new int[256];
+ GYTable = new int[256];
+ BYTable = new int[256];
+ RCbTable = new int[256];
+ GCbTable = new int[256];
+ BCbTable = new int[256];
+ RCrTable = BCbTable;
+ GCrTable = new int[256];
+ BCrTable = new int[256];
+ for (int i = 0; i < 256; i++) {
+ RYTable[i] = i * 19595;
+ GYTable[i] = i * 38470;
+ BYTable[i] = i * 7471 + 32768;
+ RCbTable[i] = i * -11059;
+ GCbTable[i] = i * -21709;
+ BCbTable[i] = i * 32768 + 8388608;
+ GCrTable[i] = i * -27439;
+ BCrTable[i] = i * -5329;
+ }
+}
+static void initializeYCbCrRGBTables() {
+ CrRTable = new int[256];
+ CbBTable = new int[256];
+ CrGTable = new int[256];
+ CbGTable = new int[256];
+ for (int i = 0; i < 256; i++) {
+ int x2 = 2 * i - 255;
+ CrRTable[i] = (45941 * x2 + 32768) / 65536;
+ CbBTable[i] = (58065 * x2 + 32768) / 65536;
+ CrGTable[i] = -23401 * x2;
+ CbGTable[i] = -11277 * x2 + 32768;
+ }
+}
+void inverseDCT(int[] dataUnit) {
+ for (int row = 0; row < 8; row++) {
+ int rIndex = row * DCTSIZE;
+ /**
+ * Due to quantization, we will usually find that many of the input
+ * coefficients are zero, especially the AC terms. We can exploit this
+ * by short-circuiting the IDCT calculation for any row in which all
+ * the AC terms are zero. In that case each output is equal to the
+ * DC coefficient (with scale factor as needed).
+ * With typical images and quantization tables, half or more of the
+ * row DCT calculations can be simplified this way.
+ */
+ if (isZeroInRow(dataUnit, rIndex)) {
+ int dcVal = dataUnit[rIndex] * 4;
+ for (int i = rIndex; i < rIndex + 8; i++) {
+ dataUnit[i] = dcVal;
+ }
+ } else {
+ /**
+ * Even part: reverse the even part of the forward DCT.
+ * The rotator is sqrt(2)*c(-6).
+ */
+ int z2 = dataUnit[rIndex + 2];
+ int z3 = dataUnit[rIndex + 6];
+ int z1 = (z2 + z3) * FIX_0_541196100;
+ int tmp2 = z1 + (z3 * (0 - FIX_1_847759065));
+ int tmp3 = z1 + (z2 * FIX_0_765366865);
+ int tmp0 = (dataUnit[rIndex] + dataUnit[rIndex + 4]) * 8192;
+ int tmp1 = (dataUnit[rIndex] - dataUnit[rIndex + 4]) * 8192;
+ int tmp10 = tmp0 + tmp3;
+ int tmp13 = tmp0 - tmp3;
+ int tmp11 = tmp1 + tmp2;
+ int tmp12 = tmp1 - tmp2;
+ /**
+ * Odd part per figure 8; the matrix is unitary and hence its
+ * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
+ */
+ tmp0 = dataUnit[rIndex + 7];
+ tmp1 = dataUnit[rIndex + 5];
+ tmp2 = dataUnit[rIndex + 3];
+ tmp3 = dataUnit[rIndex + 1];
+ z1 = tmp0 + tmp3;
+ z2 = tmp1 + tmp2;
+ z3 = tmp0 + tmp2;
+ int z4 = tmp1 + tmp3;
+ int z5 = (z3 + z4)* FIX_1_175875602; /* sqrt(2) * c3 */
+
+ tmp0 = tmp0 * FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = tmp1 * FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = tmp2 * FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = tmp3 * FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = z1 * (0 - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = z2 * (0 - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = z3 * (0 - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = z4 * (0 - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+
+ z3 = z3 + z5;
+ z4 = z4 + z5;
+ tmp0 = tmp0 + z1 + z3;
+ tmp1 = tmp1 + z2 + z4;
+ tmp2 = tmp2 + z2 + z3;
+ tmp3 = tmp3 + z1 + z4;
+
+ int descaleFactor1 = ExtendTest[11];
+ int descaleFactor2 = ExtendTest[12];
+ dataUnit[rIndex] = (tmp10 + tmp3 + descaleFactor1) / descaleFactor2;
+ dataUnit[rIndex + 7] = (tmp10 - tmp3 + descaleFactor1) / descaleFactor2;
+ dataUnit[rIndex + 1] = (tmp11 + tmp2 + descaleFactor1) / descaleFactor2;
+ dataUnit[rIndex + 6] = (tmp11 - tmp2 + descaleFactor1) / descaleFactor2;
+ dataUnit[rIndex + 2] = (tmp12 + tmp1 + descaleFactor1) / descaleFactor2;
+ dataUnit[rIndex + 5] = (tmp12 - tmp1 + descaleFactor1) / descaleFactor2;
+ dataUnit[rIndex + 3] = (tmp13 + tmp0 + descaleFactor1) / descaleFactor2;
+ dataUnit[rIndex + 4] = (tmp13 - tmp0 + descaleFactor1) / descaleFactor2;
+ }
+ }
+ /**
+ * Pass 2: process columns.
+ * Note that we must descale the results by a factor of 8 == 2**3,
+ * and also undo the PASS1_BITS scaling.
+ */
+ for (int col = 0; col < 8; col++) {
+ int c0 = col;
+ int c1 = col + 8;
+ int c2 = col + 16;
+ int c3 = col + 24;
+ int c4 = col + 32;
+ int c5 = col + 40;
+ int c6 = col + 48;
+ int c7 = col + 56;
+ if (isZeroInColumn(dataUnit, col)) {
+ int dcVal = (dataUnit[c0] + 16) / 32;
+ dataUnit[c0] = dcVal;
+ dataUnit[c1] = dcVal;
+ dataUnit[c2] = dcVal;
+ dataUnit[c3] = dcVal;
+ dataUnit[c4] = dcVal;
+ dataUnit[c5] = dcVal;
+ dataUnit[c6] = dcVal;
+ dataUnit[c7] = dcVal;
+ } else {
+ /**
+ * Even part: reverse the even part of the forward DCT.
+ * The rotator is sqrt(2)*c(-6).
+ */
+ int z2 = dataUnit[c2];
+ int z3 = dataUnit[c6];
+ int z1 = (z2 + z3) * FIX_0_541196100;
+ int tmp2 = z1 + (z3 * (0 - FIX_1_847759065));
+ int tmp3 = z1 + (z2 * FIX_0_765366865);
+ int tmp0 = (dataUnit[c0] + dataUnit[c4]) * 8192;
+ int tmp1 = (dataUnit[c0] - dataUnit[c4]) * 8192;
+ int tmp10 = tmp0 + tmp3;
+ int tmp13 = tmp0 - tmp3;
+ int tmp11 = tmp1 + tmp2;
+ int tmp12 = tmp1 - tmp2;
+ /**
+ * Odd part per figure 8; the matrix is unitary and hence its
+ * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
+ */
+ tmp0 = dataUnit[c7];;
+ tmp1 = dataUnit[c5];
+ tmp2 = dataUnit[c3];
+ tmp3 = dataUnit[c1];
+ z1 = tmp0 + tmp3;
+ z2 = tmp1 + tmp2;
+ z3 = tmp0 + tmp2;
+ int z4 = tmp1 + tmp3;
+ int z5 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */
+
+ tmp0 = tmp0 * FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = tmp1 * FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = tmp2 * FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = tmp3 * FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = z1 * (0 - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = z2 * (0 - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = z3 * (0 - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = z4 * (0 - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+
+ z3 = z3 + z5;
+ z4 = z4 + z5;
+
+ tmp0 = tmp0 + z1 + z3;
+ tmp1 = tmp1 + z2 + z4;
+ tmp2 = tmp2 + z2 + z3;
+ tmp3 = tmp3 + z1 + z4;
+
+ /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
+ int descaleFactor1 = ExtendTest[18];
+ int descaleFactor2 = ExtendTest[19];
+ dataUnit[c0] = (tmp10 + tmp3 + descaleFactor1) / descaleFactor2;
+ dataUnit[c7] = (tmp10 - tmp3 + descaleFactor1) / descaleFactor2;
+ dataUnit[c1] = (tmp11 + tmp2 + descaleFactor1) / descaleFactor2;
+ dataUnit[c6] = (tmp11 - tmp2 + descaleFactor1) / descaleFactor2;
+ dataUnit[c2] = (tmp12 + tmp1 + descaleFactor1) / descaleFactor2;
+ dataUnit[c5] = (tmp12 - tmp1 + descaleFactor1) / descaleFactor2;
+ dataUnit[c3] = (tmp13 + tmp0 + descaleFactor1) / descaleFactor2;
+ dataUnit[c4] = (tmp13 - tmp0 + descaleFactor1) / descaleFactor2;
+ }
+ }
+}
+public static boolean isJPEGFile(LEDataInputStream stream) {
+ try {
+ JPEGStartOfImage soi = new JPEGStartOfImage(stream);
+ byte[] header = new byte[16];
+ stream.read(header);
+ JPEGAppn appn = new JPEGAppn(header);
+ stream.unread(appn.reference);
+ stream.unread(soi.reference);
+ return soi.verify() && appn.verify();
+ // && appn.getSegmentMarker() == APP0; doesn't have to be app0
+ } catch (Exception e) {
+ return false;
+ }
+}
+boolean isZeroInColumn(int[] dataUnit, int col) {
+ return (dataUnit[col + 8] + dataUnit[col + 16] +
+ dataUnit[col + 24] + dataUnit[col + 32] +
+ dataUnit[col + 40] + dataUnit[col + 48] +
+ dataUnit[col + 56]) == 0;
+}
+boolean isZeroInRow(int[] dataUnit, int rIndex) {
+ return (dataUnit[rIndex + 1] + dataUnit[rIndex + 2] +
+ dataUnit[rIndex + 3] + dataUnit[rIndex + 4] +
+ dataUnit[rIndex + 5] + dataUnit[rIndex + 6] +
+ dataUnit[rIndex + 7]) == 0;
+}
+ImageData[] loadFromByteStream() {
+ JPEGStartOfImage soi = new JPEGStartOfImage(inputStream);
+ if (!soi.verify()) SWT.error(SWT.ERROR_INVALID_IMAGE);
+ restartInterval = 0;
+
+ /* Process the tables preceding the frame header. */
+ processTables();
+
+ /* Start of Frame. */
+ frameHeader = new JPEGFrameHeader(inputStream);
+ if (!frameHeader.verify()) SWT.error(SWT.ERROR_INVALID_IMAGE);
+ imageWidth = frameHeader.getSamplesPerLine();
+ imageHeight = frameHeader.getNumberOfLines();
+ maxH = frameHeader.getMaxHFactor();
+ maxV = frameHeader.getMaxVFactor();
+ int mcuWidth = maxH * DCTSIZE;
+ int mcuHeight = maxV * DCTSIZE;
+ interleavedMcuCols = (imageWidth + mcuWidth - 1) / mcuWidth;
+ interleavedMcuRows = (imageHeight + mcuHeight - 1) / mcuHeight;
+ progressive = frameHeader.isProgressive();
+ samplePrecision = frameHeader.getSamplePrecision();
+ nComponents = frameHeader.getNumberOfImageComponents();
+ frameComponents = frameHeader.componentParameters;
+ imageComponents = new byte[nComponents][];
+ if (progressive) {
+ // Progressive jpeg: need to keep all of the data units.
+ dataUnits = new int[nComponents][][];
+ } else {
+ // Sequential jpeg: only need one data unit.
+ dataUnit = new int[8 * 8];
+ }
+ for (int i = 0; i < nComponents; i++) {
+ int[] frameComponent = frameComponents[i];
+ int bufferSize = frameComponent[CW] * frameComponent[CH];
+ imageComponents[i] = new byte[bufferSize];
+ if (progressive) {
+ dataUnits[i] = new int[bufferSize][];
+ }
+ }
+
+ /* Process the tables preceding the scan header. */
+ processTables();
+
+ /* Start of Scan. */
+ scanHeader = new JPEGScanHeader(inputStream);
+ if (!scanHeader.verify()) SWT.error(SWT.ERROR_INVALID_IMAGE);
+
+ /* Process scan(s) and further tables until EOI. */
+ int progressiveScanCount = 0;
+ boolean done = false;
+ while(!done) {
+ resetInputBuffer();
+ precedingDCs = new int[4];
+ decodeScan();
+ if (progressive && loader.hasListeners()) {
+ ImageData imageData = createImageData();
+ loader.notifyListeners(new ImageLoaderEvent(loader, imageData, progressiveScanCount, false));
+ progressiveScanCount++;
+ }
+
+ /* Unread any buffered data before looking for tables again. */
+ int delta = 512 - bufferCurrentPosition - 1;
+ if (delta > 0) {
+ byte[] unreadBuffer = new byte[delta];
+ System.arraycopy(dataBuffer, bufferCurrentPosition + 1, unreadBuffer, 0, delta);
+ try {
+ inputStream.unread(unreadBuffer);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ }
+
+ /* Process the tables preceding the next scan header. */
+ JPEGSegment jpegSegment = processTables();
+ if (jpegSegment == null || jpegSegment.getSegmentMarker() == EOI) {
+ done = true;
+ } else {
+ scanHeader = new JPEGScanHeader(inputStream);
+ if (!scanHeader.verify()) SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ }
+
+ if (progressive) {
+ for (int ymcu = 0; ymcu < interleavedMcuRows; ymcu++) {
+ for (int xmcu = 0; xmcu < interleavedMcuCols; xmcu++) {
+ for (int iComp = 0; iComp < nComponents; iComp++) {
+ int[] frameComponent = frameComponents[iComp];
+ int hi = frameComponent[HI];
+ int vi = frameComponent[VI];
+ int compWidth = frameComponent[CW];
+ for (int ivi = 0; ivi < vi; ivi++) {
+ for (int ihi = 0; ihi < hi; ihi++) {
+ int index = (ymcu * vi + ivi) * compWidth + xmcu * hi + ihi;
+ dataUnit = dataUnits[iComp][index];
+ dequantize(dataUnit, iComp);
+ inverseDCT(dataUnit);
+ storeData(dataUnit, iComp, xmcu, ymcu, hi, ihi, vi, ivi);
+ }
+ }
+ }
+ }
+ }
+ }
+ ImageData imageData = createImageData();
+ if (progressive && loader.hasListeners()) {
+ loader.notifyListeners(new ImageLoaderEvent(loader, imageData, progressiveScanCount, true));
+ }
+ return new ImageData[] {imageData};
+}
+ImageData createImageData() {
+ return ImageData.internal_new(
+ imageWidth,
+ imageHeight,
+ nComponents * samplePrecision,
+ setUpPalette(),
+ nComponents == 1 ? 4 : 1,
+ decodeImageComponents(),
+ 0,
+ null,
+ null,
+ -1,
+ -1,
+ SWT.IMAGE_JPEG,
+ 0,
+ 0,
+ 0,
+ 0);
+}
+int nextBit() {
+ if (currentBitCount != 0) {
+ currentBitCount--;
+ currentByte *= 2;
+ if (currentByte > 255) {
+ currentByte -= 256;
+ return 1;
+ } else {
+ return 0;
+ }
+ }
+ bufferCurrentPosition++;
+ if (bufferCurrentPosition >= 512) {
+ resetInputBuffer();
+ bufferCurrentPosition = 0;
+ }
+ currentByte = dataBuffer[bufferCurrentPosition] & 0xFF;
+ currentBitCount = 8;
+ byte nextByte;
+ if (bufferCurrentPosition == 511) {
+ resetInputBuffer();
+ currentBitCount = 8;
+ nextByte = dataBuffer[0];
+ } else {
+ nextByte = dataBuffer[bufferCurrentPosition + 1];
+ }
+ if (currentByte == 0xFF) {
+ if (nextByte == 0) {
+ bufferCurrentPosition ++;
+ currentBitCount--;
+ currentByte *= 2;
+ if (currentByte > 255) {
+ currentByte -= 256;
+ return 1;
+ } else {
+ return 0;
+ }
+ } else {
+ if ((nextByte & 0xFF) + 0xFF00 == DNL) {
+ getDNL();
+ return 0;
+ } else {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ return 0;
+ }
+ }
+ } else {
+ currentBitCount--;
+ currentByte *= 2;
+ if (currentByte > 255) {
+ currentByte -= 256;
+ return 1;
+ } else {
+ return 0;
+ }
+ }
+}
+void processRestartInterval() {
+ do {
+ bufferCurrentPosition++;
+ if (bufferCurrentPosition > 511) {
+ resetInputBuffer();
+ bufferCurrentPosition = 0;
+ }
+ currentByte = dataBuffer[bufferCurrentPosition] & 0xFF;
+ } while (currentByte != 0xFF);
+ while (currentByte == 0xFF) {
+ bufferCurrentPosition++;
+ if (bufferCurrentPosition > 511) {
+ resetInputBuffer();
+ bufferCurrentPosition = 0;
+ }
+ currentByte = dataBuffer[bufferCurrentPosition] & 0xFF;
+ }
+ if (currentByte != ((RST0 + nextRestartNumber) % 256)) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ bufferCurrentPosition++;
+ if (bufferCurrentPosition > 511) {
+ resetInputBuffer();
+ bufferCurrentPosition = 0;
+ }
+ currentByte = dataBuffer[bufferCurrentPosition] & 0xFF;
+ currentBitCount = 8;
+ restartsToGo = restartInterval;
+ nextRestartNumber = (nextRestartNumber + 1) % 8;
+ precedingDCs = new int[4];
+ eobrun = 0;
+}
+/* Process all markers until a frame header, scan header, or EOI is found. */
+JPEGSegment processTables() {
+ while (true) {
+ JPEGSegment jpegSegment = seekUnspecifiedMarker(inputStream);
+ if (jpegSegment == null) return null;
+ JPEGFrameHeader sof = new JPEGFrameHeader(jpegSegment.reference);
+ if (sof.verify()) {
+ return jpegSegment;
+ }
+ int marker = jpegSegment.getSegmentMarker();
+ switch (marker) {
+ case SOI: // there should only be one SOI per file
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ case EOI:
+ case SOS:
+ return jpegSegment;
+ case DQT:
+ getDQT();
+ break;
+ case DHT:
+ getDHT();
+ break;
+ case DAC:
+ getDAC();
+ break;
+ case DRI:
+ getDRI();
+ break;
+ case APP0:
+ getAPP0();
+ break;
+ case COM:
+ getCOM();
+ break;
+ default:
+ skipSegmentFrom(inputStream);
+
+ }
+ }
+}
+void quantizeData(int[] dataUnit, int iComp) {
+ int[] qTable = quantizationTables[frameComponents[iComp][TQI]];
+ for (int i = 0; i < dataUnit.length; i++) {
+ int zzIndex = ZigZag8x8[i];
+ int data = dataUnit[zzIndex];
+ int absData = data < 0 ? 0 - data : data;
+ int qValue = qTable[i];
+ int q2 = qValue / 2;
+ absData += q2;
+ if (absData < qValue) {
+ dataUnit[zzIndex] = 0;
+ } else {
+ absData /= qValue;
+ if (data >= 0) {
+ dataUnit[zzIndex] = absData;
+ } else {
+ dataUnit[zzIndex] = 0 - absData;
+ }
+ }
+ }
+}
+int receive(int nBits) {
+ int v = 0;
+ for (int i = 0; i < nBits; i++) {
+ v = v * 2 + nextBit();
+ }
+ return v;
+}
+void resetInputBuffer() {
+ if (dataBuffer == null) {
+ dataBuffer = new byte[512];
+ }
+ try {
+ inputStream.read(dataBuffer);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ currentBitCount = 0;
+ bufferCurrentPosition = -1;
+}
+void resetOutputBuffer() {
+ if (dataBuffer == null) {
+ dataBuffer = new byte[512];
+ } else {
+ try {
+ outputStream.write(dataBuffer, 0, bufferCurrentPosition);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ }
+ bufferCurrentPosition = 0;
+}
+static JPEGSegment seekUnspecifiedMarker(LEDataInputStream byteStream) {
+ byte[] byteArray = new byte[2];
+ try {
+ while (true) {
+ if (byteStream.read(byteArray, 0, 1) != 1) return null;
+ if (byteArray[0] == (byte) 0xFF) {
+ if (byteStream.read(byteArray, 1, 1) != 1) return null;
+ if (byteArray[1] != (byte) 0xFF && byteArray[1] != 0) {
+ byteStream.unread(byteArray);
+ return new JPEGSegment(byteArray);
+ }
+ }
+ }
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ return null;
+}
+PaletteData setUpPalette() {
+ if (nComponents == 1) {
+ RGB[] entries = new RGB[256];
+ for (int i = 0; i < 256; i++) {
+ entries[i] = new RGB(i, i, i);
+ }
+ return new PaletteData(entries);
+ }
+ return new PaletteData(0xFF, 0xFF00, 0xFF0000);
+}
+static void skipSegmentFrom(LEDataInputStream byteStream) {
+ try {
+ byte[] byteArray = new byte[4];
+ JPEGSegment jpegSegment = new JPEGSegment(byteArray);
+
+ if (byteStream.read(byteArray) != byteArray.length) {
+ throw new SWTError(SWT.ERROR_INVALID_IMAGE);
+ }
+ if (!(byteArray[0] == -1 && byteArray[1] != 0 && byteArray[1] != -1)) {
+ throw new SWTError(SWT.ERROR_INVALID_IMAGE);
+ }
+ int delta = jpegSegment.getSegmentLength() - 2;
+ byteStream.skip(delta);
+ } catch (Exception e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+}
+void storeData(int[] dataUnit, int iComp, int xmcu, int ymcu, int hi, int ihi, int vi, int ivi) {
+ byte[] compImage = imageComponents[iComp];
+ int[] frameComponent = frameComponents[iComp];
+ int compWidth = frameComponent[CW];
+ int destIndex = ((ymcu * vi + ivi) * compWidth * DCTSIZE) + ((xmcu * hi + ihi) * DCTSIZE);
+ int srcIndex = 0;
+ for (int i = 0; i < DCTSIZE; i++) {
+ for (int col = 0; col < DCTSIZE; col++) {
+ int x = dataUnit[srcIndex] + 128;
+ if (x < 0) {
+ x = 0;
+ } else {
+ if (x > 255) x = 255;
+ }
+ compImage[destIndex + col] = (byte)x;
+ srcIndex++;
+ }
+ destIndex += compWidth;
+ }
+}
+void unloadIntoByteStream(ImageData image) {
+ if (!new JPEGStartOfImage().writeToStream(outputStream)) {
+ SWT.error(SWT.ERROR_IO);
+ }
+ JPEGAppn appn = new JPEGAppn(new byte[] {(byte)0xFF, (byte)0xE0, 0, 0x10, 0x4A, 0x46, 0x49, 0x46, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0});
+ if (!appn.writeToStream(outputStream)) {
+ SWT.error(SWT.ERROR_IO);
+ }
+ quantizationTables = new int[4][];
+ JPEGQuantizationTable chromDQT = JPEGQuantizationTable.defaultChrominanceTable();
+ chromDQT.scaleBy(encoderQFactor);
+ int[] jpegDQTKeys = chromDQT.getQuantizationTablesKeys();
+ int[][] jpegDQTValues = chromDQT.getQuantizationTablesValues();
+ for (int i = 0; i < jpegDQTKeys.length; i++) {
+ quantizationTables[jpegDQTKeys[i]] = jpegDQTValues[i];
+ }
+ JPEGQuantizationTable lumDQT = JPEGQuantizationTable.defaultLuminanceTable();
+ lumDQT.scaleBy(encoderQFactor);
+ jpegDQTKeys = lumDQT.getQuantizationTablesKeys();
+ jpegDQTValues = lumDQT.getQuantizationTablesValues();
+ for (int i = 0; i < jpegDQTKeys.length; i++) {
+ quantizationTables[jpegDQTKeys[i]] = jpegDQTValues[i];
+ }
+ if (!lumDQT.writeToStream(outputStream)) {
+ SWT.error(SWT.ERROR_IO);
+ }
+ if (!chromDQT.writeToStream(outputStream)) {
+ SWT.error(SWT.ERROR_IO);
+ }
+ int frameLength, scanLength, precision;
+ int[][] frameParams, scanParams;
+ if (image.depth == 1) {
+ frameLength = 11;
+ frameParams = new int[1][];
+ frameParams[0] = new int[] {1, 1, 1, 0, 0};
+ scanParams = new int[1][];
+ scanParams[0] = new int[] {0, 0};
+ scanLength = 8;
+ nComponents = 1;
+ precision = 1;
+ } else {
+ frameLength = 17;
+ frameParams = new int[3][];
+ frameParams[0] = new int[] {0, 2, 2, 0, 0};
+ frameParams[1] = new int[] {1, 1, 1, 0, 0};
+ frameParams[2] = new int[] {1, 1, 1, 0, 0};
+ scanParams = new int[3][];
+ scanParams[0] = new int[] {0, 0};
+ scanParams[1] = new int[] {1, 1};
+ scanParams[2] = new int[] {1, 1};
+ scanLength = 12;
+ nComponents = 3;
+ precision = 8;
+ }
+ imageWidth = image.width;
+ imageHeight = image.height;
+ frameHeader = new JPEGFrameHeader(new byte[19]);
+ frameHeader.setSegmentMarker(SOF0);
+ frameHeader.setSegmentLength(frameLength);
+ frameHeader.setSamplePrecision(precision);
+ frameHeader.setSamplesPerLine(imageWidth);
+ frameHeader.setNumberOfLines(imageHeight);
+ frameHeader.setNumberOfImageComponents(nComponents);
+ frameHeader.componentParameters = frameParams;
+ frameHeader.initializeContents();
+ if (!frameHeader.writeToStream(outputStream)) {
+ SWT.error(SWT.ERROR_IO);
+ }
+ frameComponents = frameParams;
+ maxH = frameHeader.getMaxHFactor();
+ maxV = frameHeader.getMaxVFactor();
+ int mcuWidth = maxH * DCTSIZE;
+ int mcuHeight = maxV * DCTSIZE;
+ interleavedMcuCols = (imageWidth + mcuWidth - 1) / mcuWidth;
+ interleavedMcuRows = (imageHeight + mcuHeight - 1) / mcuHeight;
+ JPEGHuffmanTable[] acHuffmanTables = new JPEGHuffmanTable[4];
+ JPEGHuffmanTable[] dcHuffmanTables = new JPEGHuffmanTable[4];
+ JPEGHuffmanTable[] dhtTables = new JPEGHuffmanTable[] {
+ JPEGHuffmanTable.getDefaultDCLuminanceTable(),
+ JPEGHuffmanTable.getDefaultDCChrominanceTable(),
+ JPEGHuffmanTable.getDefaultACLuminanceTable(),
+ JPEGHuffmanTable.getDefaultACChrominanceTable()
+ };
+ for (int i = 0; i < dhtTables.length; i++) {
+ JPEGHuffmanTable dhtTable = dhtTables[i];
+ if (!dhtTable.writeToStream(outputStream)) {
+ SWT.error(SWT.ERROR_IO);
+ }
+ JPEGHuffmanTable[] allTables = dhtTable.getAllTables();
+ for (int j = 0; j < allTables.length; j++) {
+ JPEGHuffmanTable huffmanTable = allTables[j];
+ if (huffmanTable.getTableClass() == 0) {
+ dcHuffmanTables[huffmanTable.getTableIdentifier()] = huffmanTable;
+ } else {
+ acHuffmanTables[huffmanTable.getTableIdentifier()] = huffmanTable;
+ }
+ }
+ }
+ precedingDCs = new int[4];
+ scanHeader = new JPEGScanHeader(new byte[14]);
+ scanHeader.setSegmentMarker(SOS);
+ scanHeader.setSegmentLength(scanLength);
+ scanHeader.setNumberOfImageComponents(nComponents);
+ scanHeader.setStartOfSpectralSelection(0);
+ scanHeader.setEndOfSpectralSelection(63);
+ scanHeader.componentParameters = scanParams;
+ scanHeader.initializeContents();
+ if (!scanHeader.writeToStream(outputStream)) {
+ SWT.error(SWT.ERROR_IO);
+ }
+ convertImageToYCbCr(image);
+ resetOutputBuffer();
+ currentByte = 0;
+ currentBitCount = 0;
+ encodeScan();
+ if (!new JPEGEndOfImage().writeToStream(outputStream)) {
+ SWT.error(SWT.ERROR_IO);
+ }
+}
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGFixedSizeSegment.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGFixedSizeSegment.java
new file mode 100755
index 0000000000..9bf9191e51
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGFixedSizeSegment.java
@@ -0,0 +1,38 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+import org.eclipse.swt.*;
+
+abstract class JPEGFixedSizeSegment extends JPEGSegment {
+
+ public JPEGFixedSizeSegment() {
+ reference = new byte[fixedSize()];
+ setSegmentMarker(signature());
+ }
+
+ public JPEGFixedSizeSegment(byte[] reference) {
+ super(reference);
+ }
+
+ public JPEGFixedSizeSegment(LEDataInputStream byteStream) {
+ reference = new byte[fixedSize()];
+ try {
+ byteStream.read(reference);
+ } catch (Exception e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ }
+
+ abstract public int fixedSize();
+
+ public int getSegmentLength() {
+ return fixedSize() - 2;
+ }
+
+ public void setSegmentLength(int length) {
+ }
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGFrameHeader.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGFrameHeader.java
new file mode 100755
index 0000000000..be2cf6c6d3
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGFrameHeader.java
@@ -0,0 +1,203 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+import org.eclipse.swt.*;
+
+final class JPEGFrameHeader extends JPEGVariableSizeSegment {
+ int maxVFactor;
+ int maxHFactor;
+ public int[][] componentParameters;
+
+ public JPEGFrameHeader(byte[] reference) {
+ super(reference);
+ }
+
+ public JPEGFrameHeader(LEDataInputStream byteStream) {
+ super(byteStream);
+ initializeComponentParameters();
+ }
+
+ public int getSamplePrecision() {
+ return reference[4] & 0xFF;
+ }
+
+ public int getNumberOfLines() {
+ return (reference[5] & 0xFF) << 8 | (reference[6] & 0xFF);
+ }
+
+ public int getSamplesPerLine() {
+ return (reference[7] & 0xFF) << 8 | (reference[8] & 0xFF);
+ }
+
+ public int getNumberOfImageComponents() {
+ return reference[9] & 0xFF;
+ }
+
+ public void setSamplePrecision(int precision) {
+ reference[4] = (byte)(precision & 0xFF);
+ }
+
+ public void setNumberOfLines(int anInteger) {
+ reference[5] = (byte)((anInteger & 0xFF00) >> 8);
+ reference[6] = (byte)(anInteger & 0xFF);
+ }
+
+ public void setSamplesPerLine(int samples) {
+ reference[7] = (byte)((samples & 0xFF00) >> 8);
+ reference[8] = (byte)(samples & 0xFF);
+ }
+
+ public void setNumberOfImageComponents(int anInteger) {
+ reference[9] = (byte)(anInteger & 0xFF);
+ }
+
+ public int getMaxHFactor() {
+ return maxHFactor;
+ }
+
+ public int getMaxVFactor() {
+ return maxVFactor;
+ }
+
+ public void setMaxHFactor(int anInteger) {
+ maxHFactor = anInteger;
+ }
+
+ public void setMaxVFactor(int anInteger) {
+ maxVFactor = anInteger;
+ }
+
+ void initializeComponentParameters() {
+ int nf = getNumberOfImageComponents();
+ int[][] compSpecParams = new int[0][];
+ int hmax = 1;
+ int vmax = 1;
+ for (int i = 0; i < nf; i++) {
+ int ofs = i * 3 + 10;
+ int ci = reference[ofs] & 0xFF;
+ int hi = (reference[ofs + 1] & 0xFF) / 16;
+ int vi = (reference[ofs + 1] & 0xFF) % 16;
+ int tqi = reference[ofs + 2] & 0xFF;
+ if (hi > hmax) {
+ hmax = hi;
+ }
+ if (vi > vmax) {
+ vmax = vi;
+ }
+ int[] compParam = new int[5];
+ compParam[0] = tqi;
+ compParam[1] = hi;
+ compParam[2] = vi;
+ if (compSpecParams.length < ci) {
+ int[][] newParams = new int[ci][];
+ System.arraycopy(compSpecParams, 0, newParams, 0, compSpecParams.length);
+ compSpecParams = newParams;
+ }
+ compSpecParams[ci - 1] = compParam;
+ }
+ int x = getSamplesPerLine();
+ int y = getNumberOfLines();
+ int[] multiples = new int[] { 8, 16, 24, 32 };
+ for (int i = 0; i < compSpecParams.length; i++) {
+ int[] compParam = compSpecParams[i];
+ int hi = compParam[1];
+ int vi = compParam[2];
+ int compWidth = (x * hi + hmax - 1) / hmax;
+ int compHeight = (y * vi + vmax - 1) / vmax;
+ int dsWidth = roundUpToMultiple(compWidth, multiples[hi - 1]);
+ int dsHeight = roundUpToMultiple(compHeight, multiples[vi - 1]);
+ compParam[3] = dsWidth;
+ compParam[4] = dsHeight;
+ }
+ setMaxHFactor(hmax);
+ setMaxVFactor(vmax);
+ componentParameters = compSpecParams;
+ }
+
+ public void initializeContents() {
+ int nf = getNumberOfImageComponents();
+ if (nf == 0 || nf != componentParameters.length) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ int hmax = 0;
+ int vmax = 0;
+ int[][] compSpecParams = componentParameters;
+ for (int i = 0; i < nf; i++) {
+ int ofs = i * 3 + 10;
+ int[] compParam = compSpecParams[i];
+ int hi = compParam[1];
+ int vi = compParam[2];
+ if (hi * vi > 4) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ reference[ofs] = (byte)(i + 1);
+ reference[ofs + 1] = (byte)(hi * 16 + vi);
+ reference[ofs + 2] = (byte)(compParam[0]);
+ if (hi > hmax) hmax = hi;
+ if (vi > vmax) vmax = vi;
+ }
+ int x = getSamplesPerLine();
+ int y = getNumberOfLines();
+ int[] multiples = new int[] {8, 16, 24, 32};
+ for (int i = 0; i < compSpecParams.length; i++) {
+ int[] compParam = compSpecParams[i];
+ int hi = compParam[1];
+ int vi = compParam[2];
+ int compWidth = (x * hi + hmax - 1) / hmax;
+ int compHeight = (y * vi + vmax - 1) / vmax;
+ int dsWidth = roundUpToMultiple(compWidth, multiples[hi - 1]);
+ int dsHeight = roundUpToMultiple(compHeight, multiples[vi - 1]);
+ compParam[3] = dsWidth;
+ compParam[4] = dsHeight;
+ }
+ setMaxHFactor(hmax);
+ setMaxVFactor(vmax);
+ }
+
+ int roundUpToMultiple(int anInteger, int mInteger) {
+ int a = anInteger + mInteger - 1;
+ return a - (a % mInteger);
+ }
+
+ /*
+ * Verify the information contained in the receiver is correct.
+ * Answer true if the header contains a valid marker. Otherwise,
+ * answer false. Valid Start Of Frame markers are:
+ * SOF_0 - Baseline DCT, Huffman coding
+ * SOF_1 - Extended sequential DCT, Huffman coding
+ * SOF_2 - Progressive DCT, Huffman coding
+ * SOF_3 - Lossless (sequential), Huffman coding
+ * SOF_5 - Differential sequential, Huffman coding
+ * SOF_6 - Differential progressive, Huffman coding
+ * SOF_7 - Differential lossless, Huffman coding
+ * SOF_9 - Extended sequential DCT, arithmetic coding
+ * SOF_10 - Progressive DCT, arithmetic coding
+ * SOF_11 - Lossless (sequential), arithmetic coding
+ * SOF_13 - Differential sequential, arithmetic coding
+ * SOF_14 - Differential progressive, arithmetic coding
+ * SOF_15 - Differential lossless, arithmetic coding
+ */
+ public boolean verify() {
+ int marker = getSegmentMarker();
+ return (marker >= JPEGFileFormat.SOF0 && marker <= JPEGFileFormat.SOF3) ||
+ (marker >= JPEGFileFormat.SOF5 && marker <= JPEGFileFormat.SOF7) ||
+ (marker >= JPEGFileFormat.SOF9 && marker <= JPEGFileFormat.SOF11) ||
+ (marker >= JPEGFileFormat.SOF13 && marker <= JPEGFileFormat.SOF15);
+ }
+
+ public boolean isProgressive() {
+ int marker = getSegmentMarker();
+ return marker == JPEGFileFormat.SOF2
+ || marker == JPEGFileFormat.SOF6
+ || marker == JPEGFileFormat.SOF10
+ || marker == JPEGFileFormat.SOF14;
+ }
+
+ public boolean isArithmeticCoding() {
+ return getSegmentMarker() >= JPEGFileFormat.SOF9;
+ }
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGHuffmanTable.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGHuffmanTable.java
new file mode 100755
index 0000000000..fc50d691e9
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGHuffmanTable.java
@@ -0,0 +1,262 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+/**
+ * JPEGHuffmanTable class actually represents two types of object:
+ * 1) A DHT (Define Huffman Tables) segment, which may represent
+ * as many as 4 Huffman tables. In this case, the tables are
+ * stored in the allTables array.
+ * 2) A single Huffman table. In this case, the allTables array
+ * will be null.
+ * The 'reference' field is stored in both types of object, but
+ * 'initialize' is only called if the object represents a DHT.
+ */
+final class JPEGHuffmanTable extends JPEGVariableSizeSegment {
+ JPEGHuffmanTable[] allTables;
+ int tableClass;
+ int tableIdentifier;
+ int[] dhCodes;
+ int[] dhCodeLengths;
+ int[] dhMaxCodes;
+ int[] dhMinCodes;
+ int[] dhValPtrs;
+ int[] dhValues;
+ int[] ehCodes;
+ byte[] ehCodeLengths;
+ static byte[] DCLuminanceTable = {
+ (byte)255, (byte)196, 0, 31, 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
+ };
+ static byte[] DCChrominanceTable = {
+ (byte)255, (byte)196, 0, 31, 1, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
+ };
+ static byte[] ACLuminanceTable = {
+ (byte)255, (byte)196, 0, (byte)181, 16, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125,
+ 1, 2, 3, 0, 4, 17, 5, 18, 33, 49, 65, 6, 19, 81, 97, 7, 34, 113, 20,
+ 50, (byte)129, (byte)145, (byte)161, 8, 35, 66, (byte)177, (byte)193, 21, 82, (byte)209, (byte)240, 36, 51, 98,
+ 114, (byte)130, 9, 10, 22, 23, 24, 25, 26, 37, 38, 39, 40, 41, 42, 52, 53,
+ 54, 55, 56, 57, 58, 67, 68, 69, 70, 71, 72, 73, 74, 83, 84, 85, 86, 87,
+ 88, 89, 90, 99, 100, 101, 102, 103, 104, 105, 106, 115, 116, 117, 118,
+ 119, 120, 121, 122, (byte)131, (byte)132, (byte)133, (byte)134, (byte)135, (byte)136, (byte)137, (byte)138, (byte)146, (byte)147, (byte)148,
+ (byte)149, (byte)150, (byte)151, (byte)152, (byte)153, (byte)154, (byte)162, (byte)163, (byte)164, (byte)165, (byte)166, (byte)167, (byte)168, (byte)169, (byte)170,
+ (byte)178, (byte)179, (byte)180, (byte)181, (byte)182, (byte)183, (byte)184, (byte)185, (byte)186, (byte)194, (byte)195, (byte)196, (byte)197, (byte)198, (byte)199,
+ (byte)200, (byte)201, (byte)202, (byte)210, (byte)211, (byte)212, (byte)213, (byte)214, (byte)215, (byte)216, (byte)217, (byte)218, (byte)225, (byte)226, (byte)227,
+ (byte)228, (byte)229, (byte)230, (byte)231, (byte)232, (byte)233, (byte)234, (byte)241, (byte)242, (byte)243, (byte)244, (byte)245, (byte)246, (byte)247, (byte)248,
+ (byte)249, (byte)250
+ };
+ static byte[] ACChrominanceTable = {
+ (byte)255, (byte)196, 0, (byte)181, 17, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0,
+ 1, 2, 119, 0, 1, 2, 3, 17, 4, 5, 33, 49, 6, 18, 65, 81, 7, 97, 113, 19, 34,
+ 50, (byte)129, 8, 20, 66, (byte)145, (byte)161, (byte)177, (byte)193, 9, 35,
+ 51, 82, (byte)240, 21, 98, 114, (byte)209, 10, 22, 36, 52, (byte)225, 37,
+ (byte)241, 23, 24, 25, 26, 38, 39, 40, 41, 42, 53, 54, 55, 56, 57, 58, 67,
+ 68, 69, 70, 71, 72, 73, 74, 83, 84, 85, 86, 87, 88, 89, 90, 99, 100, 101, 102,
+ 103, 104, 105, 106, 115, 116, 117, 118, 119, 120, 121, 122, (byte)130,
+ (byte)131, (byte)132, (byte)133, (byte)134, (byte)135, (byte)136, (byte)137,
+ (byte)138, (byte)146, (byte)147, (byte)148, (byte)149, (byte)150, (byte)151,
+ (byte)152, (byte)153, (byte)154, (byte)162, (byte)163, (byte)164, (byte)165,
+ (byte)166, (byte)167, (byte)168, (byte)169, (byte)170, (byte)178, (byte)179,
+ (byte)180, (byte)181, (byte)182, (byte)183, (byte)184, (byte)185, (byte)186,
+ (byte)194, (byte)195, (byte)196, (byte)197, (byte)198, (byte)199, (byte)200,
+ (byte)201, (byte)202, (byte)210, (byte)211, (byte)212, (byte)213, (byte)214,
+ (byte)215, (byte)216, (byte)217, (byte)218, (byte)226, (byte)227, (byte)228,
+ (byte)229, (byte)230, (byte)231, (byte)232, (byte)233, (byte)234, (byte)242,
+ (byte)243, (byte)244, (byte)245, (byte)246, (byte)247, (byte)248, (byte)249,
+ (byte)250
+ };
+
+public JPEGHuffmanTable(byte[] reference) {
+ super(reference);
+}
+
+public JPEGHuffmanTable(LEDataInputStream byteStream) {
+ super(byteStream);
+ initialize();
+}
+
+public JPEGHuffmanTable[] getAllTables() {
+ return allTables;
+}
+
+public static JPEGHuffmanTable getDefaultACChrominanceTable() {
+ JPEGHuffmanTable result = new JPEGHuffmanTable(ACChrominanceTable);
+ result.initialize();
+ return result;
+}
+
+public static JPEGHuffmanTable getDefaultACLuminanceTable() {
+ JPEGHuffmanTable result = new JPEGHuffmanTable(ACLuminanceTable);
+ result.initialize();
+ return result;
+}
+
+public static JPEGHuffmanTable getDefaultDCChrominanceTable() {
+ JPEGHuffmanTable result = new JPEGHuffmanTable(DCChrominanceTable);
+ result.initialize();
+ return result;
+}
+
+public static JPEGHuffmanTable getDefaultDCLuminanceTable() {
+ JPEGHuffmanTable result = new JPEGHuffmanTable(DCLuminanceTable);
+ result.initialize();
+ return result;
+}
+
+public int[] getDhMaxCodes() {
+ return dhMaxCodes;
+}
+
+public int[] getDhMinCodes() {
+ return dhMinCodes;
+}
+
+public int[] getDhValPtrs() {
+ return dhValPtrs;
+}
+
+public int[] getDhValues() {
+ return dhValues;
+}
+
+public int getTableClass() {
+ return tableClass;
+}
+
+public int getTableIdentifier() {
+ return tableIdentifier;
+}
+
+void initialize() {
+ int totalLength = getSegmentLength() - 2;
+ int ofs = 4;
+ int[] bits = new int[16];
+ JPEGHuffmanTable[] huffTables = new JPEGHuffmanTable[8]; // maximum is 4 AC + 4 DC
+ int huffTableCount = 0;
+ while (totalLength > 0) {
+ int tc = (reference[ofs] & 0xFF) / 16; // table class: AC (1) or DC (0)
+ int tid = (reference[ofs] & 0xFF) % 16; // table id: 0-1 baseline, 0-3 prog/ext
+ ofs++;
+
+ /* Read the 16 count bytes and add them together to get the table size. */
+ int count = 0;
+ for (int i = 0; i < bits.length; i++) {
+ int bCount = reference[ofs + i] & 0xFF;
+ bits[i] = bCount;
+ count += bCount;
+ }
+ ofs += 16;
+ totalLength -= 17;
+
+ /* Read the table. */
+ int[] huffVals = new int[count];
+ for (int i = 0; i < count; i++) {
+ huffVals[i] = reference[ofs + i] & 0xFF;
+ }
+ ofs += count;
+ totalLength -= count;
+
+ /* Calculate the lengths. */
+ int[] huffCodeLengths = new int[50]; // start with 50 and increment as needed
+ int huffCodeLengthsIndex = 0;
+ for (int i = 0; i < 16; i++) {
+ for (int j = 0; j < bits[i]; j++) {
+ if (huffCodeLengthsIndex >= huffCodeLengths.length) {
+ int[] newHuffCodeLengths = new int[huffCodeLengths.length + 50];
+ System.arraycopy(huffCodeLengths, 0, newHuffCodeLengths, 0, huffCodeLengths.length);
+ huffCodeLengths = newHuffCodeLengths;
+ }
+ huffCodeLengths[huffCodeLengthsIndex] = i + 1;
+ huffCodeLengthsIndex++;
+ }
+ }
+
+ /* Truncate huffCodeLengths to the correct size. */
+ if (huffCodeLengthsIndex < huffCodeLengths.length) {
+ int[] newHuffCodeLengths = new int[huffCodeLengthsIndex];
+ System.arraycopy(huffCodeLengths, 0, newHuffCodeLengths, 0, huffCodeLengthsIndex);
+ huffCodeLengths = newHuffCodeLengths;
+ }
+
+ /* Calculate the Huffman codes. */
+ int[] huffCodes = new int[50]; // start with 50 and increment as needed
+ int huffCodesIndex = 0;
+ int k = 1;
+ int code = 0;
+ int si = huffCodeLengths[0];
+ int p = 0;
+ while (p < huffCodeLengthsIndex) {
+ while ((p < huffCodeLengthsIndex) && (huffCodeLengths[p] == si)) {
+ if (huffCodesIndex >= huffCodes.length) {
+ int[] newHuffCodes = new int[huffCodes.length + 50];
+ System.arraycopy(huffCodes, 0, newHuffCodes, 0, huffCodes.length);
+ huffCodes = newHuffCodes;
+ }
+ huffCodes[huffCodesIndex] = code;
+ huffCodesIndex++;
+ code++;
+ p++;
+ }
+ code *= 2;
+ si++;
+ }
+
+ /* Truncate huffCodes to the correct size. */
+ if (huffCodesIndex < huffCodes.length) {
+ int[] newHuffCodes = new int[huffCodesIndex];
+ System.arraycopy(huffCodes, 0, newHuffCodes, 0, huffCodesIndex);
+ huffCodes = newHuffCodes;
+ }
+
+ /* Calculate the maximum and minimum codes */
+ k = 0;
+ int[] maxCodes = new int[16];
+ int[] minCodes = new int[16];
+ int[] valPtrs = new int[16];
+ for (int i = 0; i < 16; i++) {
+ int bSize = bits[i];
+ if (bSize == 0) {
+ maxCodes[i] = -1;
+ } else {
+ valPtrs[i] = k;
+ minCodes[i] = huffCodes[k];
+ k += bSize;
+ maxCodes[i] = huffCodes[k - 1];
+ }
+ }
+
+ /* Calculate the eHuffman codes and lengths. */
+ int[] eHuffCodes = new int[256];
+ byte[] eHuffSize = new byte[256];
+ for (int i = 0; i < huffCodesIndex; i++) {
+ eHuffCodes[huffVals[i]] = huffCodes[i];
+ eHuffSize[huffVals[i]] = (byte)huffCodeLengths[i];
+ }
+
+ /* Create the new JPEGHuffmanTable and add it to the allTables array. */
+ JPEGHuffmanTable dhtTable = new JPEGHuffmanTable(reference);
+ dhtTable.tableClass = tc;
+ dhtTable.tableIdentifier = tid;
+ dhtTable.dhValues = huffVals;
+ dhtTable.dhCodes = huffCodes;
+ dhtTable.dhCodeLengths = huffCodeLengths;
+ dhtTable.dhMinCodes = minCodes;
+ dhtTable.dhMaxCodes = maxCodes;
+ dhtTable.dhValPtrs = valPtrs;
+ dhtTable.ehCodes = eHuffCodes;
+ dhtTable.ehCodeLengths = eHuffSize;
+ huffTables[huffTableCount] = dhtTable;
+ huffTableCount++;
+ }
+ allTables = new JPEGHuffmanTable[huffTableCount];
+ System.arraycopy(huffTables, 0, allTables, 0, huffTableCount);
+}
+
+public int signature() {
+ return JPEGFileFormat.DHT;
+}
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGQuantizationTable.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGQuantizationTable.java
new file mode 100755
index 0000000000..47405a44c6
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGQuantizationTable.java
@@ -0,0 +1,159 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+final class JPEGQuantizationTable extends JPEGVariableSizeSegment {
+ public static byte[] DefaultLuminanceQTable = {
+ (byte)255, (byte)219, 0, 67, 0,
+ 16, 11, 10, 16, 24, 40, 51, 61,
+ 12, 12, 14, 19, 26, 58, 60, 55,
+ 14, 13, 16, 24, 40, 57, 69, 56,
+ 14, 17, 22, 29, 51, 87, 80, 62,
+ 18, 22, 37, 56, 68, 109, 103, 77,
+ 24, 35, 55, 64, 81, 104, 113, 92,
+ 49, 64, 78, 87, 103, 121, 120, 101,
+ 72, 92, 95, 98, 112, 100, 103, 99
+ };
+ public static byte[] DefaultChrominanceQTable = {
+ (byte)255, (byte)219, 0, 67, 1,
+ 17, 18, 24, 47, 99, 99, 99, 99,
+ 18, 21, 26, 66, 99, 99, 99, 99,
+ 24, 26, 56, 99, 99, 99, 99, 99,
+ 47, 66, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99
+ };
+
+public JPEGQuantizationTable(byte[] reference) {
+ super(reference);
+}
+
+public JPEGQuantizationTable(LEDataInputStream byteStream) {
+ super(byteStream);
+}
+
+public static JPEGQuantizationTable defaultChrominanceTable() {
+ byte[] data = new byte[DefaultChrominanceQTable.length];
+ System.arraycopy(DefaultChrominanceQTable, 0, data, 0, data.length);
+ return new JPEGQuantizationTable(data);
+}
+
+public static JPEGQuantizationTable defaultLuminanceTable() {
+ byte[] data = new byte[DefaultLuminanceQTable.length];
+ System.arraycopy(DefaultLuminanceQTable, 0, data, 0, data.length);
+ return new JPEGQuantizationTable(data);
+}
+
+public int[] getQuantizationTablesKeys() {
+ int[] keys = new int[4];
+ int keysIndex = 0;
+ int totalLength = getSegmentLength() - 2;
+ int ofs = 4;
+ while (totalLength > 64) {
+ int tq = (reference[ofs] & 0xFF) % 16;
+ int pq = (reference[ofs] & 0xFF) / 16;
+ if (pq == 0) {
+ ofs += 65;
+ totalLength -= 65;
+ } else {
+ ofs += 129;
+ totalLength -= 129;
+ }
+ if (keysIndex >= keys.length) {
+ int[] newKeys = new int[keys.length + 4];
+ System.arraycopy(keys, 0, newKeys, 0, keys.length);
+ keys = newKeys;
+ }
+ keys[keysIndex] = tq;
+ keysIndex++;
+ }
+ int[] newKeys = new int[keysIndex];
+ System.arraycopy(keys, 0, newKeys, 0, keysIndex);
+ return newKeys;
+}
+
+public int[][] getQuantizationTablesValues() {
+ int[][] values = new int[4][];
+ int valuesIndex = 0;
+ int totalLength = getSegmentLength() - 2;
+ int ofs = 4;
+ while (totalLength > 64) {
+ int[] qk = new int[64];
+ int pq = (reference[ofs] & 0xFF) / 16;
+ if (pq == 0) {
+ for (int i = 0; i < qk.length; i++) {
+ qk[i] = reference[ofs + i + 1];
+ }
+ ofs += 65;
+ totalLength -= 65;
+ } else {
+ for (int i = 0; i < qk.length; i++) {
+ int idx = (i - 1) * 2 ;
+ qk[i] = (reference[ofs + idx + 1] & 0xFF) * 256 + (reference[ofs + idx + 2] & 0xFF);
+ }
+ ofs += 129;
+ totalLength -= 129;
+ }
+ if (valuesIndex >= values.length) {
+ int[][] newValues = new int[values.length + 4][];
+ System.arraycopy(values, 0, newValues, 0, values.length);
+ values = newValues;
+ }
+ values[valuesIndex] = qk;
+ valuesIndex++;
+ }
+ int[][] newValues = new int[valuesIndex][];
+ System.arraycopy(values, 0, newValues, 0, valuesIndex);
+ return newValues;
+}
+
+public void scaleBy(int qualityFactor) {
+ int qFactor = qualityFactor;
+ if (qFactor <= 0) {
+ qFactor = 1;
+ }
+ if (qFactor > 100) {
+ qFactor = 100;
+ }
+ if (qFactor < 50) {
+ qFactor = 5000 / qFactor;
+ } else {
+ qFactor = 200 - (qFactor * 2);
+ }
+ int totalLength = getSegmentLength() - 2;
+ int ofs = 4;
+ while (totalLength > 64) {
+ int tq = (reference[ofs] & 0xFF) % 16;
+ int pq = (reference[ofs] & 0xFF) / 16;
+ if (pq == 0) {
+ for (int i = ofs + 1; i <= ofs + 64; i++) {
+ int temp = ((reference[i] & 0xFF) * qFactor + 50) / 100;
+ if (temp <= 0) temp = 1;
+ if (temp > 255) temp = 255;
+ reference[i] = (byte)temp;
+ }
+ ofs += 65;
+ totalLength -= 65;
+ } else {
+ for (int i = ofs + 1; i <= ofs + 128; i += 2) {
+ int temp = (((reference[i] & 0xFF) * 256 + (reference[i + 1] & 0xFF)) * qFactor + 50) / 100;
+ if (temp <= 0) temp = 1;
+ if (temp > 32767) temp = 32767;
+ reference[i] = (byte)(temp / 256);
+ reference[i + 1] = (byte)(temp % 256);
+ }
+ ofs += 129;
+ totalLength -= 129;
+ }
+ }
+}
+
+public int signature() {
+ return JPEGFileFormat.DQT;
+}
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGRestartInterval.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGRestartInterval.java
new file mode 100755
index 0000000000..242d5d924d
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGRestartInterval.java
@@ -0,0 +1,25 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+final class JPEGRestartInterval extends JPEGFixedSizeSegment {
+
+ public JPEGRestartInterval(LEDataInputStream byteStream) {
+ super(byteStream);
+ }
+
+ public int signature() {
+ return JPEGFileFormat.DRI;
+ }
+
+ public int getRestartInterval() {
+ return ((reference[4] & 0xFF) << 8 | (reference[5] & 0xFF));
+ }
+
+ public int fixedSize() {
+ return 6;
+ }
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGScanHeader.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGScanHeader.java
new file mode 100755
index 0000000000..4e087fb951
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGScanHeader.java
@@ -0,0 +1,117 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+import org.eclipse.swt.*;
+
+final class JPEGScanHeader extends JPEGVariableSizeSegment {
+ public int[][] componentParameters;
+
+public JPEGScanHeader(byte[] reference) {
+ super(reference);
+}
+
+public JPEGScanHeader(LEDataInputStream byteStream) {
+ super(byteStream);
+ initializeComponentParameters();
+}
+
+public int getApproxBitPositionHigh() {
+ return (reference[(2 * getNumberOfImageComponents()) + 7] & 0xFF) / 16;
+}
+
+public int getApproxBitPositionLow() {
+ return (reference[(2 * getNumberOfImageComponents()) + 7] & 0xFF) % 16;
+}
+
+public int getEndOfSpectralSelection() {
+ return (reference[(2 * getNumberOfImageComponents()) + 6] & 0xFF);
+}
+
+public int getNumberOfImageComponents() {
+ return (reference[4] & 0xFF);
+}
+
+public int getStartOfSpectralSelection() {
+ return (reference[(2 * getNumberOfImageComponents()) + 5] & 0xFF);
+}
+
+/* Used when decoding. */
+void initializeComponentParameters() {
+ int compCount = getNumberOfImageComponents();
+ componentParameters = new int[0][];
+ for (int i = 0; i < compCount; i++) {
+ int ofs = 5 + i * 2;
+ int cid = reference[ofs] & 0xFF;
+ int dc = (reference[ofs + 1] & 0xFF) / 16;
+ int ac = (reference[ofs + 1] & 0xFF) % 16;
+ if (componentParameters.length < cid) {
+ int[][] newParams = new int[cid][];
+ System.arraycopy(componentParameters, 0, newParams, 0, componentParameters.length);
+ componentParameters = newParams;
+ }
+ componentParameters[cid - 1] = new int[] { dc, ac };
+ }
+}
+
+/* Used when encoding. */
+public void initializeContents() {
+ int compCount = getNumberOfImageComponents();
+ int[][] compSpecParams = componentParameters;
+ if (compCount == 0 || compCount != compSpecParams.length) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ for (int i = 0; i < compCount; i++) {
+ int ofs = i * 2 + 5;
+ int[] compParams = compSpecParams[i];
+ reference[ofs] = (byte)(i + 1);
+ reference[ofs + 1] = (byte)(compParams[0] * 16 + compParams[1]);
+ }
+}
+
+public void setEndOfSpectralSelection(int anInteger) {
+ reference[(2 * getNumberOfImageComponents()) + 6] = (byte)anInteger;
+}
+
+public void setNumberOfImageComponents(int anInteger) {
+ reference[4] = (byte)(anInteger & 0xFF);
+}
+
+public void setStartOfSpectralSelection(int anInteger) {
+ reference[(2 * getNumberOfImageComponents()) + 5] = (byte)anInteger;
+}
+
+public int signature() {
+ return JPEGFileFormat.SOS;
+}
+
+public boolean verifyProgressiveScan() {
+ int start = getStartOfSpectralSelection();
+ int end = getEndOfSpectralSelection();
+ int low = getApproxBitPositionLow();
+ int high = getApproxBitPositionHigh();
+ int count = getNumberOfImageComponents();
+ if ((start == 0 && end == 00) || (start <= end && end <= 63)) {
+ if (low <= 13 && high <= 13 && (high == 0 || high == low + 1)) {
+ return start == 0 || (start > 0 && count == 1);
+ }
+ }
+ return false;
+}
+
+public boolean isACProgressiveScan() {
+ return getStartOfSpectralSelection() != 0 && getEndOfSpectralSelection() != 0;
+}
+
+public boolean isDCProgressiveScan() {
+ return getStartOfSpectralSelection() == 0 && getEndOfSpectralSelection() == 0;
+}
+
+public boolean isFirstScan() {
+ return getApproxBitPositionHigh() == 0;
+}
+
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGSegment.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGSegment.java
new file mode 100755
index 0000000000..4f41a6a98b
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGSegment.java
@@ -0,0 +1,54 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+import org.eclipse.swt.*;
+
+class JPEGSegment {
+ public byte[] reference;
+
+ JPEGSegment() {
+ }
+
+ public JPEGSegment(byte[] reference) {
+ this.reference = reference;
+ }
+
+ public int signature() {
+ return 0;
+ }
+
+ public boolean verify() {
+ return getSegmentMarker() == signature();
+ }
+
+ public int getSegmentMarker() {
+ return ((reference[0] & 0xFF) << 8 | (reference[1] & 0xFF));
+ }
+
+ public void setSegmentMarker(int marker) {
+ reference[0] = (byte)((marker & 0xFF00) >> 8);
+ reference[1] = (byte)(marker & 0xFF);
+ }
+
+ public int getSegmentLength() {
+ return ((reference[2] & 0xFF) << 8 | (reference[3] & 0xFF));
+ }
+
+ public void setSegmentLength(int length) {
+ reference[2] = (byte)((length & 0xFF00) >> 8);
+ reference[3] = (byte)(length & 0xFF);
+ }
+
+ public boolean writeToStream(LEDataOutputStream byteStream) {
+ try {
+ byteStream.write(reference);
+ return true;
+ } catch (Exception e) {
+ return false;
+ }
+ }
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGStartOfImage.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGStartOfImage.java
new file mode 100755
index 0000000000..4a487d421b
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGStartOfImage.java
@@ -0,0 +1,29 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+final class JPEGStartOfImage extends JPEGFixedSizeSegment {
+
+ public JPEGStartOfImage() {
+ super();
+ }
+
+ public JPEGStartOfImage(byte[] reference) {
+ super(reference);
+ }
+
+ public JPEGStartOfImage(LEDataInputStream byteStream) {
+ super(byteStream);
+ }
+
+ public int signature() {
+ return JPEGFileFormat.SOI;
+ }
+
+ public int fixedSize() {
+ return 2;
+ }
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGVariableSizeSegment.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGVariableSizeSegment.java
new file mode 100755
index 0000000000..7b96ed1aac
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/JPEGVariableSizeSegment.java
@@ -0,0 +1,32 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+import org.eclipse.swt.*;
+
+abstract class JPEGVariableSizeSegment extends JPEGSegment {
+
+ public JPEGVariableSizeSegment(byte[] reference) {
+ super(reference);
+ }
+
+ public JPEGVariableSizeSegment(LEDataInputStream byteStream) {
+ try {
+ byte[] header = new byte[4];
+ byteStream.read(header);
+ reference = header; // to use getSegmentLength()
+ byte[] contents = new byte[getSegmentLength() + 2];
+ contents[0] = header[0];
+ contents[1] = header[1];
+ contents[2] = header[2];
+ contents[3] = header[3];
+ byteStream.read(contents, 4, contents.length - 4);
+ reference = contents;
+ } catch (Exception e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ }
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LEDataInputStream.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LEDataInputStream.java
new file mode 100755
index 0000000000..46e843d4c0
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LEDataInputStream.java
@@ -0,0 +1,88 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp 2000
+ */
+
+import java.io.*;
+
+final class LEDataInputStream extends InputStream {
+ int position;
+ PushbackInputStream in;
+
+ public LEDataInputStream(InputStream input) {
+ this(input, 512);
+ }
+
+ public LEDataInputStream(InputStream input, int bufferSize) {
+ this.in = new PushbackInputStream(input, bufferSize);
+ }
+
+ public void close() throws IOException {
+ in.close();
+ }
+
+ /**
+ * Answer how many bytes were read.
+ */
+ public int getPosition() {
+ return position;
+ }
+
+ /**
+ * Answer the next byte of the input stream.
+ */
+ public int read() throws IOException {
+ position++;
+ return in.read();
+ }
+
+ /**
+ * Don't imitate the JDK behaviour of reading a random number
+ * of bytes when you can actually read them all.
+ */
+ public int read(byte b[], int off, int len) throws IOException {
+ int result;
+ int left = len;
+ result = in.read(b, off, len);
+ while (true) {
+ if (result == -1)
+ return -1;
+ position += result;
+ if (result == left)
+ return len;
+ left -= result;
+ off += result;
+ result = in.read(b, off, left);
+ }
+ }
+
+ /**
+ * Answer an integer comprised of the next
+ * four bytes of the input stream.
+ */
+ public int readInt() throws IOException {
+ byte[] buf = new byte[4];
+ read(buf);
+ return ((((((buf[3] & 0xFF) << 8) |
+ (buf[2] & 0xFF)) << 8) |
+ (buf[1] & 0xFF)) << 8) |
+ (buf[0] & 0xFF);
+ }
+
+ /**
+ * Answer a short comprised of the next
+ * two bytes of the input stream.
+ */
+ public short readShort() throws IOException {
+ byte[] buf = new byte[2];
+ read(buf);
+ return (short)(((buf[1] & 0xFF) << 8) | (buf[0] & 0xFF));
+ }
+
+ public void unread(byte[] b) throws IOException {
+ position -= b.length;
+ in.unread(b);
+ }
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LEDataOutputStream.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LEDataOutputStream.java
new file mode 100755
index 0000000000..7859012ca8
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LEDataOutputStream.java
@@ -0,0 +1,54 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * WebSphere Studio Workbench
+ * (c) Copyright IBM Corp 2000
+ */
+
+/* Imports */
+import java.io.*;
+
+/* Class Definition */
+final class LEDataOutputStream extends OutputStream {
+ OutputStream out;
+public LEDataOutputStream(OutputStream output) {
+ this.out = output;
+}
+public void close() throws IOException {
+ out.close();
+}
+public void write(byte b[], int off, int len) throws IOException {
+ out.write(b, off, len);
+}
+/**
+ * Answer the next byte of the input stream.
+ */
+public void write(int b) throws IOException {
+ out.write(b);
+}
+/**
+ * Answer the next byte of the input stream.
+ */
+public void writeByte(byte b) throws IOException {
+ out.write(b & 0xFF);
+}
+/**
+ * Answer an integer comprised of the next
+ * four bytes of the input stream.
+ */
+public void writeInt(int theInt) throws IOException {
+ out.write(theInt & 0xFF);
+ out.write((theInt >> 8) & 0xFF);
+ out.write((theInt >> 16) & 0xFF);
+ out.write((theInt >> 24) & 0xFF);
+}
+/**
+ * Answer an integer comprised of the next
+ * two bytes of the input stream.
+ */
+public void writeShort(int theShort) throws IOException {
+ out.write(theShort & 0xFF);
+ out.write((theShort >> 8) & 0xFF);
+}
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LZWCodec.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LZWCodec.java
new file mode 100755
index 0000000000..fcf71f81a9
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LZWCodec.java
@@ -0,0 +1,479 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * WebSphere Studio Workbench
+ * (c) Copyright IBM Corp 2000
+ */
+
+/* Imports */
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+
+/* Class Definition */
+final class LZWCodec {
+ int bitsPerPixel, blockSize, blockIndex, currentByte, bitsLeft,
+ codeSize, clearCode, endCode, newCodes, topSlot, currentSlot,
+ imageWidth, imageHeight, imageX, imageY, pass, line, codeMask, buffer;
+ byte[] block, lineArray;
+ int[] maskTable, stack, suffix, prefix;
+ LZWNode[] nodeStack;
+ LEDataInputStream inputStream;
+ LEDataOutputStream outputStream;
+ ImageData image;
+ ImageLoader loader;
+ boolean interlaced;
+/**
+ * Decode the input.
+ */
+void decode() {
+ int code;
+ int oc = 0;
+ int fc = 0;
+ byte[] buf = new byte[imageWidth];
+ int stackIndex = 0;
+ int bufIndex = 0;
+ int c;
+ while ((c = nextCode()) != endCode) {
+ if (c == clearCode) {
+ codeSize = bitsPerPixel + 1;
+ codeMask = maskTable[bitsPerPixel];
+ currentSlot = newCodes;
+ topSlot = 1 << codeSize;
+ while ((c = nextCode()) == clearCode) {};
+ if (c != endCode) {
+ oc = fc = c;
+ buf[bufIndex] = (byte)c;
+ bufIndex++;
+ if (bufIndex == imageWidth) {
+ nextPutPixels(buf);
+ bufIndex = 0;
+ }
+ }
+ } else {
+ code = c;
+ if (code >= currentSlot) {
+ if (code > currentSlot)
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ code = oc;
+ stack[stackIndex] = fc;
+ stackIndex++;
+ }
+ while (code >= newCodes) {
+ stack[stackIndex] = suffix[code];
+ stackIndex++;
+ code = prefix[code];
+ }
+ stack[stackIndex] = code;
+ stackIndex++;
+ if (currentSlot < topSlot) {
+ fc = code;
+ suffix[currentSlot] = fc;
+ prefix[currentSlot] = oc;
+ currentSlot++;
+ oc = c;
+ }
+ if (currentSlot >= topSlot) {
+ if (codeSize < 12) {
+ codeMask = maskTable[codeSize];
+ codeSize++;
+ topSlot = topSlot + topSlot;
+ }
+ }
+ while (stackIndex > 0) {
+ stackIndex--;
+ buf[bufIndex] = (byte)stack[stackIndex];
+ bufIndex++;
+ if (bufIndex == imageWidth) {
+ nextPutPixels(buf);
+ bufIndex = 0;
+ }
+ }
+ }
+ }
+ if (bufIndex != 0 && line < imageHeight) {
+ nextPutPixels(buf);
+ }
+}
+/**
+ * Decode the LZW-encoded bytes in the given byte stream
+ * into the given DeviceIndependentImage.
+ */
+public void decode(LEDataInputStream inputStream, ImageLoader loader, ImageData image, boolean interlaced, int depth) {
+ this.inputStream = inputStream;
+ this.loader = loader;
+ this.image = image;
+ this.interlaced = interlaced;
+ this.bitsPerPixel = depth;
+ initializeForDecoding();
+ decode();
+}
+/**
+ * Encode the image.
+ */
+void encode() {
+ nextPutCode(clearCode);
+ int lastPrefix = encodeLoop();
+ nextPutCode(lastPrefix);
+ nextPutCode(endCode);
+
+ // Write out last partial block
+ if (bitsLeft == 8) {
+ block[0] = (byte)(blockIndex - 1); // Nothing in last byte
+ } else {
+ block[0] = (byte)(blockIndex); // Last byte has data
+ }
+ writeBlock();
+
+ // Write out empty block to indicate the end (if needed)
+ if (block[0] != 0) {
+ block[0] = 0;
+ writeBlock();
+ }
+}
+/**
+ * Encode the bytes into the given byte stream
+ * from the given DeviceIndependentImage.
+ */
+public void encode(LEDataOutputStream byteStream, ImageData image) {
+ this.outputStream = byteStream;
+ this.image = image;
+ initializeForEncoding();
+ encode();
+}
+/**
+ * Encoding loop broken out to allow early return.
+ */
+int encodeLoop() {
+ int pixel = nextPixel();
+ boolean found;
+ LZWNode node;
+ while (true) {
+ int currentPrefix = pixel;
+ node = nodeStack[currentPrefix];
+ found = true;
+ pixel = nextPixel();
+ if (pixel < 0)
+ return currentPrefix;
+ while (found && (node.children != null)) {
+ node = node.children;
+ while (found && (node.suffix != pixel)) {
+ if (pixel < node.suffix) {
+ if (node.left == null) {
+ node.left = new LZWNode();
+ found = false;
+ }
+ node = node.left;
+ } else {
+ if (node.right == null) {
+ node.right = new LZWNode();
+ found = false;
+ }
+ node = node.right;
+ }
+ }
+ if (found) {
+ currentPrefix = node.code;
+ pixel = nextPixel();
+ if (pixel < 0)
+ return currentPrefix;
+ }
+ }
+ if (found) {
+ node.children = new LZWNode();
+ node = node.children;
+ }
+ node.children = null;
+ node.left = null;
+ node.right = null;
+ node.code = currentSlot;
+ node.prefix = currentPrefix;
+ node.suffix = pixel;
+ nextPutCode(currentPrefix);
+ currentSlot++;
+ // Off by one?
+ if (currentSlot < 4096) {
+ if (currentSlot > topSlot) {
+ codeSize++;
+ codeMask = maskTable[codeSize - 1];
+ topSlot *= 2;
+ }
+ } else {
+ nextPutCode(clearCode);
+ for (int i = 0; i < nodeStack.length; i++)
+ nodeStack[i].children = null;
+ codeSize = bitsPerPixel + 1;
+ codeMask = maskTable[codeSize - 1];
+ currentSlot = newCodes;
+ topSlot = 1 << codeSize;
+ }
+ }
+}
+/**
+ * Initialize the receiver for decoding the given
+ * byte array.
+ */
+void initializeForDecoding() {
+ pass = 1;
+ line = 0;
+ codeSize = bitsPerPixel + 1;
+ topSlot = 1 << codeSize;
+ clearCode = 1 << bitsPerPixel;
+ endCode = clearCode + 1;
+ newCodes = currentSlot = endCode + 1;
+ currentByte = -1;
+ blockSize = bitsLeft = 0;
+ blockIndex = 0;
+ maskTable = new int[] {
+ 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F,
+ 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF
+ };
+ codeMask = maskTable[codeSize - 1];
+ stack = new int[4096];
+ suffix = new int[4096];
+ prefix = new int[4096];
+ block = new byte[256];
+ imageWidth = image.width;
+ imageHeight = image.height;
+}
+/**
+ * Initialize the receiver for encoding the given
+ * byte array.
+ */
+void initializeForEncoding() {
+ interlaced = false;
+ bitsPerPixel = image.depth;
+ codeSize = bitsPerPixel + 1;
+ topSlot = 1 << codeSize;
+ clearCode = 1 << bitsPerPixel;
+ endCode = clearCode + 1;
+ newCodes = currentSlot = endCode + 1;
+ bitsLeft = 8;
+ currentByte = 0;
+ blockIndex = 1;
+ blockSize = 255;
+ block = new byte[blockSize];
+ block[0] = (byte)(blockSize - 1);
+ maskTable = new int[] {
+ 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F,
+ 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF
+ };
+ nodeStack = new LZWNode[1 << bitsPerPixel];
+ for (int i = 0; i < nodeStack.length; i++) {
+ LZWNode node = new LZWNode();
+ node.code = i + 1;
+ node.prefix = -1;
+ node.suffix = i + 1;
+ nodeStack[i] = node;
+ }
+ imageWidth = image.width;
+ imageHeight = image.height;
+ imageY = -1;
+ lineArray = new byte[imageWidth];
+ imageX = imageWidth + 1; // Force a read
+}
+/**
+ * Answer the next code from the input byte array.
+ */
+int nextCode() {
+ int code;
+ if (bitsLeft == 0) {
+ if (blockIndex >= blockSize) {
+ blockSize = readBlock();
+ blockIndex = 0;
+ if (blockSize == 0) return endCode;
+ }
+ blockIndex++;
+ currentByte = block[blockIndex] & 0xFF;
+ bitsLeft = 8;
+ code = currentByte;
+ } else {
+ int shift = bitsLeft - 8;
+ if (shift < 0)
+ code = currentByte >> (0 - shift);
+ else
+ code = currentByte << shift;
+ }
+ while (codeSize > bitsLeft) {
+ if (blockIndex >= blockSize) {
+ blockSize = readBlock();
+ blockIndex = 0;
+ if (blockSize == 0) return endCode;
+ }
+ blockIndex++;
+ currentByte = block[blockIndex] & 0xFF;
+ code += currentByte << bitsLeft;
+ bitsLeft += 8;
+ }
+ bitsLeft -= codeSize;
+ return code & codeMask;
+}
+/**
+ * Answer the next pixel to encode in the image
+ */
+int nextPixel() {
+ imageX++;
+ if (imageX > imageWidth) {
+ imageY++;
+ if (imageY >= imageHeight) {
+ return -1;
+ } else {
+ nextPixels(lineArray, imageWidth);
+ }
+ imageX = 1;
+ }
+ return this.lineArray[imageX - 1] & 0xFF;
+}
+/**
+ * Copy a row of pixel values from the image.
+ */
+void nextPixels(byte[] buf, int lineWidth) {
+ if (image.depth == 8) {
+ System.arraycopy(image.data, imageY * image.bytesPerLine, buf, 0, lineWidth);
+ } else {
+ image.getPixels(0, imageY, lineWidth, buf, 0);
+ }
+}
+/**
+ * Output aCode to the output stream.
+ */
+void nextPutCode(int aCode) {
+ int codeToDo = aCode;
+ int codeBitsToDo = codeSize;
+ // Fill in the remainder of the current byte with the
+ // *high-order* bits of the code.
+ int c = codeToDo & maskTable[bitsLeft - 1];
+ currentByte = currentByte | (c << (8 - bitsLeft));
+ block[blockIndex] = (byte)currentByte;
+ codeBitsToDo -= bitsLeft;
+ if (codeBitsToDo < 1) {
+ // The whole code fit in the first byte, so we are done.
+ bitsLeft -= codeSize;
+ if (bitsLeft == 0) {
+ // We used the whole last byte, so get ready
+ // for the next one.
+ bitsLeft = 8;
+ blockIndex++;
+ if (blockIndex >= blockSize) {
+ writeBlock();
+ blockIndex = 1;
+ }
+ currentByte = 0;
+ }
+ return;
+ }
+ codeToDo = codeToDo >> bitsLeft;
+
+ // Fill in any remaining whole bytes (i.e. not the last one!)
+ blockIndex++;
+ if (blockIndex >= blockSize) {
+ writeBlock();
+ blockIndex = 1;
+ }
+ while (codeBitsToDo >= 8) {
+ currentByte = codeToDo & 0xFF;
+ block[blockIndex] = (byte)currentByte;
+ codeToDo = codeToDo >> 8;
+ codeBitsToDo -= 8;
+ blockIndex++;
+ if (blockIndex >= blockSize) {
+ writeBlock();
+ blockIndex = 1;
+ }
+ }
+ // Fill the *low-order* bits of the last byte with the remainder
+ bitsLeft = 8 - codeBitsToDo;
+ currentByte = codeToDo;
+ block[blockIndex] = (byte)currentByte;
+}
+/**
+ * Copy a row of pixel values to the image.
+ */
+void nextPutPixels(byte[] buf) {
+ if (image.depth == 8) {
+ // Slight optimization for depth = 8.
+ int start = line * image.bytesPerLine;
+ for (int i = 0; i < imageWidth; i++)
+ image.data[start + i] = buf[i];
+ } else {
+ image.setPixels(0, line, imageWidth, buf, 0);
+ }
+ if (interlaced) {
+ if (pass == 1) {
+ copyRow(buf, 7);
+ line += 8;
+ } else if (pass == 2) {
+ copyRow(buf, 3);
+ line += 8;
+ } else if (pass == 3) {
+ copyRow(buf, 1);
+ line += 4;
+ } else if (pass == 4) {
+ line += 2;
+ } else if (pass == 5) {
+ line += 0;
+ }
+ if (line >= imageHeight) {
+ pass++;
+ if (pass == 2) line = 4;
+ else if (pass == 3) line = 2;
+ else if (pass == 4) line = 1;
+ else if (pass == 5) line = 0;
+ if (pass < 5) {
+ if (loader.hasListeners()) {
+ ImageData imageCopy = (ImageData) image.clone();
+ loader.notifyListeners(
+ new ImageLoaderEvent(loader, imageCopy, pass - 2, false));
+ }
+ }
+ }
+ if (line >= imageHeight) line = 0;
+ } else {
+ line++;
+ }
+}
+/**
+ * Copy duplicate rows of pixel values to the image.
+ * This is to fill in rows if the image is interlaced.
+ */
+void copyRow(byte[] buf, int copies) {
+ for (int i = 1; i <= copies; i++) {
+ if (line + i < imageHeight) {
+ image.setPixels(0, line + i, imageWidth, buf, 0);
+ }
+ }
+}
+/**
+ * Read a block from the byte stream.
+ * Return the number of bytes read.
+ * Throw an exception if the block could not be read.
+ */
+int readBlock() {
+ int size = -1;
+ try {
+ size = inputStream.read();
+ if (size == -1) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ block[0] = (byte)size;
+ size = inputStream.read(block, 1, size);
+ if (size == -1) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ } catch (Exception e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ return size;
+}
+/**
+ * Write a block to the byte stream.
+ * Throw an exception if the block could not be written.
+ */
+void writeBlock() {
+ try {
+ outputStream.write(block, 0, (block[0] & 0xFF) + 1);
+ } catch (Exception e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+}
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LZWNode.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LZWNode.java
new file mode 100755
index 0000000000..d4d3d4b680
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/LZWNode.java
@@ -0,0 +1,13 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * WebSphere Studio Workbench
+ * (c) Copyright IBM Corp 2000
+ */
+
+/* Class Definition */
+final class LZWNode {
+ public LZWNode left, right, children;
+ public int code, prefix, suffix;
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PNGFileFormat.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PNGFileFormat.java
new file mode 100755
index 0000000000..6a9413bdb9
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PNGFileFormat.java
@@ -0,0 +1,525 @@
+package org.eclipse.swt.internal.image;
+
+import java.io.*;
+import java.util.*;
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * WebSphere Studio Workbench
+ * (c) Copyright IBM Corp 2000
+ */
+public class PNGFileFormat extends FileFormat {
+ static final int SIGNATURE_LENGTH = 8;
+ PngDecodingDataStream decodingStream;
+ PngIhdrChunk headerChunk;
+ PngPlteChunk paletteChunk;
+ PngTrnsChunk trnsChunk;
+ ImageData imageData;
+ byte[] data;
+ byte[] alphaPalette;
+
+/**
+ * Skip over signature data. This has already been
+ * verified in isPNGFile().
+ */
+void readSignature() throws IOException {
+ byte[] signature = new byte[SIGNATURE_LENGTH];
+ inputStream.read(signature);
+}
+/**
+ * Load the PNG image from the byte stream.
+ */
+ImageData[] loadFromByteStream() {
+ try {
+ readSignature();
+ PngChunkReader chunkReader = new PngChunkReader(inputStream);
+ headerChunk = chunkReader.getIhdrChunk();
+ int imageSize = getAlignedBytesPerRow() * headerChunk.getHeight();
+ data = new byte[imageSize];
+ imageData = ImageData.internal_new(
+ headerChunk.getWidth(),
+ headerChunk.getHeight(),
+ headerChunk.getSwtBitsPerPixel(),
+ new PaletteData(0, 0, 0),
+ 4,
+ data,
+ 0,
+ null,
+ null,
+ -1,
+ -1,
+ SWT.IMAGE_PNG,
+ 0,
+ 0,
+ 0,
+ 0);
+
+ if (headerChunk.usesDirectColor()) {
+ imageData.palette = headerChunk.getPaletteData();
+ };
+
+ // Read and process chunks until the IEND chunk is encountered.
+ while (chunkReader.hasMoreChunks()) {
+ readNextChunk(chunkReader);
+ }
+
+ return new ImageData[] {imageData};
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ return null;
+ }
+}
+/**
+ * Read and handle the next chunk of data from the
+ * PNG file.
+ */
+void readNextChunk(PngChunkReader chunkReader) {
+ PngChunk chunk = chunkReader.readNextChunk();
+ switch (chunk.getChunkType()) {
+ case PngChunk.CHUNK_IEND:
+ break;
+ case PngChunk.CHUNK_PLTE:
+ if (!headerChunk.usesDirectColor()) {
+ paletteChunk = (PngPlteChunk) chunk;
+ imageData.palette = paletteChunk.getPaletteData();
+ };
+ break;
+ case PngChunk.CHUNK_tRNS:
+ PngTrnsChunk trnsChunk = (PngTrnsChunk) chunk;
+ if (trnsChunk.getTransparencyType(headerChunk) ==
+ PngTrnsChunk.TRANSPARENCY_TYPE_PIXEL)
+ {
+ imageData.transparentPixel =
+ trnsChunk.getSwtTransparentPixel(headerChunk);
+ } else {
+ alphaPalette = trnsChunk.getAlphaValues(headerChunk, paletteChunk);
+ }
+ break;
+ case PngChunk.CHUNK_IDAT:
+ if (chunkReader.readPixelData()) {
+ // All IDAT chunks in an image file must be
+ // sequential. If the pixel data has already
+ // been read and another IDAT block is encountered,
+ // then this is an invalid image.
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ } else {
+ // Read in the pixel data for the image. This should
+ // go through all the image's IDAT chunks.
+ PngIdatChunk dataChunk = (PngIdatChunk) chunk;
+ readPixelData(dataChunk, chunkReader);
+ }
+ break;
+ default:
+ if (chunk.isCritical()) {
+ // All critical chunks must be supported.
+ SWT.error(SWT.ERROR_NOT_IMPLEMENTED);
+ }
+ }
+}
+void unloadIntoByteStream(ImageData p1) {
+ SWT.error(SWT.ERROR_NOT_IMPLEMENTED);
+}
+/**
+ * Answer whether the specified input stream
+ * contains a PNG image.
+ */
+public static boolean isPNGFile(LEDataInputStream stream) {
+ try {
+ byte[] signature = new byte[SIGNATURE_LENGTH];
+ stream.read(signature);
+ stream.unread(signature);
+ if ((signature[0] & 0xFF) != 137) return false; //137
+ if ((signature[1] & 0xFF) != 80) return false; //P
+ if ((signature[2] & 0xFF) != 78) return false; //N
+ if ((signature[3] & 0xFF) != 71) return false; //G
+ if ((signature[4] & 0xFF) != 13) return false; //<RETURN>
+ if ((signature[5] & 0xFF) != 10) return false; //<LINEFEED>
+ if ((signature[6] & 0xFF) != 26) return false; //<CTRL/Z>
+ if ((signature[7] & 0xFF) != 10) return false; //<LINEFEED>
+ return true;
+ } catch (Exception e) {
+ return false;
+ }
+}
+/**
+ * SWT does not support 16-bit depths. If this image uses
+ * 16-bit depths, convert the data to an 8-bit depth.
+ */
+byte[] validateBitDepth(byte[] data) {
+ if (headerChunk.getBitDepth() > 8) {
+ byte[] result = new byte[data.length / 2];
+ compress16BitDepthTo8BitDepth(data, 0, result, 0, result.length);
+ return result;
+ } else {
+ return data;
+ }
+}
+/**
+ * SWT does not support greyscale as a color type. For
+ * plain grayscale, we create a palette. For Grayscale
+ * with Alpha, however, we need to convert the pixels
+ * to use RGB values.
+ * Note: This method assumes that the bit depth of the
+ * data has already been restricted to 8 or less.
+ */
+void setPixelData(byte[] data, ImageData imageData) {
+ switch (headerChunk.getColorType()) {
+ case PngIhdrChunk.COLOR_TYPE_GRAYSCALE_WITH_ALPHA:
+ {
+ int width = imageData.width;
+ int height = imageData.height;
+ int destBytesPerLine = imageData.bytesPerLine;
+ int srcBytesPerLine = width * 2;
+ byte[] rgbData = new byte[destBytesPerLine * height];
+ byte[] alphaData = new byte[width * height];
+ for (int y = 0; y < height; y++) {
+ int srcIndex = srcBytesPerLine * y;
+ int destIndex = destBytesPerLine * y;
+ int destAlphaIndex = width * y;
+ for (int x = 0; x < width; x++) {
+ byte grey = data[srcIndex];
+ byte alpha = data[srcIndex + 1];
+ rgbData[destIndex + 0] = grey;
+ rgbData[destIndex + 1] = grey;
+ rgbData[destIndex + 2] = grey;
+ alphaData[destAlphaIndex] = alpha;
+ srcIndex += 2;
+ destIndex += 3;
+ destAlphaIndex++;
+ }
+ }
+ imageData.data = rgbData;
+ imageData.alphaData = alphaData;
+ break;
+ }
+ case PngIhdrChunk.COLOR_TYPE_RGB_WITH_ALPHA:
+ {
+ int width = imageData.width;
+ int height = imageData.height;
+ int destBytesPerLine = imageData.bytesPerLine;
+ int srcBytesPerLine = getAlignedBytesPerRow();
+ byte[] rgbData = new byte[destBytesPerLine * height];
+ byte[] alphaData = new byte[width * height];
+ for (int y = 0; y < height; y++) {
+ int srcIndex = srcBytesPerLine * y;
+ int destIndex = destBytesPerLine * y;
+ int destAlphaIndex = width * y;
+ for (int x = 0; x < width; x++) {
+ rgbData[destIndex + 0] = data[srcIndex + 0];
+ rgbData[destIndex + 1] = data[srcIndex + 1];
+ rgbData[destIndex + 2] = data[srcIndex + 2];
+ alphaData[destAlphaIndex] = data[srcIndex + 3];
+ srcIndex += 4;
+ destIndex += 3;
+ destAlphaIndex++;
+ }
+ }
+ imageData.data = rgbData;
+ imageData.alphaData = alphaData;
+ break;
+ }
+ case PngIhdrChunk.COLOR_TYPE_RGB:
+ imageData.data = data;
+ break;
+ case PngIhdrChunk.COLOR_TYPE_PALETTE:
+ imageData.data = data;
+ if (alphaPalette != null) {
+ int size = imageData.width * imageData.height;
+ byte[] alphaData = new byte[size];
+ byte[] pixelData = new byte[size];
+ imageData.getPixels(0, 0, size, pixelData, 0);
+ for (int i = 0; i < pixelData.length; i++) {
+ alphaData[i] = alphaPalette[pixelData[i] & 0xFF];
+ }
+ imageData.alphaData = alphaData;
+ }
+ break;
+ default:
+ imageData.data = data;
+ break;
+ }
+}
+/**
+ * PNG supports some color types and bit depths that are
+ * unsupported by SWT. If the image uses an unsupported
+ * color type (either of the gray scale types) or bit
+ * depth (16), convert the data to an SWT-supported
+ * format. Then assign the data into the ImageData given.
+ */
+void setImageDataValues(byte[] data, ImageData imageData) {
+ byte[] result = validateBitDepth(data);
+ setPixelData(result, imageData);
+}
+/**
+ * Read the image data from the data stream. This must handle
+ * decoding the data, filtering, and interlacing.
+ */
+void readPixelData(PngIdatChunk chunk, PngChunkReader chunkReader) {
+ decodingStream = new PngDecodingDataStream(chunk, chunkReader);
+ int interlaceMethod = headerChunk.getInterlaceMethod();
+ if (interlaceMethod == PngIhdrChunk.INTERLACE_METHOD_NONE) {
+ readNonInterlacedImage();
+ } else {
+ readInterlacedImage();
+ }
+ decodingStream.assertImageDataAtEnd();
+ decodingStream.checkAdler();
+}
+/**
+ * Answer the number of bytes in a word-aligned row of pixel data.
+ */
+int getAlignedBytesPerRow() {
+ return ((getBytesPerRow(headerChunk.getWidth()) + 3) / 4) * 4;
+}
+/**
+ * Answer the number of bytes in each row of the image
+ * data. Each PNG row is byte-aligned, so images with bit
+ * depths less than a byte may have unused bits at the
+ * end of each row. The value of these bits is undefined.
+ */
+int getBytesPerRow() {
+ return getBytesPerRow(headerChunk.getWidth());
+}
+/**
+ * Answer the number of bytes needed to represent a pixel.
+ * This value depends on the image's color type and bit
+ * depth.
+ * Note that this method rounds up if an image's pixel size
+ * isn't byte-aligned.
+ */
+int getBytesPerPixel() {
+ int bitsPerPixel = headerChunk.getBitsPerPixel();
+ return (bitsPerPixel + 7) / 8;
+}
+/**
+ * Answer the number of bytes in a row of the given pixel
+ * width. Each row is byte-aligned, so images with bit
+ * depths less than a byte may have unused bits at the
+ * end of each row. The value of these bits is undefined.
+ */
+int getBytesPerRow(int rowWidthInPixels) {
+ int bitsPerPixel = headerChunk.getBitsPerPixel();
+ int bitsPerRow = bitsPerPixel * rowWidthInPixels;
+ int bitsPerByte = 8;
+ return (bitsPerRow + (bitsPerByte - 1)) / bitsPerByte;
+}
+/**
+ * 1. Read one of the seven frames of interlaced data.
+ * 2. Update the imageData.
+ * 3. Notify the image loader's listeners of the frame load.
+ */
+void readInterlaceFrame(
+ int rowInterval,
+ int columnInterval,
+ int startRow,
+ int startColumn,
+ int frameCount)
+{
+ int width = headerChunk.getWidth();
+ int alignedBytesPerRow = getAlignedBytesPerRow();
+ int height = headerChunk.getHeight();
+ if (startRow >= height || startColumn >= width) return;
+
+ int pixelsPerRow = (width - startColumn + columnInterval - 1) / columnInterval;
+ int bytesPerRow = getBytesPerRow(pixelsPerRow);
+ byte[] row1 = new byte[bytesPerRow];
+ byte[] row2 = new byte[bytesPerRow];
+ byte[] currentRow = row1;
+ byte[] lastRow = row2;
+ for (int row = startRow; row < height; row += rowInterval) {
+ byte filterType = decodingStream.getNextDecodedByte();
+ for (int col = 0; col < bytesPerRow; col++) {
+ currentRow[col] = decodingStream.getNextDecodedByte();
+ }
+ filterRow(currentRow, lastRow, filterType);
+ if (headerChunk.getBitDepth() >= 8) {
+ int bytesPerPixel = getBytesPerPixel();
+ int dataOffset = (row * alignedBytesPerRow) + (startColumn * bytesPerPixel);
+ for (int rowOffset = 0; rowOffset < currentRow.length; rowOffset += bytesPerPixel) {
+ for (int byteOffset = 0; byteOffset < bytesPerPixel; byteOffset++) {
+ data[dataOffset + byteOffset] = currentRow[rowOffset + byteOffset];
+ }
+ dataOffset += (columnInterval * bytesPerPixel);
+ }
+ } else {
+ int bitsPerPixel = headerChunk.getBitDepth();
+ int pixelsPerByte = 8 / bitsPerPixel;
+ int column = startColumn;
+ int rowBase = row * alignedBytesPerRow;
+ int valueMask = 0;
+ for (int i = 0; i < bitsPerPixel; i++) {
+ valueMask <<= 1;
+ valueMask |= 1;
+ }
+ int maxShift = 8 - bitsPerPixel;
+ for (int byteOffset = 0; byteOffset < currentRow.length; byteOffset++) {
+ for (int bitOffset = maxShift; bitOffset >= 0; bitOffset -= bitsPerPixel) {
+ if (column < width) {
+ int dataOffset = rowBase + (column * bitsPerPixel / 8);
+ int value = (currentRow[byteOffset] >> bitOffset) & valueMask;
+ int dataShift = maxShift - (bitsPerPixel * (column % pixelsPerByte));
+ data[dataOffset] |= value << dataShift;
+ }
+ column += columnInterval;
+ }
+ }
+ }
+ currentRow = (currentRow == row1) ? row2 : row1;
+ lastRow = (lastRow == row1) ? row2 : row1;
+ }
+ setImageDataValues(data, imageData);
+ fireInterlacedFrameEvent(frameCount);
+}
+/**
+ * Read the pixel data for an interlaced image from the
+ * data stream.
+ */
+void readInterlacedImage() {
+ readInterlaceFrame(8, 8, 0, 0, 0);
+ readInterlaceFrame(8, 8, 0, 4, 1);
+ readInterlaceFrame(8, 4, 4, 0, 2);
+ readInterlaceFrame(4, 4, 0, 2, 3);
+ readInterlaceFrame(4, 2, 2, 0, 4);
+ readInterlaceFrame(2, 2, 0, 1, 5);
+ readInterlaceFrame(2, 1, 1, 0, 6);
+}
+/**
+ * Fire an event to let listeners know that an interlaced
+ * frame has been loaded.
+ * finalFrame should be true if the image has finished
+ * loading, false if there are more frames to come.
+ */
+void fireInterlacedFrameEvent(int frameCount) {
+ if (loader.hasListeners()) {
+ ImageData image = (ImageData) imageData.clone();
+ boolean finalFrame = frameCount == 6;
+ loader.notifyListeners(new ImageLoaderEvent(loader, image, frameCount, finalFrame));
+ }
+}
+/**
+ * Read the pixel data for a non-interlaced image from the
+ * data stream.
+ * Update the imageData to reflect the new data.
+ */
+void readNonInterlacedImage() {
+ int dataOffset = 0;
+ int alignedBytesPerRow = getAlignedBytesPerRow();
+ int bytesPerRow = getBytesPerRow();
+ byte[] row1 = new byte[bytesPerRow];
+ byte[] row2 = new byte[bytesPerRow];
+ byte[] currentRow = row1;
+ byte[] lastRow = row2;
+ for (int row = 0; row < headerChunk.getHeight(); row++) {
+ byte filterType = decodingStream.getNextDecodedByte();
+ for (int col = 0; col < bytesPerRow; col++) {
+ currentRow[col] = decodingStream.getNextDecodedByte();
+ }
+ filterRow(currentRow, lastRow, filterType);
+ System.arraycopy(currentRow, 0, data, dataOffset, bytesPerRow);
+ dataOffset += alignedBytesPerRow;
+ currentRow = (currentRow == row1) ? row2 : row1;
+ lastRow = (lastRow == row1) ? row2 : row1;
+ }
+ setImageDataValues(data, imageData);
+}
+/**
+ * SWT does not support 16-bit depth color formats.
+ * Convert the 16-bit data to 8-bit data.
+ * The correct way to do this is to multiply each
+ * 16 bit value by the value:
+ * (2^8 - 1) / (2^16 - 1).
+ * The fast way to do this is just to drop the low
+ * byte of the 16-bit value.
+ */
+static void compress16BitDepthTo8BitDepth(
+ byte[] source,
+ int sourceOffset,
+ byte[] destination,
+ int destinationOffset,
+ int numberOfValues)
+{
+ //double multiplier = (Math.pow(2, 8) - 1) / (Math.pow(2, 16) - 1);
+ for (int i = 0; i < numberOfValues; i++) {
+ int sourceIndex = sourceOffset + (2 * i);
+ int destinationIndex = destinationOffset + i;
+ //int value = (source[sourceIndex] << 8) | source[sourceIndex + 1];
+ //byte compressedValue = (byte)(value * multiplier);
+ byte compressedValue = source[sourceIndex];
+ destination[destinationIndex] = compressedValue;
+ }
+}
+/**
+ * SWT does not support 16-bit depth color formats.
+ * Convert the 16-bit data to 8-bit data.
+ * The correct way to do this is to multiply each
+ * 16 bit value by the value:
+ * (2^8 - 1) / (2^16 - 1).
+ * The fast way to do this is just to drop the low
+ * byte of the 16-bit value.
+ */
+static int compress16BitDepthTo8BitDepth(int value) {
+ //double multiplier = (Math.pow(2, 8) - 1) / (Math.pow(2, 16) - 1);
+ //byte compressedValue = (byte)(value * multiplier);
+ return value >> 8;
+}
+/**
+ * PNG supports four filtering types. These types are applied
+ * per row of image data. This method unfilters the given row
+ * based on the filterType.
+ */
+void filterRow(byte[] row, byte[] previousRow, int filterType) {
+ int byteOffset = headerChunk.getFilterByteOffset();
+ switch (filterType) {
+ case PngIhdrChunk.FILTER_NONE:
+ break;
+ case PngIhdrChunk.FILTER_SUB:
+ for (int i = byteOffset; i < row.length; i++) {
+ int current = row[i] & 0xFF;
+ int left = row[i - byteOffset] & 0xFF;
+ row[i] = (byte)((current + left) & 0xFF);
+ }
+ break;
+ case PngIhdrChunk.FILTER_UP:
+ for (int i = 0; i < row.length; i++) {
+ int current = row[i] & 0xFF;
+ int above = previousRow[i] & 0xFF;
+ row[i] = (byte)((current + above) & 0xFF);
+ }
+ break;
+ case PngIhdrChunk.FILTER_AVERAGE:
+ for (int i = 0; i < row.length; i++) {
+ int left = (i < byteOffset) ? 0 : row[i - byteOffset] & 0xFF;
+ int above = previousRow[i] & 0xFF;
+ int current = row[i] & 0xFF;
+ row[i] = (byte)((current + ((left + above) / 2)) & 0xFF);
+ }
+ break;
+ case PngIhdrChunk.FILTER_PAETH:
+ for (int i = 0; i < row.length; i++) {
+ int left = (i < byteOffset) ? 0 : row[i - byteOffset] & 0xFF;
+ int aboveLeft = (i < byteOffset) ? 0 : previousRow[i - byteOffset] & 0xFF;
+ int above = previousRow[i] & 0xFF;
+
+ int a = Math.abs(above - aboveLeft);
+ int b = Math.abs(left - aboveLeft);
+ int c = Math.abs(left - aboveLeft + above - aboveLeft);
+
+ int preductor = 0;
+ if (a <= b && a <= c) {
+ preductor = left;
+ } else if (b <= c) {
+ preductor = above;
+ } else {
+ preductor = aboveLeft;
+ }
+
+ int currentValue = row[i] & 0xFF;
+ row[i] = (byte) ((currentValue + preductor) & 0xFF);
+ }
+ break;
+ }
+}
+
+} \ No newline at end of file
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngChunk.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngChunk.java
new file mode 100755
index 0000000000..1715ebccb1
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngChunk.java
@@ -0,0 +1,333 @@
+package org.eclipse.swt.internal.image;
+
+import org.eclipse.swt.*;
+import java.io.*;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp. 1998, 2000 All Rights Reserved
+ */
+
+class PngChunk extends Object {
+ byte[] reference;
+
+ static final int LENGTH_OFFSET = 0;
+ static final int TYPE_OFFSET = 4;
+ static final int DATA_OFFSET = 8;
+
+ static final int TYPE_FIELD_LENGTH = 4;
+ static final int LENGTH_FIELD_LENGTH = 4;
+ static final int MIN_LENGTH = 12;
+
+ static int[] crcTable;
+
+ static final int CHUNK_UNKNOWN = -1;
+ // Critical chunks.
+ static final int CHUNK_IHDR = 0;
+ static final int CHUNK_PLTE = 1;
+ static final int CHUNK_IDAT = 2;
+ static final int CHUNK_IEND = 3;
+ // Non-critical chunks.
+ static final int CHUNK_tRNS = 5;
+
+ static final byte[] TYPE_IHDR = {(byte) 'I', (byte) 'H', (byte) 'D', (byte) 'R'};
+ static final byte[] TYPE_PLTE = {(byte) 'P', (byte) 'L', (byte) 'T', (byte) 'E'};
+ static final byte[] TYPE_IDAT = {(byte) 'I', (byte) 'D', (byte) 'A', (byte) 'T'};
+ static final byte[] TYPE_IEND = {(byte) 'I', (byte) 'E', (byte) 'N', (byte) 'D'};
+ static final byte[] TYPE_tRNS = {(byte) 't', (byte) 'R', (byte) 'N', (byte) 'S'};
+
+/**
+ * Construct a PngChunk using the reference bytes
+ * given.
+ */
+PngChunk(byte[] reference) {
+ super();
+ setReference(reference);
+}
+
+/**
+ * Get the PngChunk's reference byteArray;
+ */
+byte[] getReference() {
+ return reference;
+}
+
+/**
+ * Set the PngChunk's reference byteArray;
+ */
+void setReference(byte[] reference) {
+ this.reference = reference;
+}
+
+/**
+ * Get the 32-bit integer from the reference byte
+ * array at the given offset.
+ */
+int getInt32(int offset) {
+ int answer = 0;
+ answer |= (reference[offset] & 0xFF) << 24;
+ answer |= (reference[offset + 1] & 0xFF) << 16;
+ answer |= (reference[offset + 2] & 0xFF) << 8;
+ answer |= (reference[offset + 3] & 0xFF);
+ return answer;
+}
+
+/**
+ * Set the 32-bit integer in the reference byte
+ * array at the given offset.
+ */
+void setInt32(int offset, int value) {
+ reference[offset] = (byte) ((value >> 24) & 0xFF);
+ reference[offset + 1] = (byte) ((value >> 16) & 0xFF);
+ reference[offset + 2] = (byte) ((value >> 8) & 0xFF);
+ reference[offset + 3] = (byte) (value & 0xFF);
+}
+
+/**
+ * Get the length of the data component of this chunk.
+ * This is not the length of the entire chunk.
+ */
+int getLength() {
+ return getInt32(LENGTH_OFFSET);
+}
+
+/**
+ * Set the length of the data component of this chunk.
+ * This is not the length of the entire chunk.
+ */
+void setLength(int value) {
+ setInt32(LENGTH_OFFSET, value);
+}
+
+/**
+ * Get the chunk type. This is a four byte value.
+ * Each byte should be an ASCII character.
+ * The first byte is upper case if the chunk is critical.
+ * The second byte is upper case if the chunk is publicly defined.
+ * The third byte must be upper case.
+ * The fourth byte is upper case if the chunk is unsafe to copy.
+ * Public chunk types are defined by the PNG Development Group.
+ */
+byte[] getTypeBytes() {
+ byte[] type = new byte[4];
+ System.arraycopy(reference, TYPE_OFFSET, type, 0, TYPE_FIELD_LENGTH);
+ return type;
+}
+
+/**
+ * Set the chunk type. This is a four byte value.
+ * Each byte should be an ASCII character.
+ * The first byte is upper case if the chunk is critical.
+ * The second byte is upper case if the chunk is publicly defined.
+ * The third byte must be upper case.
+ * The fourth byte is upper case if the chunk is unsafe to copy.
+ * Public chunk types are defined by the PNG Development Group.
+ */
+void setType(byte[] value) {
+ if (value.length != TYPE_FIELD_LENGTH) {
+ throw new SWTException(SWT.ERROR_INVALID_ARGUMENT);
+ }
+ System.arraycopy(value, 0, reference, TYPE_OFFSET, TYPE_FIELD_LENGTH);
+}
+
+/**
+ * Get the chunk's data.
+ */
+byte[] getData() {
+ int dataLength = getLength();
+ if (reference.length < MIN_LENGTH + dataLength) {
+ throw new SWTException(SWT.ERROR_INVALID_RANGE);
+ }
+ byte[] data = new byte[dataLength];
+ System.arraycopy(reference, DATA_OFFSET, data, 0, dataLength);
+ return data;
+}
+
+/**
+ * Set the chunk's data.
+ * This method has two side-effects.
+ * 1. It will set the length field to be the length
+ * of the data array given.
+ * 2. It will set the CRC field to the computed CRC
+ * value of the data array given.
+ */
+void setData(byte[] data) {
+ setLength(data.length);
+ System.arraycopy(data, 0, reference, DATA_OFFSET, data.length);
+ setCRC(computeCRC());
+}
+
+/**
+ * Get the CRC value for the chunk's data.
+ * Ensure that the length field has a good
+ * value before making this call.
+ */
+int getCRC() {
+ int crcOffset = DATA_OFFSET + getLength();
+ return getInt32(crcOffset);
+}
+
+/**
+ * Set the CRC value for the chunk's data.
+ * Ensure that the length field has a good
+ * value before making this call.
+ */
+void setCRC(int value) {
+ int crcOffset = DATA_OFFSET + getLength();
+ setInt32(crcOffset, value);
+}
+
+/**
+ * Get the chunk's total size including the length, type, and crc fields.
+ */
+int getSize() {
+ return MIN_LENGTH + getLength();
+}
+
+/**
+ * Compute the CRC value for the chunk's data. Answer
+ * whether this value matches the value stored in the
+ * chunk.
+ */
+boolean checkCRC() {
+ int crc = computeCRC();
+ int storedCRC = getCRC();
+ return crc == storedCRC;
+}
+
+/**
+ * Answer the CRC value of chunk's data.
+ */
+int computeCRC() {
+ if (crcTable == null) {
+ crcTable = new int[256];
+ for (int i = 0; i < 256; i++) {
+ crcTable[i] = i;
+ for (int j = 0; j < 8; j++) {
+ if ((crcTable[i] & 0x1) == 0) {
+ crcTable[i] = (crcTable[i] >> 1) & 0x7FFFFFFF;
+ } else {
+ crcTable[i] = 0xEDB88320 ^ ((crcTable[i] >> 1) & 0x7FFFFFFF);
+ }
+ }
+ }
+ }
+ int crc = 0xFFFFFFFF;
+ int start = TYPE_OFFSET;
+ int stop = DATA_OFFSET + getLength();
+ for (int i = start; i < stop; i++) {
+ int index = (crc ^ reference[i]) & 0xFF;
+ crc = crcTable[index] ^ ((crc >> 8) & 0x00FFFFFF);
+ }
+ return ~crc;
+}
+
+boolean typeMatchesArray(byte[] array) {
+ for (int i = 0; i < TYPE_FIELD_LENGTH; i++) {
+ if (reference[TYPE_OFFSET + i] != array[i]){
+ return false;
+ }
+ }
+ return true;
+}
+
+boolean isCritical() {
+ return Character.isUpperCase((char) getTypeBytes()[0]);
+}
+
+int getChunkType() {
+ if (typeMatchesArray(TYPE_IHDR)) return CHUNK_IHDR;
+ if (typeMatchesArray(TYPE_PLTE)) return CHUNK_PLTE;
+ if (typeMatchesArray(TYPE_IDAT)) return CHUNK_IDAT;
+ if (typeMatchesArray(TYPE_IEND)) return CHUNK_IEND;
+ if (typeMatchesArray(TYPE_tRNS)) return CHUNK_tRNS;
+ return CHUNK_UNKNOWN;
+}
+
+
+
+
+/**
+ * Read the next PNG chunk from the input stream given.
+ * If unable to read a chunk, return null.
+ */
+static PngChunk readNextFromStream(LEDataInputStream stream) {
+ try {
+ int headerLength = LENGTH_FIELD_LENGTH + TYPE_FIELD_LENGTH;
+ byte[] headerBytes = new byte[headerLength];
+ int result = stream.read(headerBytes, 0, headerLength);
+ stream.unread(headerBytes);
+ if (result != headerLength) return null;
+
+ PngChunk tempChunk = new PngChunk(headerBytes);
+
+ int chunkLength = tempChunk.getSize();
+ byte[] chunk = new byte[chunkLength];
+ result = stream.read(chunk, 0, chunkLength);
+ if (result != chunkLength) return null;
+
+ switch (tempChunk.getChunkType()) {
+ case CHUNK_IHDR:
+ return new PngIhdrChunk(chunk);
+ case CHUNK_PLTE:
+ return new PngPlteChunk(chunk);
+ case CHUNK_IDAT:
+ return new PngIdatChunk(chunk);
+ case CHUNK_IEND:
+ return new PngIendChunk(chunk);
+ case CHUNK_tRNS:
+ return new PngTrnsChunk(chunk);
+ default:
+ return new PngChunk(chunk);
+ }
+ } catch (IOException e) {
+ return null;
+ }
+}
+
+/**
+ * Answer whether the chunk is a valid PNG chunk.
+ */
+void validate(PngFileReadState readState, PngIhdrChunk headerChunk) {
+ if (reference.length < MIN_LENGTH) SWT.error(SWT.ERROR_INVALID_IMAGE);
+
+ byte[] type = getTypeBytes();
+
+ // The third character MUST be upper case.
+ if (!Character.isUpperCase((char) type[2])) SWT.error(SWT.ERROR_INVALID_IMAGE);
+
+ // All characters must be letters.
+ for (int i = 0; i < TYPE_FIELD_LENGTH; i++) {
+ if (!Character.isLetter((char) type[i])) SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+
+ // The stored CRC must match the data's computed CRC.
+ if (!checkCRC()) SWT.error(SWT.ERROR_INVALID_IMAGE);
+}
+
+/**
+ * Provided so that subclasses can override and add
+ * data to the toString() call.
+ */
+void contributeToString(StringBuffer buffer) {}
+
+public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append("{");
+ buffer.append("\n\tLength: ");
+ buffer.append(getLength());
+ buffer.append("\n\tType: ");
+ byte[] type = getTypeBytes();
+ for(int i = 0; i < type.length; i++) {
+ buffer.append((char) type[i]);
+ }
+
+ contributeToString(buffer);
+
+ buffer.append("\n\tCRC: ");
+ buffer.append(Integer.toHexString(getCRC()));
+ buffer.append("\n}");
+ return buffer.toString();
+}
+
+} \ No newline at end of file
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngChunkReader.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngChunkReader.java
new file mode 100755
index 0000000000..f93b716697
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngChunkReader.java
@@ -0,0 +1,64 @@
+package org.eclipse.swt.internal.image;
+
+import org.eclipse.swt.*;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp. 1998, 2000 All Rights Reserved
+ */
+
+public class PngChunkReader {
+ LEDataInputStream inputStream;
+ PngFileReadState readState;
+ PngIhdrChunk headerChunk;
+ PngPlteChunk paletteChunk;
+
+PngChunkReader(LEDataInputStream inputStream) {
+ this.inputStream = inputStream;
+ readState = new PngFileReadState();
+ headerChunk = null;
+}
+
+PngIhdrChunk getIhdrChunk() {
+ if (headerChunk == null) {
+ try {
+ PngChunk chunk = PngChunk.readNextFromStream(inputStream);
+ headerChunk = (PngIhdrChunk) chunk;
+ headerChunk.validate(readState, null);
+ } catch (ClassCastException e) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ }
+ return headerChunk;
+}
+
+PngChunk readNextChunk() {
+ if (headerChunk == null) return getIhdrChunk();
+
+ PngChunk chunk = PngChunk.readNextFromStream(inputStream);
+ switch (chunk.getChunkType()) {
+ case PngChunk.CHUNK_tRNS:
+ ((PngTrnsChunk) chunk).validate(readState, headerChunk, paletteChunk);
+ break;
+ case PngChunk.CHUNK_PLTE:
+ chunk.validate(readState, headerChunk);
+ paletteChunk = (PngPlteChunk) chunk;
+ break;
+ default:
+ chunk.validate(readState, headerChunk);
+ }
+ if (readState.readIDAT && !(chunk.getChunkType() == PngChunk.CHUNK_IDAT)) {
+ readState.readPixelData = true;
+ }
+ return chunk;
+}
+
+boolean readPixelData() {
+ return readState.readPixelData;
+}
+
+boolean hasMoreChunks() {
+ return !readState.readIEND;
+}
+
+} \ No newline at end of file
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngDecodingDataStream.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngDecodingDataStream.java
new file mode 100755
index 0000000000..1800a2415b
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngDecodingDataStream.java
@@ -0,0 +1,131 @@
+package org.eclipse.swt.internal.image;
+
+import java.io.*;
+import org.eclipse.swt.*;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp. 1998, 2000 All Rights Reserved
+ */
+
+public class PngDecodingDataStream {
+ PngIdatChunk currentChunk;
+ PngChunkReader chunkReader;
+ byte currentByte;
+ int nextByteIndex;
+ int nextBitIndex;
+
+ PngLzBlockReader lzBlockReader;
+ int adlerValue;
+
+ static final int PRIME = 65521;
+ static final int MAX_BIT = 7;
+
+PngDecodingDataStream(PngIdatChunk idatChunk, PngChunkReader chunkReader) {
+ super();
+ this.currentChunk = idatChunk;
+ this.chunkReader = chunkReader;
+ nextByteIndex = 0;
+ nextBitIndex = MAX_BIT + 1;
+ adlerValue = 1;
+ lzBlockReader = new PngLzBlockReader(this);
+ readCompressedDataHeader();
+ lzBlockReader.readNextBlockHeader();
+}
+
+/**
+ * This method should be called when the image decoder thinks
+ * that all of the compressed image data has been read. This
+ * method will ensure that the next data value is an end of
+ * block marker. If there are more blocks after this one,
+ * the method will read them and ensure that they are empty.
+ */
+void assertImageDataAtEnd() {
+ lzBlockReader.assertCompressedDataAtEnd();
+}
+
+int getNextIdatBits(int length) {
+ int value = 0;
+ for (int i = 0; i < length; i++) {
+ value |= (getNextIdatBit() << i);
+ }
+ return value;
+}
+
+byte getNextIdatBit() {
+ if (nextBitIndex > MAX_BIT) {
+ currentByte = getNextIdatByte();
+ nextBitIndex = 0;
+ }
+ int mask = 1 << nextBitIndex;
+ nextBitIndex++;
+ return ((currentByte & mask) > 0) ? (byte) 1 : (byte) 0;
+}
+
+private PngIdatChunk getNextChunk() {
+ PngChunk chunk = chunkReader.readNextChunk();
+ if (chunk == null) error();
+ if (chunk.getChunkType() != PngChunk.CHUNK_IDAT) error();
+ return (PngIdatChunk) chunk;
+}
+
+byte getNextIdatByte() {
+ if (nextByteIndex > currentChunk.getLength() - 1) {
+ currentChunk = getNextChunk();
+ nextByteIndex = 0;
+ }
+ byte nextByte = currentChunk.getDataByteAtOffset(nextByteIndex);
+ nextByteIndex++;
+ nextBitIndex = MAX_BIT + 1;
+ return nextByte;
+}
+
+private void updateAdler(byte value) {
+ int low = adlerValue & 0xFFFF;
+ int high = (adlerValue >> 16) & 0xFFFF;
+ int valueInt = value & 0xFF;
+ low = (low + valueInt) % PRIME;
+ high = (low + high) % PRIME;
+ adlerValue = (high << 16) | low;
+}
+
+byte getNextDecodedByte() {
+ byte nextDecodedByte = lzBlockReader.getNextByte();
+ updateAdler(nextDecodedByte);
+ return nextDecodedByte;
+}
+
+void error() {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+}
+
+private void readCompressedDataHeader() {
+ byte headerByte1 = getNextIdatByte();
+ byte headerByte2 = getNextIdatByte();
+
+ int number = (headerByte1 << 8) | (headerByte2 & 0xFF);
+ if (number % 31 != 0) error();
+
+ int compressionMethod = headerByte1 & 0x0F;
+ if (compressionMethod != 8) error();
+
+ int windowSizeHint = (headerByte1 & 0xF0) >> 4;
+ if (windowSizeHint > 7) error();
+ int windowSize = (1 << (windowSizeHint + 8));
+ lzBlockReader.setWindowSize(windowSize);
+
+ int dictionary = (headerByte2 & (1 << 5));
+ if (dictionary != 0) error();
+
+ int compressionLevel = (headerByte2 & 0xC0) >> 6;
+}
+
+void checkAdler() {
+ int storedAdler = ((getNextIdatByte() & 0xFF) << 24)
+ | ((getNextIdatByte() & 0xFF) << 16)
+ | ((getNextIdatByte() & 0xFF) << 8)
+ | (getNextIdatByte() & 0xFF);
+ if (storedAdler != adlerValue) error();
+}
+
+} \ No newline at end of file
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngFileReadState.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngFileReadState.java
new file mode 100755
index 0000000000..13e23783f3
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngFileReadState.java
@@ -0,0 +1,20 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp. 1998, 2000 All Rights Reserved
+ */
+
+class PngFileReadState extends Object {
+ boolean readIHDR;
+ boolean readPLTE;
+ boolean readIDAT;
+ boolean readIEND;
+
+ // Non - critical chunks
+ boolean readBKGD;
+ boolean readTRNS;
+
+ // Set to true after IDATs have been read.
+ boolean readPixelData;
+} \ No newline at end of file
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngHuffmanTable.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngHuffmanTable.java
new file mode 100755
index 0000000000..5c5eafa9a7
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngHuffmanTable.java
@@ -0,0 +1,122 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp. 1998, 2000 All Rights Reserved
+ */
+
+public class PngHuffmanTable {
+ CodeLengthInfo[] codeLengthInfo;
+ int[] codeValues;
+
+ static final int MAX_CODE_LENGTH = 15;
+ static final int BAD_CODE = 0xFFFFFFF;
+
+PngHuffmanTable (int[] lengths) {
+ super();
+ initialize(lengths);
+ generateTable(lengths);
+}
+
+private void initialize(int[] lengths) {
+ codeValues = new int[lengths.length];
+ for (int i = 0; i < codeValues.length; i++) {
+ codeValues[i] = i;
+ }
+
+ // minCodesByLength[n] : The smallest Huffman code of length n + 1.
+ // maxCodesByLength[n] : The largest Huffman code of length n + 1.
+ // indexesByLength[n] : Index into the values array. First value with a code of length n + 1.
+ codeLengthInfo = new CodeLengthInfo[MAX_CODE_LENGTH];
+ for (int i = 0; i < MAX_CODE_LENGTH; i++) {
+ codeLengthInfo[i] = new CodeLengthInfo();
+ codeLengthInfo[i].length = i;
+ codeLengthInfo[i].baseIndex = 0;
+ codeLengthInfo[i].min = BAD_CODE;
+ codeLengthInfo[i].max = -1;
+ }
+}
+
+private void generateTable(int[] lengths) {
+ // Sort the values. Primary key is code size. Secondary key is value.
+ for (int i = 0; i < lengths.length - 1; i++) {
+ for (int j = i + 1; j < lengths.length; j++) {
+ if (lengths[j] < lengths[i]
+ || (lengths[j] == lengths[i]
+ && codeValues[j] < codeValues[i]))
+ {
+ int tmp;
+ tmp = lengths[j];
+ lengths[j] = lengths[i];
+ lengths[i] = tmp;
+ tmp = codeValues[j];
+ codeValues[j] = codeValues[i];
+ codeValues[i] = tmp;
+ }
+ }
+ }
+
+ // These values in these arrays correspond to the elements of the
+ // "values" array. The Huffman code for codeValues[N] is codes[N]
+ // and the length of the code is lengths[N].
+ int[] codes = new int[lengths.length];
+ int lastLength = 0;
+ int code = 0;
+ for (int i = 0; i < lengths.length; i++) {
+ while (lastLength != lengths[i]) {
+ lastLength++;
+ code <<= 1;
+ }
+ if (lastLength != 0) {
+ codes[i] = code;
+ code++;
+ }
+ }
+
+ int last = 0;
+ for (int i = 0; i < lengths.length; i++) {
+ if (last != lengths[i]) {
+ last = lengths[i];
+ codeLengthInfo[last - 1].baseIndex = i;
+ codeLengthInfo[last - 1].min = codes[i];
+ }
+ if (last != 0) codeLengthInfo[last - 1].max = codes[i];
+ }
+}
+
+int getNextValue(PngDecodingDataStream stream) {
+ int code = stream.getNextIdatBit();
+ int codelength = 0;
+
+ // Here we are taking advantage of the fact that 1 bits are used as
+ // a prefix to the longer codeValues.
+ while (code > codeLengthInfo[codelength].max && codelength < MAX_CODE_LENGTH) {
+ code = ((code << 1) | stream.getNextIdatBit());
+ codelength++;
+ }
+ if (codelength >= MAX_CODE_LENGTH) stream.error();
+
+ // Now we have a Huffman code of length (codelength + 1) that
+ // is somewhere in the range
+ // minCodesByLength[codelength]..maxCodesByLength[codelength].
+ // This code is the (offset + 1)'th code of (codelength + 1);
+ int offset = code - codeLengthInfo[codelength].min;
+
+ // indexesByLength[codelength] is the first code of length (codelength + 1)
+ // so now we can look up the value for the Huffman code in the table.
+ int index = codeLengthInfo[codelength].baseIndex + offset;
+ return codeValues[index];
+}
+
+class CodeValuePair {
+ int value;
+ int code;
+}
+class CodeLengthInfo {
+ int length;
+ int max;
+ int min;
+ int baseIndex;
+}
+
+} \ No newline at end of file
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngHuffmanTables.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngHuffmanTables.java
new file mode 100755
index 0000000000..383323da97
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngHuffmanTables.java
@@ -0,0 +1,156 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp. 1998, 2000 All Rights Reserved
+ */
+
+public class PngHuffmanTables {
+ PngHuffmanTable literalTable;
+ PngHuffmanTable distanceTable;
+
+ static PngHuffmanTable FixedLiteralTable;
+ static PngHuffmanTable FixedDistanceTable;
+
+ static final int LiteralTableSize = 288;
+ static final int[] FixedLiteralLengths = {
+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7, 7, 7, 7, 7, 7, 7, 7,
+ 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8,
+ };
+
+ static final int DistanceTableSize = 32;
+ static final int[] FixedDistanceLengths = {
+ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+ };
+
+ static final int LengthCodeTableSize = 19;
+ static final int[] LengthCodeOrder = {
+ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5,
+ 11, 4, 12, 3, 13, 2, 14, 1, 15
+ };
+
+static PngHuffmanTables getDynamicTables(PngDecodingDataStream stream){
+ return new PngHuffmanTables(stream);
+}
+static PngHuffmanTables getFixedTables() {
+ return new PngHuffmanTables();
+}
+
+private PngHuffmanTable getFixedLiteralTable() {
+ if (FixedLiteralTable == null) {
+ FixedLiteralTable = new PngHuffmanTable(FixedLiteralLengths);
+ }
+ return FixedLiteralTable;
+}
+
+private PngHuffmanTable getFixedDistanceTable() {
+ if (FixedDistanceTable == null) {
+ FixedDistanceTable = new PngHuffmanTable(FixedDistanceLengths);
+ }
+ return FixedDistanceTable;
+}
+
+private PngHuffmanTables () {
+ super();
+ literalTable = getFixedLiteralTable();
+ distanceTable = getFixedDistanceTable();
+}
+
+private PngHuffmanTables (PngDecodingDataStream stream) {
+ super();
+
+ int literals = PngLzBlockReader.FIRST_LENGTH_CODE
+ + stream.getNextIdatBits(5);
+ int distances = PngLzBlockReader.FIRST_DISTANCE_CODE
+ + stream.getNextIdatBits(5);
+ int codeLengthCodes = PngLzBlockReader.FIRST_CODE_LENGTH_CODE
+ + stream.getNextIdatBits(4);
+
+ if (codeLengthCodes > PngLzBlockReader.LAST_CODE_LENGTH_CODE) {
+ stream.error();
+ }
+
+ /* Tricky, tricky, tricky. The length codes are stored in
+ * a very odd order. (For the order, see the definition of
+ * the static field lengthCodeOrder.) Also, the data may
+ * not contain values for all the codes. It may just contain
+ * values for the first X number of codes. The table should
+ * be of size <LengthCodeTableSize> regardless of the number
+ * of values actually given in the table.
+ */
+ int[] lengthCodes = new int[LengthCodeTableSize];
+ for (int i = 0; i < codeLengthCodes; i++) {
+ lengthCodes[LengthCodeOrder[i]] = stream.getNextIdatBits(3);
+ }
+ PngHuffmanTable codeLengthsTable = new PngHuffmanTable(lengthCodes);
+
+ int[] literalLengths = readLengths(
+ stream, literals, codeLengthsTable, LiteralTableSize);
+ int[] distanceLengths = readLengths(
+ stream, distances, codeLengthsTable, DistanceTableSize);
+
+ literalTable = new PngHuffmanTable(literalLengths);
+ distanceTable = new PngHuffmanTable(distanceLengths);
+}
+
+private int [] readLengths (PngDecodingDataStream stream,
+ int numLengths,
+ PngHuffmanTable lengthsTable,
+ int tableSize)
+{
+ int[] lengths = new int[tableSize];
+
+ for (int index = 0; index < numLengths;) {
+ int value = lengthsTable.getNextValue(stream);
+ if (value < 16) {
+ // Literal value
+ lengths[index] = value;
+ index++;
+ } else if (value == 16) {
+ // Repeat the previous code 3-6 times.
+ int count = stream.getNextIdatBits(2) + 3;
+ for (int i = 0; i < count; i++) {
+ lengths[index] = lengths [index - 1];
+ index++;
+ }
+ } else if (value == 17) {
+ // Repeat 0 3-10 times.
+ int count = stream.getNextIdatBits(3) + 3;
+ for (int i = 0; i < count; i++) {
+ lengths[index] = 0;
+ index++;
+ }
+ } else if (value == 18) {
+ // Repeat 0 11-138 times.
+ int count = stream.getNextIdatBits(7) + 11;
+ for (int i = 0; i < count; i++) {
+ lengths[index] = 0;
+ index++;
+ }
+ } else {
+ stream.error();
+ }
+ }
+ return lengths;
+}
+
+int getNextLiteralValue(PngDecodingDataStream stream) {
+ return literalTable.getNextValue(stream);
+}
+
+int getNextDistanceValue(PngDecodingDataStream stream) {
+ return distanceTable.getNextValue(stream);
+}
+
+} \ No newline at end of file
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngIdatChunk.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngIdatChunk.java
new file mode 100755
index 0000000000..883326ebe3
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngIdatChunk.java
@@ -0,0 +1,36 @@
+package org.eclipse.swt.internal.image;
+
+import org.eclipse.swt.*;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp. 1998, 2000 All Rights Reserved
+ */
+
+class PngIdatChunk extends PngChunk {
+
+PngIdatChunk(byte[] reference){
+ super(reference);
+}
+
+/**
+ * Answer whether the chunk is a valid IDAT chunk.
+ */
+void validate(PngFileReadState readState, PngIhdrChunk headerChunk) {
+ if (!readState.readIHDR
+ || (headerChunk.getMustHavePalette() && !readState.readPLTE)
+ || readState.readIEND)
+ {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ } else {
+ readState.readIDAT = true;
+ }
+
+ super.validate(readState, headerChunk);
+}
+
+byte getDataByteAtOffset(int offset) {
+ return reference[DATA_OFFSET + offset];
+}
+
+} \ No newline at end of file
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngIendChunk.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngIendChunk.java
new file mode 100755
index 0000000000..189cf8f7a3
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngIendChunk.java
@@ -0,0 +1,39 @@
+package org.eclipse.swt.internal.image;
+
+import org.eclipse.swt.*;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp. 1998, 2000 All Rights Reserved
+ */
+
+class PngIendChunk extends PngChunk {
+
+PngIendChunk(byte[] reference){
+ super(reference);
+}
+
+/**
+ * Answer whether the chunk is a valid IEND chunk.
+ */
+void validate(PngFileReadState readState, PngIhdrChunk headerChunk) {
+ // An IEND chunk is invalid if no IHDR has been read.
+ // Or if a palette is required and has not been read.
+ // Or if no IDAT chunk has been read.
+ if (!readState.readIHDR
+ || (headerChunk.getMustHavePalette() && !readState.readPLTE)
+ || !readState.readIDAT
+ || readState.readIEND)
+ {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ } else {
+ readState.readIEND = true;
+ }
+
+ super.validate(readState, headerChunk);
+
+ // IEND chunks are not allowed to have any data.
+ if (getLength() > 0) SWT.error(SWT.ERROR_INVALID_IMAGE);
+}
+
+} \ No newline at end of file
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngIhdrChunk.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngIhdrChunk.java
new file mode 100755
index 0000000000..00f3cec52e
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngIhdrChunk.java
@@ -0,0 +1,372 @@
+package org.eclipse.swt.internal.image;
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp. 1998, 2000 All Rights Reserved
+ */
+
+class PngIhdrChunk extends PngChunk {
+ static final int EXPECTED_DATA_LENGTH = 13;
+
+ static final int WIDTH_DATA_OFFSET = DATA_OFFSET + 0;
+ static final int HEIGHT_DATA_OFFSET = DATA_OFFSET + 4;
+ static final int BIT_DEPTH_OFFSET = DATA_OFFSET + 8;
+ static final int COLOR_TYPE_OFFSET = DATA_OFFSET + 9;
+ static final int COMPRESSION_METHOD_OFFSET = DATA_OFFSET + 10;
+ static final int FILTER_METHOD_OFFSET = DATA_OFFSET + 11;
+ static final int INTERLACE_METHOD_OFFSET = DATA_OFFSET + 12;
+
+ static final int COLOR_TYPE_GRAYSCALE = 0;
+ static final int COLOR_TYPE_RGB = 2;
+ static final int COLOR_TYPE_PALETTE = 3;
+ static final int COLOR_TYPE_GRAYSCALE_WITH_ALPHA = 4;
+ static final int COLOR_TYPE_RGB_WITH_ALPHA = 6;
+
+ static final int INTERLACE_METHOD_NONE = 0;
+ static final int INTERLACE_METHOD_ADAM7 = 1;
+
+ static final int FILTER_NONE = 0;
+ static final int FILTER_SUB = 1;
+ static final int FILTER_UP = 2;
+ static final int FILTER_AVERAGE = 3;
+ static final int FILTER_PAETH = 4;
+
+ static final byte[] ValidBitDepths = {1, 2, 4, 8, 16};
+ static final byte[] ValidColorTypes = {0, 2, 3, 4, 6};
+
+/**
+ * Construct a PNGChunk using the reference bytes
+ * given.
+ */
+PngIhdrChunk(byte[] reference) {
+ super(reference);
+}
+
+/**
+ * Get the image's width in pixels.
+ */
+int getWidth() {
+ return getInt32(WIDTH_DATA_OFFSET);
+}
+
+/**
+ * Set the image's width in pixels.
+ */
+void setWidth(int value) {
+ setInt32(WIDTH_DATA_OFFSET, value);
+}
+
+/**
+ * Get the image's height in pixels.
+ */
+int getHeight() {
+ return getInt32(HEIGHT_DATA_OFFSET);
+}
+
+/**
+ * Set the image's height in pixels.
+ */
+void setHeight(int value) {
+ setInt32(HEIGHT_DATA_OFFSET, value);
+}
+
+/**
+ * Get the image's bit depth.
+ * This is limited to the values 1, 2, 4, 8, or 16.
+ */
+byte getBitDepth() {
+ return reference[BIT_DEPTH_OFFSET];
+}
+
+/**
+ * Set the image's bit depth.
+ * This is limited to the values 1, 2, 4, 8, or 16.
+ */
+void setBitDepth(byte value) {
+ reference[BIT_DEPTH_OFFSET] = value;
+}
+
+/**
+ * Get the image's color type.
+ * This is limited to the values:
+ * 0 - Grayscale image.
+ * 2 - RGB triple.
+ * 3 - Palette.
+ * 4 - Grayscale with Alpha channel.
+ * 6 - RGB with Alpha channel.
+ */
+byte getColorType() {
+ return reference[COLOR_TYPE_OFFSET];
+}
+
+/**
+ * Set the image's color type.
+ * This is limited to the values:
+ * 0 - Grayscale image.
+ * 2 - RGB triple.
+ * 3 - Palette.
+ * 4 - Grayscale with Alpha channel.
+ * 6 - RGB with Alpha channel.
+ */
+void setColorType(byte value) {
+ reference[COLOR_TYPE_OFFSET] = value;
+}
+
+/**
+ * Get the image's compression method.
+ * This value must be 0.
+ */
+byte getCompressionMethod() {
+ return reference[COMPRESSION_METHOD_OFFSET];
+}
+
+/**
+ * Set the image's compression method.
+ * This value must be 0.
+ */
+void setCompressionMethod(byte value) {
+ reference[COMPRESSION_METHOD_OFFSET] = value;
+}
+
+/**
+ * Get the image's filter method.
+ * This value must be 0.
+ */
+byte getFilterMethod() {
+ return reference[FILTER_METHOD_OFFSET];
+}
+
+/**
+ * Set the image's filter method.
+ * This value must be 0.
+ */
+void setFilterMethod(byte value) {
+ reference[FILTER_METHOD_OFFSET] = value;
+}
+
+/**
+ * Get the image's interlace method.
+ * This value is limited to:
+ * 0 - No interlacing used.
+ * 1 - Adam7 interlacing used.
+ */
+byte getInterlaceMethod() {
+ return reference[INTERLACE_METHOD_OFFSET];
+}
+
+/**
+ * Set the image's interlace method.
+ * This value is limited to:
+ * 0 - No interlacing used.
+ * 1 - Adam7 interlacing used.
+ */
+void setInterlaceMethod(byte value) {
+ reference[INTERLACE_METHOD_OFFSET] = value;
+}
+
+/**
+ * Answer whether the chunk is a valid IHDR chunk.
+ */
+void validate(PngFileReadState readState, PngIhdrChunk headerChunk) {
+ // An IHDR chunk is invalid if any other chunk has
+ // been read.
+ if (readState.readIHDR
+ || readState.readPLTE
+ || readState.readIDAT
+ || readState.readIEND)
+ {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ } else {
+ readState.readIHDR = true;
+ }
+
+ super.validate(readState, headerChunk);
+
+ if (getLength() != EXPECTED_DATA_LENGTH) SWT.error(SWT.ERROR_INVALID_IMAGE);
+ if (getCompressionMethod() != 0) SWT.error(SWT.ERROR_INVALID_IMAGE);
+ if (getInterlaceMethod() != INTERLACE_METHOD_NONE &&
+ getInterlaceMethod() != INTERLACE_METHOD_ADAM7) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+
+ boolean colorTypeIsValid = false;
+ byte colorType = getColorType();
+ for (int i = 0; i < ValidColorTypes.length; i++) {
+ if (ValidColorTypes[i] == colorType) {
+ colorTypeIsValid = true;
+ break;
+ }
+ }
+ if (!colorTypeIsValid) SWT.error(SWT.ERROR_INVALID_IMAGE);;
+
+ boolean bitDepthIsValid = false;
+ byte bitDepth = getBitDepth();
+ for (int i = 0; i < ValidBitDepths.length; i++) {
+ if (ValidBitDepths[i] == bitDepth) {
+ bitDepthIsValid = true;
+ break;
+ }
+ }
+ if (!bitDepthIsValid) SWT.error(SWT.ERROR_INVALID_IMAGE);
+
+ if ((colorType == COLOR_TYPE_RGB
+ || colorType == COLOR_TYPE_RGB_WITH_ALPHA
+ || colorType == COLOR_TYPE_GRAYSCALE_WITH_ALPHA)
+ && bitDepth < 8)
+ {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+
+ if (colorType == COLOR_TYPE_PALETTE && bitDepth > 8) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+}
+
+String getColorTypeString() {
+ switch (getColorType()) {
+ case COLOR_TYPE_GRAYSCALE: return "Grayscale";
+ case COLOR_TYPE_RGB: return "RGB";
+ case COLOR_TYPE_PALETTE: return "Palette";
+ case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: return "Grayscale with Alpha";
+ case COLOR_TYPE_RGB_WITH_ALPHA: return "RGB with Alpha";
+ default: return "Unknown - " + getColorType();
+ }
+}
+
+String getFilterMethodString() {
+ switch (getFilterMethod()) {
+ case FILTER_NONE: return "None";
+ case FILTER_SUB: return "Sub";
+ case FILTER_UP: return "Up";
+ case FILTER_AVERAGE: return "Average";
+ case FILTER_PAETH: return "Paeth";
+ default: return "Unknown";
+ }
+}
+
+String getInterlaceMethodString() {
+ switch (getInterlaceMethod()) {
+ case INTERLACE_METHOD_NONE: return "Not Interlaced";
+ case INTERLACE_METHOD_ADAM7: return "Interlaced - ADAM7";
+ default: return "Unknown";
+ }
+}
+
+void contributeToString(StringBuffer buffer) {
+ buffer.append("\n\tWidth: ");
+ buffer.append(getWidth());
+ buffer.append("\n\tHeight: ");
+ buffer.append(getHeight());
+ buffer.append("\n\tBit Depth: ");
+ buffer.append(getBitDepth());
+ buffer.append("\n\tColor Type: ");
+ buffer.append(getColorTypeString());
+ buffer.append("\n\tCompression Method: ");
+ buffer.append(getCompressionMethod());
+ buffer.append("\n\tFilter Method: ");
+ buffer.append(getFilterMethodString());
+ buffer.append("\n\tInterlace Method: ");
+ buffer.append(getInterlaceMethodString());
+}
+
+boolean getMustHavePalette() {
+ return getColorType() == COLOR_TYPE_PALETTE;
+}
+
+boolean getCanHavePalette() {
+ int colorType = getColorType();
+ return colorType != COLOR_TYPE_GRAYSCALE &&
+ colorType != COLOR_TYPE_GRAYSCALE_WITH_ALPHA;
+}
+
+/**
+ * Answer the pixel size in bits based on the color type
+ * and bit depth.
+ */
+int getBitsPerPixel() {
+ int bitDepth = getBitDepth();
+ switch (getColorType()) {
+ case COLOR_TYPE_RGB_WITH_ALPHA:
+ return 4 * bitDepth;
+ case COLOR_TYPE_RGB:
+ return 3 * bitDepth;
+ case COLOR_TYPE_GRAYSCALE_WITH_ALPHA:
+ return 2 * bitDepth;
+ case COLOR_TYPE_GRAYSCALE:
+ case COLOR_TYPE_PALETTE:
+ return bitDepth;
+ default:
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ return 0;
+ }
+}
+
+/**
+ * Answer the pixel size in bits based on the color type
+ * and bit depth.
+ */
+int getSwtBitsPerPixel() {
+ int bitDepth = getBitDepth();
+ switch (getColorType()) {
+ case COLOR_TYPE_RGB_WITH_ALPHA:
+ case COLOR_TYPE_RGB:
+ case COLOR_TYPE_GRAYSCALE_WITH_ALPHA:
+ return 24;
+ case COLOR_TYPE_GRAYSCALE:
+ case COLOR_TYPE_PALETTE:
+ return Math.min(bitDepth, 8);
+ default:
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ return 0;
+ }
+}
+
+int getFilterByteOffset() {
+ if (getBitDepth() < 8) return 1;
+ return getBitsPerPixel() / 8;
+}
+
+boolean usesDirectColor() {
+ switch (getColorType()) {
+ case COLOR_TYPE_GRAYSCALE:
+ case COLOR_TYPE_GRAYSCALE_WITH_ALPHA:
+ case COLOR_TYPE_RGB:
+ case COLOR_TYPE_RGB_WITH_ALPHA:
+ return true;
+ default:
+ return false;
+ }
+}
+
+PaletteData createGrayscalePalette() {
+ int bitDepth = Math.min(getBitDepth(), 8);
+ int max = (int) (Math.pow(2, bitDepth) - 1);
+ int delta = 255 / max;
+ int gray = 0;
+ RGB[] rgbs = new RGB[max + 1];
+ for (int i = 0; i <= max; i++) {
+ rgbs[i] = new RGB(gray, gray, gray);
+ gray += delta;
+ }
+ return new PaletteData(rgbs);
+}
+
+PaletteData getPaletteData() {
+ switch (getColorType()) {
+ case COLOR_TYPE_GRAYSCALE:
+ return createGrayscalePalette();
+ case COLOR_TYPE_GRAYSCALE_WITH_ALPHA:
+ case COLOR_TYPE_RGB:
+ case COLOR_TYPE_RGB_WITH_ALPHA:
+ return new PaletteData(0xFF0000, 0xFF00, 0xFF);
+ default:
+ return null;
+ }
+}
+
+
+
+} \ No newline at end of file
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngLzBlockReader.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngLzBlockReader.java
new file mode 100755
index 0000000000..eab8cdfa7b
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngLzBlockReader.java
@@ -0,0 +1,169 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp. 1998, 2000 All Rights Reserved
+ */
+
+public class PngLzBlockReader {
+ boolean readHeader;
+ boolean isLastBlock;
+ byte compressionType;
+ int uncompressedBytesRemaining;
+ PngDecodingDataStream stream;
+ PngHuffmanTables huffmanTables;
+
+ byte[] window;
+ int windowIndex;
+ int copyIndex;
+ int copyBytesRemaining;
+
+ static final int UNCOMPRESSED = 0;
+ static final int COMPRESSED_FIXED = 1;
+ static final int COMPRESSED_DYNAMIC = 2;
+
+ static final int END_OF_COMPRESSED_BLOCK = 256;
+ static final int FIRST_LENGTH_CODE = 257;
+ static final int LAST_LENGTH_CODE = 285;
+ static final int FIRST_DISTANCE_CODE = 1;
+ static final int LAST_DISTANCE_CODE = 29;
+ static final int FIRST_CODE_LENGTH_CODE = 4;
+ static final int LAST_CODE_LENGTH_CODE = 19;
+
+ static final int[] lengthBases = {
+ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27,
+ 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258
+ } ;
+ static final int[] extraLengthBits = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
+ 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
+ };
+ static final int[] distanceBases = {
+ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129,
+ 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097,
+ 6145, 8193, 12289, 16385, 24577,
+ };
+ static final int[] extraDistanceBits = {
+ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7,
+ 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
+ };
+
+
+PngLzBlockReader(PngDecodingDataStream stream) {
+ this.stream = stream;
+ readHeader = false;
+ isLastBlock = false;
+}
+
+void setWindowSize(int windowSize) {
+ window = new byte[windowSize];
+}
+
+void readNextBlockHeader() {
+ isLastBlock = stream.getNextIdatBit() != 0;
+ compressionType = (byte)(stream.getNextIdatBits(2) & 0xFF);
+ if (compressionType > 2) stream.error();
+
+ if (compressionType == UNCOMPRESSED) {
+ int length = stream.getNextIdatByte()
+ | (stream.getNextIdatByte() << 8);
+ int testValue = stream.getNextIdatByte()
+ | (stream.getNextIdatByte() << 8);
+ if (length != ~testValue) stream.error();
+ uncompressedBytesRemaining = length;
+ } else if (compressionType == COMPRESSED_DYNAMIC) {
+ huffmanTables = PngHuffmanTables.getDynamicTables(stream);
+ } else {
+ huffmanTables = PngHuffmanTables.getFixedTables();
+ }
+}
+
+byte getNextByte() {
+ if (compressionType == UNCOMPRESSED) {
+ if (uncompressedBytesRemaining == 0) {
+ readNextBlockHeader();
+ return getNextByte();
+ }
+ uncompressedBytesRemaining--;
+ return stream.getNextIdatByte();
+ } else {
+ byte value = getNextCompressedByte();
+ if (value == END_OF_COMPRESSED_BLOCK) {
+ if (isLastBlock) stream.error();
+ readNextBlockHeader();
+ return getNextByte();
+ } else {
+ return value;
+ }
+ }
+}
+
+private void assertBlockAtEnd() {
+ if (compressionType == UNCOMPRESSED) {
+ if (uncompressedBytesRemaining > 0) stream.error();
+ } else if (copyBytesRemaining > 0 ||
+ (huffmanTables.getNextLiteralValue(stream) != END_OF_COMPRESSED_BLOCK))
+ {
+ stream.error();
+ }
+}
+void assertCompressedDataAtEnd() {
+ assertBlockAtEnd();
+ while (!isLastBlock) {
+ readNextBlockHeader();
+ assertBlockAtEnd();
+ }
+}
+
+private byte getNextCompressedByte() {
+ if (copyBytesRemaining > 0) {
+ byte value = window[copyIndex];
+ byte temp = (byte) (value & 0xFF);
+ window[windowIndex] = value;
+ copyBytesRemaining--;
+
+ copyIndex++;
+ windowIndex++;
+ if (copyIndex == window.length) copyIndex = 0;
+ if (windowIndex == window.length) windowIndex = 0;
+
+ return value;
+ }
+
+ int value = huffmanTables.getNextLiteralValue(stream);
+ if (value < END_OF_COMPRESSED_BLOCK) {
+ byte temp = (byte) (value & 0xFF);
+ window[windowIndex] = (byte) (value & 0xFF);
+ windowIndex++;
+ if (windowIndex >= window.length) windowIndex = 0;
+ return (byte) (value & 0xFF);
+ } else if (value == END_OF_COMPRESSED_BLOCK) {
+ readNextBlockHeader();
+ return getNextCompressedByte();
+ } else if (value <= LAST_LENGTH_CODE) {
+ int extraBits = extraLengthBits[value - FIRST_LENGTH_CODE];
+ int length = lengthBases[value - FIRST_LENGTH_CODE];
+ if (extraBits > 0) {
+ length += stream.getNextIdatBits(extraBits);
+ }
+
+ value = huffmanTables.getNextDistanceValue(stream);
+ if (value > LAST_DISTANCE_CODE) stream.error();
+ extraBits = extraDistanceBits[value];
+ int distance = distanceBases[value];
+ if (extraBits > 0) {
+ distance += stream.getNextIdatBits(extraBits);
+ }
+
+ copyIndex = windowIndex - distance;
+ if (copyIndex < 0) copyIndex += window.length;
+
+ copyBytesRemaining = length;
+ return getNextCompressedByte();
+ } else {
+ stream.error();
+ return 0;
+ }
+}
+
+} \ No newline at end of file
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngPlteChunk.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngPlteChunk.java
new file mode 100755
index 0000000000..8c41b83d22
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngPlteChunk.java
@@ -0,0 +1,87 @@
+package org.eclipse.swt.internal.image;
+
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp. 1998, 2000 All Rights Reserved
+ */
+
+class PngPlteChunk extends PngChunk {
+
+PngPlteChunk(byte[] reference){
+ super(reference);
+}
+
+/**
+ * Get the number of colors in this palette.
+ */
+int getPaletteSize() {
+ return getLength() / 3;
+}
+
+/**
+ * Get a PaletteData object representing the colors
+ * stored in this PLTE chunk.
+ * The result should be cached as the PLTE chunk
+ * does not store the palette data created.
+ */
+PaletteData getPaletteData() {
+ RGB[] rgbs = new RGB[getPaletteSize()];
+ int start = DATA_OFFSET;
+ int end = DATA_OFFSET + getLength();
+ for (int i = 0; i < rgbs.length; i++) {
+ int offset = DATA_OFFSET + (i * 3);
+ int red = reference[offset] & 0xFF;
+ int green = reference[offset + 1] & 0xFF;
+ int blue = reference[offset + 2] & 0xFF;
+ rgbs[i] = new RGB(red, green, blue);
+ }
+ return new PaletteData(rgbs);
+}
+
+/**
+ * Answer whether the chunk is a valid PLTE chunk.
+ */
+void validate(PngFileReadState readState, PngIhdrChunk headerChunk) {
+ // A PLTE chunk is invalid if no IHDR has been read or if any PLTE,
+ // IDAT, or IEND chunk has been read.
+ if (!readState.readIHDR
+ || readState.readPLTE
+ || readState.readTRNS
+ || readState.readBKGD
+ || readState.readIDAT
+ || readState.readIEND)
+ {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ } else {
+ readState.readPLTE = true;
+ }
+
+ super.validate(readState, headerChunk);
+
+ // Palettes cannot be included in grayscale images.
+ if (!headerChunk.getCanHavePalette()) SWT.error(SWT.ERROR_INVALID_IMAGE);
+
+ // Palette chunks' data fields must be event multiples
+ // of 3. Each 3-byte group represents an RGB value.
+ if (getLength() % 3 != 0) SWT.error(SWT.ERROR_INVALID_IMAGE);
+
+ // Palettes cannot have more entries than 2^bitDepth
+ // where bitDepth is the bit depth of the image given
+ // in the IHDR chunk.
+ if (Math.pow(2, headerChunk.getBitDepth()) < getPaletteSize()) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+
+ // Palettes cannot have more than 256 entries.
+ if (256 < getPaletteSize()) SWT.error(SWT.ERROR_INVALID_IMAGE);
+}
+
+void contributeToString(StringBuffer buffer) {
+ buffer.append("\n\tPalette size:");
+ buffer.append(getPaletteSize());
+}
+
+} \ No newline at end of file
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngTrnsChunk.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngTrnsChunk.java
new file mode 100755
index 0000000000..a1910bade6
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/PngTrnsChunk.java
@@ -0,0 +1,133 @@
+package org.eclipse.swt.internal.image;
+
+import org.eclipse.swt.*;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * (c) Copyright IBM Corp. 1998, 2000 All Rights Reserved
+ */
+
+public class PngTrnsChunk extends PngChunk {
+ static final int TRANSPARENCY_TYPE_PIXEL = 0;
+ static final int TRANSPARENCY_TYPE_ALPHAS = 1;
+
+PngTrnsChunk(byte[] reference){
+ super(reference);
+}
+
+void validateLength(PngIhdrChunk header, PngPlteChunk paletteChunk) {
+ boolean valid;
+ switch (header.getColorType()) {
+ case PngIhdrChunk.COLOR_TYPE_RGB:
+ // Three 2-byte values (RGB)
+ valid = getLength() == 6;
+ break;
+ case PngIhdrChunk.COLOR_TYPE_PALETTE:
+ // Three 2-byte values (RGB)
+ valid = getLength() <= paletteChunk.getLength();
+ break;
+ case PngIhdrChunk.COLOR_TYPE_GRAYSCALE:
+ // One 2-byte value
+ valid = getLength() == 2;
+ break;
+ // Cannot use both Alpha and tRNS
+ case PngIhdrChunk.COLOR_TYPE_RGB_WITH_ALPHA:
+ case PngIhdrChunk.COLOR_TYPE_GRAYSCALE_WITH_ALPHA:
+ default:
+ valid = false;
+ }
+ if (!valid) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+}
+
+/**
+ * Answer whether the chunk is a valid tRNS chunk.
+ */
+void validate(PngFileReadState readState, PngIhdrChunk headerChunk, PngPlteChunk paletteChunk) {
+ if (!readState.readIHDR
+ || (headerChunk.getMustHavePalette() && !readState.readPLTE)
+ || readState.readIDAT
+ || readState.readIEND)
+ {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ } else {
+ readState.readTRNS = true;
+ }
+
+ validateLength(headerChunk, paletteChunk);
+
+ super.validate(readState, headerChunk);
+}
+
+
+int getTransparencyType(PngIhdrChunk header) {
+ if (header.getColorType() == PngIhdrChunk.COLOR_TYPE_PALETTE) {
+ return TRANSPARENCY_TYPE_ALPHAS;
+ }
+ return TRANSPARENCY_TYPE_PIXEL;
+}
+
+/**
+ * Answer the transparent pixel RGB value.
+ * This is not valid for palette color types.
+ * This is not valid for alpha color types.
+ * This will convert a grayscale value into
+ * a palette index.
+ * It will compress a 6 byte RGB into a 3 byte
+ * RGB.
+ */
+int getSwtTransparentPixel(PngIhdrChunk header) {
+ switch (header.getColorType()) {
+ case PngIhdrChunk.COLOR_TYPE_GRAYSCALE:
+ int gray = ((reference[DATA_OFFSET] & 0xFF) << 8)
+ + (reference[DATA_OFFSET + 1] & 0xFF);
+ if (header.getBitDepth() > 8) {
+ return PNGFileFormat.compress16BitDepthTo8BitDepth(gray);
+ }
+ return gray & 0xFF;
+ case PngIhdrChunk.COLOR_TYPE_RGB:
+ int red = ((reference[DATA_OFFSET] & 0xFF) << 8)
+ | (reference[DATA_OFFSET + 1] & 0xFF);
+ int green = ((reference[DATA_OFFSET + 2] & 0xFF) << 8)
+ | (reference[DATA_OFFSET + 3] & 0xFF);
+ int blue = ((reference[DATA_OFFSET + 4] & 0xFF) << 8)
+ | (reference[DATA_OFFSET + 5] & 0xFF);
+ if (header.getBitDepth() > 8) {
+ red = PNGFileFormat.compress16BitDepthTo8BitDepth(red);
+ green = PNGFileFormat.compress16BitDepthTo8BitDepth(green);
+ blue = PNGFileFormat.compress16BitDepthTo8BitDepth(blue);
+ }
+ return (red << 16) | (green << 8) | blue;
+ default:
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ return -1;
+ }
+}
+
+/**
+ * Answer an array of Alpha values that correspond to the
+ * colors in the palette.
+ * This is only valid for the COLOR_TYPE_PALETTE color type.
+ */
+byte[] getAlphaValues(PngIhdrChunk header, PngPlteChunk paletteChunk) {
+ if (header.getColorType() != PngIhdrChunk.COLOR_TYPE_PALETTE) {
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ }
+ byte[] alphas = new byte[paletteChunk.getPaletteSize()];
+ int dataLength = getLength();
+ int i = 0;
+ for (i = 0; i < dataLength; i++) {
+ alphas[i] = reference[DATA_OFFSET + i];
+ }
+ /**
+ * Any palette entries which do not have a corresponding
+ * alpha value in the tRNS chunk are spec'd to have an
+ * alpha of 255.
+ */
+ for (int j = i; j < alphas.length; j++) {
+ alphas[j] = (byte) 255;
+ }
+ return alphas;
+}
+} \ No newline at end of file
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/WinBMPFileFormat.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/WinBMPFileFormat.java
new file mode 100755
index 0000000000..fc94da00d2
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/WinBMPFileFormat.java
@@ -0,0 +1,667 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * WebSphere Studio Workbench
+ * (c) Copyright IBM Corp 2000
+ */
+
+/* Imports */
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+import java.io.*;
+
+/* Class Definition */
+final class WinBMPFileFormat extends FileFormat {
+ int compression;
+ int importantColors;
+ Point pelsPerMeter = new Point(0, 0);
+ public static final int BMPHeaderFixedSize = 40;
+
+/**
+ * Compress numBytes bytes of image data from src, storing in dest
+ * (starting at 0), using the technique specified by comp.
+ * If last is true, this indicates the last line of the image.
+ * Answer the size of the compressed data.
+ */
+int compress(int comp, byte[] src, int srcOffset, int numBytes, byte[] dest, boolean last) {
+ if (comp == 1) { // BMP_RLE8_COMPRESSION
+ return compressRLE8Data(src, srcOffset, numBytes, dest, last);
+ }
+ if (comp == 2) { // BMP_RLE4_COMPRESSION
+ return compressRLE4Data(src, srcOffset, numBytes, dest, last);
+ }
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ return 0;
+}
+int compressRLE4Data(byte[] src, int srcOffset, int numBytes, byte[] dest, boolean last) {
+ int sp = srcOffset, end = srcOffset + numBytes, dp = 0;
+ int size = 0, left, i, n;
+ byte theByte;
+ while (sp < end) {
+ /* find two consecutive bytes that are the same in the next 128 */
+ left = end - sp - 1;
+ if (left > 127)
+ left = 127;
+ for (n = 0; n < left; n++) {
+ if (src[sp + n] == src[sp + n + 1])
+ break;
+ }
+ /* if there is only one more byte in the scan line, include it */
+ if (n < 127 && n == left)
+ n++;
+ /* store the intervening data */
+ switch (n) {
+ case 0:
+ break;
+ case 1: /* handled separately because 0,2 is a command */
+ dest[dp] = 2; dp++; /* 1 byte == 2 pixels */
+ dest[dp] = src[sp];
+ dp++; sp++;
+ size += 2;
+ break;
+ default:
+ dest[dp] = 0; dp++;
+ dest[dp] = (byte)(n + n); dp++; /* n bytes = n*2 pixels */
+ for (i = n; i > 0; i--) {
+ dest[dp] = src[sp];
+ dp++; sp++;
+ }
+ size += 2 + n;
+ if ((n & 1) != 0) { /* pad to word */
+ dest[dp] = 0;
+ dp++;
+ size++;
+ }
+ break;
+ }
+ /* find the length of the next run (up to 127) and store it */
+ left = end - sp;
+ if (left > 0) {
+ if (left > 127)
+ left = 127;
+ theByte = src[sp];
+ for (n = 1; n < left; n++) {
+ if (src[sp + n] != theByte)
+ break;
+ }
+ dest[dp] = (byte)(n + n); dp++; /* n bytes = n*2 pixels */
+ dest[dp] = theByte; dp++;
+ sp += n;
+ size += 2;
+ }
+ }
+
+ /* store the end of line or end of bitmap codes */
+ dest[dp] = 0; dp++;
+ if (last) {
+ dest[dp] = 1; dp++;
+ } else {
+ dest[dp] = 0; dp++;
+ }
+ size += 2;
+
+ return size;
+}
+int compressRLE8Data(byte[] src, int srcOffset, int numBytes, byte[] dest, boolean last) {
+ int sp = srcOffset, end = srcOffset + numBytes, dp = 0;
+ int size = 0, left, i, n;
+ byte theByte;
+ while (sp < end) {
+ /* find two consecutive bytes that are the same in the next 256 */
+ left = end - sp - 1;
+ if (left > 254)
+ left = 254;
+ for (n = 0; n < left; n++) {
+ if (src[sp + n] == src[sp + n + 1])
+ break;
+ }
+ /* if there is only one more byte in the scan line, include it */
+ if (n == left)
+ n++;
+ /* store the intervening data */
+ switch (n) {
+ case 0:
+ break;
+ case 2: /* handled separately because 0,2 is a command */
+ dest[dp] = 1; dp++;
+ dest[dp] = src[sp];
+ dp++; sp++;
+ size += 2;
+ /* don't break, fall through */
+ case 1: /* handled separately because 0,1 is a command */
+ dest[dp] = 1; dp++;
+ dest[dp] = src[sp];
+ dp++; sp++;
+ size += 2;
+ break;
+ default:
+ dest[dp] = 0; dp++;
+ dest[dp] = (byte)n; dp++;
+ for (i = n; i > 0; i--) {
+ dest[dp] = src[sp];
+ dp++; sp++;
+ }
+ size += 2 + n;
+ if ((n & 1) != 0) { /* pad to word */
+ dest[dp] = 0;
+ dp++;
+ size++;
+ }
+ break;
+ }
+ /* find the length of the next run (up to 255) and store it */
+ left = end - sp;
+ if (left > 0) {
+ if (left > 255)
+ left = 255;
+ theByte = src[sp];
+ for (n = 1; n < left; n++) {
+ if (src[sp + n] != theByte)
+ break;
+ }
+ dest[dp] = (byte)n; dp++;
+ dest[dp] = theByte; dp++;
+ sp += n;
+ size += 2;
+ }
+ }
+
+ /* store the end of line or end of bitmap codes */
+ dest[dp] = 0; dp++;
+ if (last) {
+ dest[dp] = 1; dp++;
+ } else {
+ dest[dp] = 0; dp++;
+ }
+ size += 2;
+
+ return size;
+}
+void decompressData(byte[] src, byte[] dest, int stride, int cmp) {
+ if (cmp == 1) { // BMP_RLE8_COMPRESSION
+ if (decompressRLE8Data(src, src.length, stride, dest, dest.length) <= 0)
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ return;
+ }
+ if (cmp == 2) { // BMP_RLE4_COMPRESSION
+ if (decompressRLE4Data(src, src.length, stride, dest, dest.length) <= 0)
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ return;
+ }
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+}
+int decompressRLE4Data(byte[] src, int numBytes, int stride, byte[] dest, int destSize) {
+ int sp = 0;
+ int se = numBytes;
+ int dp = 0;
+ int de = destSize;
+ int x = 0, y = 0;
+ while (sp < se) {
+ int len = src[sp] & 0xFF;
+ sp++;
+ if (len == 0) {
+ len = src[sp] & 0xFF;
+ sp++;
+ switch (len) {
+ case 0: /* end of line */
+ y++;
+ x = 0;
+ dp = y * stride;
+ if (dp >= de)
+ return -1;
+ break;
+ case 1: /* end of bitmap */
+ return 1;
+ case 2: /* delta */
+ x += src[sp] & 0xFF;
+ sp++;
+ y += src[sp] & 0xFF;
+ sp++;
+ dp = y * stride + x / 2;
+ if (dp >= de)
+ return -1;
+ break;
+ default: /* absolute mode run */
+ if ((len & 1) != 0) /* odd run lengths not currently supported */
+ return -1;
+ x += len;
+ len = len / 2;
+ if (len > (se - sp))
+ return -1;
+ if (len > (de - dp))
+ return -1;
+ for (int i = 0; i < len; i++) {
+ dest[dp] = src[sp];
+ dp++;
+ sp++;
+ }
+ if ((sp & 1) != 0)
+ sp++; /* word align sp? */
+ break;
+ }
+ } else {
+ if ((len & 1) != 0)
+ return -1;
+ x += len;
+ len = len / 2;
+ byte theByte = src[sp];
+ sp++;
+ if (len > (de - dp))
+ return -1;
+ for (int i = 0; i < len; i++) {
+ dest[dp] = theByte;
+ dp++;
+ }
+ }
+ }
+ return 1;
+}
+int decompressRLE8Data(byte[] src, int numBytes, int stride, byte[] dest, int destSize) {
+ int sp = 0;
+ int se = numBytes;
+ int dp = 0;
+ int de = destSize;
+ int x = 0, y = 0;
+ while (sp < se) {
+ int len = src[sp] & 0xFF;
+ sp++;
+ if (len == 0) {
+ len = src[sp] & 0xFF;
+ sp++;
+ switch (len) {
+ case 0: /* end of line */
+ y++;
+ x = 0;
+ dp = y * stride;
+ if (dp >= de)
+ return -1;
+ break;
+ case 1: /* end of bitmap */
+ return 1;
+ case 2: /* delta */
+ x += src[sp] & 0xFF;
+ sp++;
+ y += src[sp] & 0xFF;
+ sp++;
+ dp = y * stride + x;
+ if (dp >= de)
+ return -1;
+ break;
+ default: /* absolute mode run */
+ if (len > (se - sp))
+ return -1;
+ if (len > (de - dp))
+ return -1;
+ for (int i = 0; i < len; i++) {
+ dest[dp] = src[sp];
+ dp++;
+ sp++;
+ }
+ if ((sp & 1) != 0)
+ sp++; /* word align sp? */
+ x += len;
+ break;
+ }
+ } else {
+ byte theByte = src[sp];
+ sp++;
+ if (len > (de - dp))
+ return -1;
+ for (int i = 0; i < len; i++) {
+ dest[dp] = theByte;
+ dp++;
+ }
+ x += len;
+ }
+ }
+ return 1;
+}
+public static boolean isBMPFile(LEDataInputStream stream) {
+ try {
+ byte[] header = new byte[2];
+ stream.read(header);
+ stream.unread(header);
+ return header[0] == 0x42 && header[1] == 0x4D;
+ } catch (Exception e) {
+ return false;
+ }
+}
+byte[] loadData(byte[] infoHeader) {
+ int width = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8) | ((infoHeader[6] & 0xFF) << 16) | ((infoHeader[7] & 0xFF) << 24);
+ int height = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24);
+ int bitCount = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8);
+ int stride = (width * bitCount + 7) / 8;
+ stride = (stride + 3) / 4 * 4; // Round up to 4 byte multiple
+ byte[] data = loadData(infoHeader, stride);
+ flipScanLines(data, stride, height);
+ return data;
+}
+byte[] loadData(byte[] infoHeader, int stride) {
+ int height = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24);
+ int dataSize = height * stride;
+ byte[] data = new byte[dataSize];
+ int cmp = (infoHeader[16] & 0xFF) | ((infoHeader[17] & 0xFF) << 8) | ((infoHeader[18] & 0xFF) << 16) | ((infoHeader[19] & 0xFF) << 24);
+ if (cmp == 0) { // BMP_NO_COMPRESSION
+ try {
+ if (inputStream.read(data) != dataSize)
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ } else {
+ int compressedSize = (infoHeader[20] & 0xFF) | ((infoHeader[21] & 0xFF) << 8) | ((infoHeader[22] & 0xFF) << 16) | ((infoHeader[23] & 0xFF) << 24);
+ byte[] compressed = new byte[compressedSize];
+ try {
+ if (inputStream.read(compressed) != compressedSize)
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ decompressData(compressed, data, stride, cmp);
+ }
+ return data;
+}
+int[] loadFileHeader() {
+ int[] header = new int[5];
+ try {
+ header[0] = inputStream.readShort();
+ header[1] = inputStream.readInt();
+ header[2] = inputStream.readShort();
+ header[3] = inputStream.readShort();
+ header[4] = inputStream.readInt();
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ if (header[0] != 0x4D42)
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ return header;
+}
+ImageData[] loadFromByteStream() {
+ int[] fileHeader = loadFileHeader();
+ byte[] infoHeader = new byte[BMPHeaderFixedSize];
+ try {
+ inputStream.read(infoHeader);
+ } catch (Exception e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ PaletteData palette = loadPalette(infoHeader);
+ if (inputStream.getPosition() < fileHeader[4]) {
+ // Seek to the specified offset
+ try {
+ inputStream.skip(fileHeader[4] - inputStream.getPosition());
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ }
+ byte[] data = loadData(infoHeader);
+ this.compression = (infoHeader[16] & 0xFF) | ((infoHeader[17] & 0xFF) << 8) | ((infoHeader[18] & 0xFF) << 16) | ((infoHeader[19] & 0xFF) << 24);
+ this.importantColors = (infoHeader[36] & 0xFF) | ((infoHeader[37] & 0xFF) << 8) | ((infoHeader[38] & 0xFF) << 16) | ((infoHeader[39] & 0xFF) << 24);
+ int xPelsPerMeter = (infoHeader[24] & 0xFF) | ((infoHeader[25] & 0xFF) << 8) | ((infoHeader[26] & 0xFF) << 16) | ((infoHeader[27] & 0xFF) << 24);
+ int yPelsPerMeter = (infoHeader[28] & 0xFF) | ((infoHeader[29] & 0xFF) << 8) | ((infoHeader[30] & 0xFF) << 16) | ((infoHeader[31] & 0xFF) << 24);
+ this.pelsPerMeter = new Point(xPelsPerMeter, yPelsPerMeter);
+ int width = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8) | ((infoHeader[6] & 0xFF) << 16) | ((infoHeader[7] & 0xFF) << 24);
+ int height = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24);
+ int bitCount = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8);
+ int type = (this.compression == 1 /*BMP_RLE8_COMPRESSION*/) || (this.compression == 2 /*BMP_RLE4_COMPRESSION*/) ? SWT.IMAGE_BMP_RLE : SWT.IMAGE_BMP;
+ return new ImageData[] {
+ ImageData.internal_new(
+ width,
+ height,
+ bitCount,
+ palette,
+ 4,
+ data,
+ 0,
+ null,
+ null,
+ -1,
+ -1,
+ type,
+ 0,
+ 0,
+ 0,
+ 0)
+ };
+}
+PaletteData loadPalette(byte[] infoHeader) {
+ int depth = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8);
+ if (depth <= 8) {
+ int numColors = (infoHeader[32] & 0xFF) | ((infoHeader[33] & 0xFF) << 8) | ((infoHeader[34] & 0xFF) << 16) | ((infoHeader[35] & 0xFF) << 24);
+ if (numColors == 0) {
+ numColors = 1 << ((infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8));
+ } else {
+ if (numColors > 256)
+ numColors = 256;
+ }
+ byte[] buf = new byte[numColors * 4];
+ try {
+ if (inputStream.read(buf) != buf.length)
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ return paletteFromBytes(buf, numColors);
+ }
+ if (depth == 16)
+ return new PaletteData(0x7C00, 0x3E0, 0x1F);
+ return new PaletteData(0xFF, 0xFF00, 0xFF0000);
+}
+PaletteData paletteFromBytes(byte[] bytes, int numColors) {
+ int bytesOffset = 0;
+ RGB[] colors = new RGB[numColors];
+ for (int i = 0; i < numColors; i++) {
+ colors[i] = new RGB(bytes[bytesOffset + 2] & 0xFF,
+ bytes[bytesOffset + 1] & 0xFF,
+ bytes[bytesOffset] & 0xFF);
+ bytesOffset += 4;
+ }
+ return new PaletteData(colors);
+}
+/**
+ * Answer a byte array containing the BMP representation of
+ * the given device independent palette.
+ */
+byte[] paletteToBytes(PaletteData pal) {
+ int n = (pal.colors.length < 256) ? pal.colors.length : 256;
+ byte[] bytes = new byte[n * 4];
+ int offset = 0;
+ for (int i = 0; i < n; i++) {
+ RGB col = pal.colors[i];
+ bytes[offset] = (byte)col.blue;
+ bytes[offset + 1] = (byte)col.green;
+ bytes[offset + 2] = (byte)col.red;
+ offset += 4;
+ }
+ return bytes;
+}
+/**
+ * Unload the given image's data into the given byte stream
+ * using the given compression strategy.
+ * Answer the number of bytes written.
+ */
+int unloadData(ImageData image, OutputStream out, int comp) {
+ int totalSize = 0;
+ try {
+ if (comp == 0)
+ return unloadDataNoCompression(image, out);
+ int bpl = (image.width * image.depth + 7) / 8;
+ int bmpBpl = (bpl + 3) / 4 * 4; // BMP pads scanlines to multiples of 4 bytes
+ int imageBpl = image.bytesPerLine;
+ // Compression can actually take twice as much space, in worst case
+ byte[] buf = new byte[bmpBpl * 2];
+ int srcOffset = imageBpl * (image.height - 1); // Start at last line
+ byte[] data = image.data;
+ totalSize = 0;
+ byte[] buf2 = new byte[32768];
+ int buf2Offset = 0;
+ for (int y = image.height - 1; y >= 0; y--) {
+ int lineSize = compress(comp, data, srcOffset, bpl, buf, y == 0);
+ if (buf2Offset + lineSize > buf2.length) {
+ out.write(buf2, 0, buf2Offset);
+ buf2Offset = 0;
+ }
+ System.arraycopy(buf, 0, buf2, buf2Offset, lineSize);
+ buf2Offset += lineSize;
+ totalSize += lineSize;
+ srcOffset -= imageBpl;
+ }
+ if (buf2Offset > 0)
+ out.write(buf2, 0, buf2Offset);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ return totalSize;
+}
+/**
+ * Prepare the given image's data for unloading into a byte stream
+ * using no compression strategy.
+ * Answer the number of bytes written.
+ */
+int unloadDataNoCompression(ImageData image, OutputStream out) {
+ int bmpBpl = 0;
+ try {
+ int bpl = (image.width * image.depth + 7) / 8;
+ bmpBpl = (bpl + 3) / 4 * 4; // BMP pads scanlines to multiples of 4 bytes
+ int linesPerBuf = 32678 / bmpBpl;
+ byte[] buf = new byte[linesPerBuf * bmpBpl];
+ byte[] data = image.data;
+ int imageBpl = image.bytesPerLine;
+ int dataIndex = imageBpl * (image.height - 1); // Start at last line
+ if (image.depth == 16) {
+ for (int y = 0; y < image.height; y += linesPerBuf) {
+ int count = image.height - y;
+ if (linesPerBuf < count) count = linesPerBuf;
+ int bufOffset = 0;
+ for (int i = 0; i < count; i++) {
+ for (int wIndex = 0; wIndex < bpl; wIndex += 2) {
+ buf[bufOffset + wIndex + 1] = data[dataIndex + wIndex + 1];
+ buf[bufOffset + wIndex] = data[dataIndex + wIndex];
+ }
+ bufOffset += bmpBpl;
+ dataIndex -= imageBpl;
+ }
+ out.write(buf, 0, bufOffset);
+ }
+ } else {
+ for (int y = 0; y < image.height; y += linesPerBuf) {
+ int tmp = image.height - y;
+ int count = tmp < linesPerBuf ? tmp : linesPerBuf;
+ int bufOffset = 0;
+ for (int i = 0; i < count; i++) {
+ System.arraycopy(data, dataIndex, buf, bufOffset, bpl);
+ bufOffset += bmpBpl;
+ dataIndex -= imageBpl;
+ }
+ out.write(buf, 0, bufOffset);
+ }
+ }
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ return bmpBpl * image.height;
+}
+/**
+ * Unload a DeviceIndependentImage using Windows .BMP format into the given
+ * byte stream.
+ */
+void unloadIntoByteStream(ImageData image) {
+ byte[] rgbs;
+ int numCols;
+ if (!((image.depth == 1) || (image.depth == 4) || (image.depth == 8) ||
+ (image.depth == 16) || (image.depth == 24)))
+ SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH);
+ int comp = this.compression;
+ if (!((comp == 0) || ((comp == 1) && (image.depth == 8)) ||
+ ((comp == 2) && (image.depth == 4))))
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ PaletteData pal = image.palette;
+ if ((image.depth == 16) || (image.depth == 24)) {
+ if (!pal.isDirect)
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ numCols = 0;
+ rgbs = null;
+ } else {
+ if (pal.isDirect)
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ numCols = pal.colors.length;
+ rgbs = paletteToBytes(pal);
+ }
+ // Fill in file header, except for bfsize, which is done later.
+ int headersSize = 54;
+ int[] fileHeader = new int[5];
+ fileHeader[0] = 0x4D42; // Signature
+ fileHeader[1] = 0; // File size - filled in later
+ fileHeader[2] = 0; // Reserved 1
+ fileHeader[3] = 0; // Reserved 2
+ fileHeader[4] = headersSize; // Offset to data
+ if (rgbs != null) {
+ fileHeader[4] += rgbs.length;
+ }
+
+ // Prepare data. This is done first so we don't have to try to rewind
+ // the stream and fill in the details later.
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ unloadData(image, out, comp);
+ byte[] compressedData = out.toByteArray();
+
+ // Calculate file size
+ fileHeader[1] = fileHeader[4] + compressedData.length;
+
+ // Write the headers
+ try {
+ outputStream.writeShort(fileHeader[0]);
+ outputStream.writeInt(fileHeader[1]);
+ outputStream.writeShort(fileHeader[2]);
+ outputStream.writeShort(fileHeader[3]);
+ outputStream.writeInt(fileHeader[4]);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ try {
+ outputStream.writeInt(WinBMPFileFormat.BMPHeaderFixedSize);
+ outputStream.writeInt(image.width);
+ outputStream.writeInt(image.height);
+ outputStream.writeShort(1);
+ outputStream.writeShort((short)image.depth);
+ outputStream.writeInt(comp);
+ outputStream.writeInt(compressedData.length);
+ outputStream.writeInt(pelsPerMeter.x);
+ outputStream.writeInt(pelsPerMeter.y);
+ outputStream.writeInt(numCols);
+ outputStream.writeInt(importantColors);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+
+ // Unload palette
+ if (numCols > 0) {
+ try {
+ outputStream.write(rgbs);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ }
+
+ // Unload the data
+ try {
+ outputStream.write(compressedData);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+}
+void flipScanLines(byte[] data, int stride, int height) {
+ int i1 = 0;
+ int i2 = (height - 1) * stride;
+ for (int i = 0; i < height / 2; i++) {
+ for (int index = 0; index < stride; index++) {
+ byte b = data[index + i1];
+ data[index + i1] = data[index + i2];
+ data[index + i2] = b;
+ }
+ i1 += stride;
+ i2 -= stride;
+ }
+}
+
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/WinICOFileFormat.java b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/WinICOFileFormat.java
new file mode 100755
index 0000000000..4ff4b0d3f9
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/WinICOFileFormat.java
@@ -0,0 +1,284 @@
+package org.eclipse.swt.internal.image;
+
+/*
+ * Licensed Materials - Property of IBM,
+ * WebSphere Studio Workbench
+ * (c) Copyright IBM Corp 2000
+ */
+
+/* Imports */
+import org.eclipse.swt.*;
+import org.eclipse.swt.graphics.*;
+import java.io.*;
+
+/* Class Definition */
+final class WinICOFileFormat extends FileFormat {
+/**
+ * Answer the size in bytes of the file representation of the given
+ * icon
+ */
+int iconSize(ImageData i) {
+ int shapeDataStride = (i.width * i.depth + 31) / 32 * 4;
+ int maskDataStride = (i.width + 31) / 32 * 4;
+ int dataSize = (shapeDataStride + maskDataStride) * i.height;
+ return WinBMPFileFormat.BMPHeaderFixedSize + (i.palette.colors.length * 4) + dataSize;
+}
+public static boolean isICOFile(LEDataInputStream stream) {
+ try {
+ byte[] header = new byte[4];
+ stream.read(header);
+ stream.unread(header);
+ return header[0] == 0 && header[1] == 0 && header[2] == 1 && header[3] == 0;
+ } catch (Exception e) {
+ return false;
+ }
+}
+boolean isValidIcon(ImageData i) {
+ if (!((i.depth == 1) || (i.depth == 4) || (i.depth == 8)))
+ return false;
+ int size = i.palette.colors.length;
+ return ((size == 2) || (size == 16) || (size == 32) || (size == 256));
+}
+int loadFileHeader(LEDataInputStream byteStream) {
+ int[] fileHeader = new int[3];
+ try {
+ fileHeader[0] = byteStream.readShort();
+ fileHeader[1] = byteStream.readShort();
+ fileHeader[2] = byteStream.readShort();
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ if ((fileHeader[0] != 0) || (fileHeader[1] != 1))
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ int numIcons = fileHeader[2];
+ if (numIcons <= 0)
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ return numIcons;
+}
+int loadFileHeader(LEDataInputStream byteStream, boolean hasHeader) {
+ int[] fileHeader = new int[3];
+ try {
+ if (hasHeader) {
+ fileHeader[0] = byteStream.readShort();
+ fileHeader[1] = byteStream.readShort();
+ } else {
+ fileHeader[0] = 0;
+ fileHeader[1] = 1;
+ }
+ fileHeader[2] = byteStream.readShort();
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ if ((fileHeader[0] != 0) || (fileHeader[1] != 1))
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ int numIcons = fileHeader[2];
+ if (numIcons <= 0)
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ return numIcons;
+}
+ImageData[] loadFromByteStream() {
+ int numIcons = loadFileHeader(inputStream);
+ int[][] headers = loadIconHeaders(numIcons);
+ ImageData[] icons = new ImageData[headers.length];
+ for (int i = 0; i < icons.length; i++) {
+ icons[i] = loadIcon(headers[i]);
+ }
+ return icons;
+}
+/**
+ * Load one icon from the byte stream.
+ */
+ImageData loadIcon(int[] iconHeader) {
+ byte[] infoHeader = loadInfoHeader(iconHeader);
+ WinBMPFileFormat bmpFormat = new WinBMPFileFormat();
+ bmpFormat.inputStream = inputStream;
+ PaletteData palette = bmpFormat.loadPalette(infoHeader);
+ byte[] shapeData = bmpFormat.loadData(infoHeader);
+ int depth = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8);
+ infoHeader[14] = 1;
+ infoHeader[15] = 0;
+ byte[] maskData = bmpFormat.loadData(infoHeader);
+ bitInvertData(maskData, 0, maskData.length);
+ int infoWidth = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8) | ((infoHeader[6] & 0xFF) << 16) | ((infoHeader[7] & 0xFF) << 24);
+ int infoHeight = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24);
+ return ImageData.internal_new(
+ infoWidth,
+ infoHeight,
+ depth,
+ palette,
+ 4,
+ shapeData,
+// 4,
+ 2,
+ maskData,
+ null,
+ -1,
+ -1,
+ SWT.IMAGE_ICO,
+ 0,
+ 0,
+ 0,
+ 0);
+}
+int[][] loadIconHeaders(int numIcons) {
+ int[][] headers = new int[numIcons][7];
+ try {
+ for (int i = 0; i < numIcons; i++) {
+ headers[i][0] = inputStream.read();
+ headers[i][1] = inputStream.read();
+ headers[i][2] = inputStream.readShort();
+ headers[i][3] = inputStream.readShort();
+ headers[i][4] = inputStream.readShort();
+ headers[i][5] = inputStream.readInt();
+ headers[i][6] = inputStream.readInt();
+ }
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ return headers;
+}
+byte[] loadInfoHeader(int[] iconHeader) {
+ int width = iconHeader[0];
+ int height = iconHeader[1];
+ int numColors = iconHeader[2];
+ if ((numColors != 2) && (numColors != 8) && (numColors != 16) &&
+ (numColors != 32) && (numColors != 256))
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ if (inputStream.getPosition() < iconHeader[6]) {
+ // Seek to the specified offset
+ try {
+ inputStream.skip(iconHeader[6] - inputStream.getPosition());
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ return null;
+ }
+ }
+ byte[] infoHeader = new byte[WinBMPFileFormat.BMPHeaderFixedSize];
+ try {
+ inputStream.read(infoHeader);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ if (((infoHeader[12] & 0xFF) | ((infoHeader[13] & 0xFF) << 8)) != 1)
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ int infoWidth = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8) | ((infoHeader[6] & 0xFF) << 16) | ((infoHeader[7] & 0xFF) << 24);
+ int infoHeight = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24);
+ int bitCount = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8);
+ if (height == infoHeight && bitCount == 1) height /= 2;
+ if (!((width == infoWidth) && (height * 2 == infoHeight) &&
+ ((bitCount == 1) || (bitCount == 4) || (bitCount == 8))))
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ infoHeader[8] = (byte)(height & 0xFF);
+ infoHeader[9] = (byte)((height >> 8) & 0xFF);
+ infoHeader[10] = (byte)((height >> 16) & 0xFF);
+ infoHeader[11] = (byte)((height >> 24) & 0xFF);
+ return infoHeader;
+}
+/**
+ * Unload a single icon
+ */
+void unloadIcon(ImageData icon) {
+ int sizeImage = (((icon.width * icon.depth + 31) / 32 * 4) +
+ ((icon.width + 31) / 32 * 4)) * icon.height;
+ try {
+ outputStream.writeInt(WinBMPFileFormat.BMPHeaderFixedSize);
+ outputStream.writeInt(icon.width);
+ outputStream.writeInt(icon.height * 2);
+ outputStream.writeShort(1);
+ outputStream.writeShort((short)icon.depth);
+ outputStream.writeInt(0);
+ outputStream.writeInt(sizeImage);
+ outputStream.writeInt(0);
+ outputStream.writeInt(0);
+ outputStream.writeInt(icon.palette.colors.length);
+ outputStream.writeInt(0);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+
+ byte[] rgbs = new WinBMPFileFormat().paletteToBytes(icon.palette);
+ try {
+ outputStream.write(rgbs);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ unloadShapeData(icon);
+ unloadMaskData(icon);
+}
+/**
+ * Unload the icon header for the given icon, calculating the offset.
+ */
+void unloadIconHeader(ImageData i) {
+ int headerSize = 16;
+ int offset = headerSize + 6;
+ int iconSize = iconSize(i);
+ try {
+ outputStream.writeByte((byte)i.width);
+ outputStream.writeByte((byte)i.height);
+ outputStream.writeShort(i.palette.colors.length);
+ outputStream.writeShort(0);
+ outputStream.writeShort(0);
+ outputStream.writeInt(iconSize);
+ outputStream.writeInt(offset);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+}
+void unloadIntoByteStream(ImageData image) {
+ if (!isValidIcon(image))
+ SWT.error(SWT.ERROR_INVALID_IMAGE);
+ try {
+ outputStream.writeShort(0);
+ outputStream.writeShort(1);
+ outputStream.writeShort(1);
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+ unloadIconHeader(image);
+ unloadIcon(image);
+}
+/**
+ * Unload the mask data for an icon. The data is flipped vertically
+ * and inverted.
+ */
+void unloadMaskData(ImageData icon) {
+ int bpl = (icon.width + 7) / 8;
+ int pad = 4;
+ int srcBpl = (bpl + pad - 1) / pad * pad;
+ int destBpl = (bpl + 3) / 4 * 4;
+ byte[] buf = new byte[destBpl];
+ int offset = (icon.height - 1) * srcBpl;
+ byte[] data = icon.getTransparencyMask().data;
+ try {
+ for (int i = 0; i < icon.height; i++) {
+ System.arraycopy(data, offset, buf, 0, bpl);
+ bitInvertData(buf, 0, bpl);
+ outputStream.write(buf, 0, destBpl);
+ offset -= srcBpl;
+ }
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+}
+/**
+ * Unload the shape data for an icon. The data is flipped vertically.
+ */
+void unloadShapeData(ImageData icon) {
+ int bpl = (icon.width * icon.depth + 7) / 8;
+ int pad = 4;
+ int srcBpl = (bpl + pad - 1) / pad * pad;
+ int destBpl = (bpl + 3) / 4 * 4;
+ byte[] buf = new byte[destBpl];
+ int offset = (icon.height - 1) * srcBpl;
+ byte[] data = icon.data;
+ try {
+ for (int i = 0; i < icon.height; i++) {
+ System.arraycopy(data, offset, buf, 0, bpl);
+ outputStream.write(buf, 0, destBpl);
+ offset -= srcBpl;
+ }
+ } catch (IOException e) {
+ SWT.error(SWT.ERROR_IO, e);
+ }
+}
+}
diff --git a/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/package.html b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/package.html
new file mode 100755
index 0000000000..62fccda519
--- /dev/null
+++ b/bundles/org.eclipse.swt/Eclipse SWT/common/org/eclipse/swt/internal/image/package.html
@@ -0,0 +1,18 @@
+ <html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <meta name="Author" content="IBM">
+ <title>Package-level Javadoc</title>
+</head>
+<body>
+SWT internal image loading/saving support classes.
+<h2>
+Package Specification</h2>
+This package contains the classes used by SWT to load and save images
+in the various formats we support, including GIF, JPEG, PNG, BMP, and ICO.
+<p>
+Applications should not need to reference the classes in this package
+directly.
+</p>
+</body>
+</html>

Back to the top