view org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet288.d @ 120:536e43f63c81

Comprehensive update for Win32/Linux32 dmd-2.053/dmd-1.068+Tango-r5661 ===D2=== * added [Try]Immutable/Const/Shared templates to work with differenses in D1/D2 instead of version statements used these templates to work with strict type storage rules of dmd-2.053 * com.ibm.icu now also compilable with D2, but not tested yet * small fixes Snippet288 - shared data is in TLS ===Phobos=== * fixed critical bugs in Phobos implemention completely incorrect segfault prone fromStringz (Linux's port ruthless killer) terrible, incorrect StringBuffer realization (StyledText killer) * fixed small bugs as well Snippet72 - misprint in the snippet * implemented missed functionality for Phobos ByteArrayOutputStream implemented (image loading available) formatting correctly works for all DWT's cases As a result, folowing snippets now works with Phobos (Snippet### - what is fixed): Snippet24, 42, 111, 115, 130, 235, 276 - bad string formatting Snippet48, 282 - crash on image loading Snippet163, 189, 211, 213, 217, 218, 222 - crash on copy/cut in StyledText Snippet244 - hang-up ===Tango=== * few changes for the latest Tango trunc-r5661 * few small performance improvments ===General=== * implMissing-s for only one version changed to implMissingInTango/InPhobos * incorrect calls to Format in toString-s fixed * fixed loading \uXXXX characters in ResourceBundle * added good UTF-8 support for StyledText, TextLayout (Win32) and friends UTF functions revised and tested. It is now in java.nonstandard.*Utf modules StyledText and TextLayout (Win32) modules revised for UTF-8 support * removed small diferences in most identical files in *.swt.* folders *.swt.internal.image, *.swt.events and *.swt.custom are identical in Win32/Linux32 now 179 of 576 (~31%) files in *.swt.* folders are fully identical * Win32: snippets now have right subsystem, pretty icons and native system style controls * small fixes in snippets Snippet44 - it's not Snippet44 Snippet212 - functions work with different images and offsets arrays Win32: Snippet282 - crash on close if the button has an image Snippet293 - setGrayed is commented and others Win32: As a result, folowing snippets now works Snippet68 - color doesn't change Snippet163, 189, 211, 213, 217, 218, 222 - UTF-8 issues (see above) Snippet193 - no tabel headers
author Denis Shelomovskij <verylonglogin.reg@gmail.com>
date Sat, 09 Jul 2011 15:50:20 +0300
parents 9f4c18c268b2
children
line wrap: on
line source

/*******************************************************************************
 * Copyright (c) 2008 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
module org.eclipse.swt.snippets.Snippet288;

/*
 * Create a ToolBar containing animated GIFs
 *
 * For a list of all SWT example snippets see
 * http://www.eclipse.org/swt/snippets/
 */
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.FileDialog;

import java.lang.all;

version(Tango){
    import tango.io.FilePath;
    import tango.io.model.IFile;
    //import tango.core.Thread;
    import tango.io.Stdout;
    import tango.util.Convert;
    import tango.core.Exception;
} else { // Phobos
    import std.path;
    import std.stream;
    import std.stdio;
    import std.conv;
    import core.exception;
    import core.thread : ThreadException;
    struct FileConst {
        static const PathSeparatorChar = sep;
    }
}

mixin(gshared!("
Display display;
Shell shell;
GC shellGC;
Color shellBackground;
ImageLoader[] loader;
ImageData[][] imageDataArray;
Thread[] animateThread;
Image[][] image;
ToolItem[] item;
"));
const bool useGIFBackground = false;

void main () {
    display = new Display();
    Shell shell = new Shell (display);
    shellBackground = shell.getBackground();
    FileDialog dialog = new FileDialog(shell, SWT.OPEN | SWT.MULTI);
    dialog.setText("Select Multiple Animated GIFs");
    dialog.setFilterExtensions(["*.gif"]);
    String filename = dialog.open();
    String[] filenames = dialog.getFileNames();
    int numToolBarItems = filenames.length;
    if (numToolBarItems > 0) {
        version(Tango){
            try {
                loadAllImages((new FilePath(filename)).parent, filenames);
            } catch (SWTException e) {
                Stdout.print("There was an error loading an image.").newline;
                e.printStackTrace();
            }
        } else { // Phobos
            try {
                loadAllImages(filename.getDirName, filenames);
            } catch (SWTException e) {
                writeln("There was an error loading an image.");
                e.printStackTrace();
            }
        }
        ToolBar toolBar = new ToolBar (shell, SWT.FLAT | SWT.BORDER | SWT.WRAP);
        item = new ToolItem[numToolBarItems];
        for (int i = 0; i < numToolBarItems; i++) {
            item[i] = new ToolItem (toolBar, SWT.PUSH);
            item[i].setImage(image[i][0]);
        }
        toolBar.pack ();
        shell.open ();
			
        startAnimationThreads();
			
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch ()) display.sleep ();
        }
			
        for (int i = 0; i < numToolBarItems; i++) {
            for (int j = 0; j < image[i].length; j++) {
                image[i][j].dispose();
            }
        }
        display.dispose ();
    }
    Thread.joinAll();
}

void loadAllImages(String directory, String[] filenames) {
    int numItems = filenames.length;
    loader.length = numItems;
    imageDataArray.length = numItems;
    image.length = numItems;
    for (int i = 0; i < numItems; i++) {
        loader[i] = new ImageLoader();
        int fullWidth = loader[i].logicalScreenWidth;
        int fullHeight = loader[i].logicalScreenHeight;
        imageDataArray[i] = loader[i].load(directory ~ FileConst.PathSeparatorChar ~ filenames[i]);
        int numFramesOfAnimation = imageDataArray[i].length;
        image[i] = new Image[numFramesOfAnimation];
        for (int j = 0; j < numFramesOfAnimation; j++) {
            if (j == 0) {
                //for the first frame of animation, just draw the first frame
                image[i][j] = new Image(display, imageDataArray[i][j]);
                fullWidth = imageDataArray[i][j].width;
                fullHeight = imageDataArray[i][j].height;
            }
            else {
                //after the first frame of animation, draw the background or previous frame first, then the new image data 
                image[i][j] = new Image(display, fullWidth, fullHeight);
                GC gc = new GC(image[i][j]);
                gc.setBackground(shellBackground);
                gc.fillRectangle(0, 0, fullWidth, fullHeight);
                ImageData imageData = imageDataArray[i][j];
                switch (imageData.disposalMethod) {
                case SWT.DM_FILL_BACKGROUND:
                    /* Fill with the background color before drawing. */
                    Color bgColor = null;
                    if (useGIFBackground && loader[i].backgroundPixel != -1) {
                        bgColor = new Color(display, imageData.palette.getRGB(loader[i].backgroundPixel));
                    }
                    gc.setBackground(bgColor !is null ? bgColor : shellBackground);
                    gc.fillRectangle(imageData.x, imageData.y, imageData.width, imageData.height);
                    if (bgColor !is null) bgColor.dispose();
                    break;
                default:
                    /* Restore the previous image before drawing. */
                    gc.drawImage(
                        image[i][j-1],
                        0,
                        0,
                        fullWidth,
                        fullHeight,
                        0,
                        0,
                        fullWidth,
                        fullHeight);
                    break;
                }
                Image newFrame = new Image(display, imageData);
                gc.drawImage(newFrame,
                             0,
                             0,
                             imageData.width,
                             imageData.height,
                             imageData.x,
                             imageData.y,
                             imageData.width,
                             imageData.height);
                newFrame.dispose();
                gc.dispose();
            }
        }
    }
}

void startAnimationThreads() {
    animateThread = new Thread[image.length];
    for (int ii = 0; ii < image.length; ii++) {
        animateThread[ii] = new class(ii) Thread {
            int imageDataIndex = 0;
            int id = 0;
            this(int _id) { 
                id = _id;
                //name = "Animation "~to!(char[])(ii);
                //isDaemon = true;
                super(&run);
            }
            void run() {
                try {
                    int repeatCount = loader[id].repeatCount;
                    while (loader[id].repeatCount == 0 || repeatCount > 0) {
                        imageDataIndex = (imageDataIndex + 1) % imageDataArray[id].length;
                        if (!display.isDisposed()) {
                            display.asyncExec(new class Runnable {
									public void run() {
										if (!item[id].isDisposed())
											item[id].setImage(image[id][imageDataIndex]);
									}
								});
                        }
							
                        /* Sleep for the specified delay time (adding commonly-used slow-down fudge factors). */
                        try {
                            int ms = imageDataArray[id][imageDataIndex].delayTime * 10;
                            if (ms < 20) ms += 30;
                            if (ms < 30) ms += 10;
                            Thread.sleep(1 * ms);
                        } catch (ThreadException e) {
                        }

                        /* If we have just drawn the last image, decrement the repeat count and start again. */
                        if (imageDataIndex == imageDataArray[id].length - 1) repeatCount--;
                    }
                } catch (SWTException ex) {
                    version(Tango){
                        Stdout.print("There was an error animating the GIF").newline;
                    } else { // Phobos
                        writeln("There was an error animating the GIF");
                    }
                    ex.printStackTrace();
                }
            }
        };
        animateThread[ii].start();
    }
}