/*
 *  WindowMaker window manager
 * 
 *  Copyright (c) 1997 Alfredo K. Kojima
 * 
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "wconfig.h"

#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include <stdlib.h>
#include <unistd.h>

#include "generic/wwmlib.h"
#include "WindowMaker.h"
#include "screen.h"


#define PSIZE 4
#define PIECES ((64/PSIZE)*(64/PSIZE))


void
DoKaboom(WScreen *scr, Window win, int x, int y)
{
    int i, j, k;
    int sw=scr->scr_width, sh=scr->scr_height;
    short px[PIECES], py[PIECES];
    char pvx[PIECES], pvy[PIECES];
    char ax[PIECES], ay[PIECES];
    Pixmap tmp;
    XImage *img;
    
    img=XGetImage(dpy, win, 0, 0, 64, 64, AllPlanes, ZPixmap);
    XUnmapWindow(dpy,win);
    if (!img)
      return;
    XSetClipMask(dpy, scr->copy_gc, None);
    tmp = XCreatePixmap(dpy, scr->root_win, 64, 64, scr->depth);
    XPutImage(dpy, tmp, scr->copy_gc, img, 0, 0, 0, 0, 64, 64);
    XDestroyImage(img);
    for (i=0,k=0; i<64/PSIZE; i++) {
	for (j=0; j<64/PSIZE; j++) {
	    if (rand()%3) {
		ax[k]=i;
		ay[k]=j;
		px[k]=x+i*PSIZE;
		py[k]=y+j*PSIZE;
		pvx[k]=rand()%7-3;
		pvy[k]=-12-rand()%6;
		k++;
	    } else {
		ax[k]=-1;
	    }
	}
    }
    j=k;
    while (k>0) {
	for (i=0; i<j; i++) {
	    if (ax[i]>=0) {
		px[i]+=pvx[i];
		py[i]+=pvy[i];
		pvy[i]++;
		if (px[i]<-64 || px[i]>sw || py[i]>sh) {
		    ax[i]=-1;
		    k--;
		} else {
		    XCopyArea(dpy, tmp, scr->root_win, scr->copy_gc, 
			      ax[i]*PSIZE, ay[i]*PSIZE, 
			      PSIZE, PSIZE, px[i], py[i]);
		}
	    }
	}
#if (MINIATURIZE_ANIMATION_DELAY > 0)	
	wmsleep(MINIATURIZE_ANIMATION_DELAY*2);
#endif
	for (i=0; i<j; i++) {
	    if (ax[i]>=0) {
		XClearArea(dpy, scr->root_win, px[i], py[i], PSIZE, PSIZE, 1);
	    }
	}
    }
    XFreePixmap(dpy, tmp);
}

