#include "g_visu.h"
#include "v_view.h"
#include "v_menu.h"
#include "v_extern.h"

extern LAMBDA xscreen, yscreen, dxscreen, dyscreen;
extern int C_atomicValue, V_lock;
extern char run_mode;

/* redraws the entire contents of the database to the screen */
void V_refresh()
{
GC gc = V_gcCao[GC_FGND];
char mode = run_mode;

	run_mode = STEP;
	/* clearing the window and it's associated pixmap */
	V_changeCursor(0);
	XFlush(display);
	XClearArea(display, V_window, 0, YMENU, dxWin, dyWin, False);
	XSetFillStyle(display, gc, FillSolid);
	XSetForeground(display, gc, V_colors[COLOR_BGND]);
	XFillRectangle(display, V_PixSave, gc, 0, YMENU, dxWin, dyWin);
	XSetForeground(display, gc, V_colors[COLOR_FGND]);
	if (V_lock == 1)
		if (peek(xscreen - 4 , yscreen - 4, dxscreen + 8, dyscreen + 8) == 1) {
			V_peek_it(ON, 0, YMENU, dxWin, dyWin);
			unpeek();
		}
	if (!C_atomicValue || !V_lock)
		put_it(V_window, xscreen, yscreen, dxscreen, dyscreen);
	V_changeCursor(1);
	run_mode = mode;
}

/* redraws part of the screen due to a partial exposure.
   some strange behavior lead me to believe that the expose event
   gives underestimated results, so I add some stuff on the borders. */
#define SOME_MORE_STUFF 10
void V_refreshArea(x, y, dx, dy)
long x, y, dx, dy;
{
GC gc = V_gcCao[GC_FGND];
char mode = run_mode;

	V_changeCursor(0);
	XFlush(display); /* do not wait for the buffer to be filled */
	XSetFillStyle(display, gc, FillSolid);
	XSetForeground(display, gc, V_colors[COLOR_BGND]);
	XFillRectangle(display, V_PixSave, gc, 0, 0, dxWin, dyWin + YMENU);
	XSetForeground(display, gc, V_colors[COLOR_FGND]);
	x -= SOME_MORE_STUFF;
	y -= SOME_MORE_STUFF;
	dx += 2 * SOME_MORE_STUFF;
	dy += 2 * SOME_MORE_STUFF;
	if (V_lock == 1)
		if (peek(xscreen +(long)(x / scale) - 1,
				yscreen + dyscreen +(long)(YMENU / scale) -
				(long)((y + dy) / scale) - 1,
				(long)(dx / scale) + 1,(long)(dy / scale) + 1) == 1) {
			V_peek_it(OFF, x, y, dx, dy); /* do not transfer yet */
			unpeek();
		}
	if (!C_atomicValue)
		put_it(V_PixSave, xscreen +(long)(x / scale) - 1,
				yscreen + dyscreen + (long)(YMENU / scale) 
				- (long)((y + dy) / scale) - 1,
				(long)(dx / scale) + 1,(long)(dy / scale) + 1);
	x += SOME_MORE_STUFF;
	y += SOME_MORE_STUFF;
	dx -= 2 * SOME_MORE_STUFF;
	dy -= 2 * SOME_MORE_STUFF;
	XCopyArea(display, V_PixSave, V_window, gc, x, y, dx, dy, x, y);
	V_drawAB();
	V_drawPointer(0, 0);
	V_changeCursor(1);
	run_mode = mode;
}

void V_saveWindow()
{
GC gc = V_gcCao[GC_FGND];

	XCopyArea(display, V_window, V_PixSave, gc, 0, 0,
					dxWin, dyWin + YMENU, 0, 0);
}

void V_restoreWindow()
{
GC gc = V_gcCao[GC_FGND];

	XCopyArea(display, V_PixSave, V_window, gc, 0, 0,
					dxWin, dyWin + YMENU, 0, 0);
}
