/**********************************************************************
 
	Copyright (C) 2003-2004
	Hirohisa MORI <joshua@nichibun.ac.jp>
	Tomoki SEKIYAMA <sekiyama@yahoo.co.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	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.

**********************************************************************/



#include <LClipboard.h>

#include "v/VClipboard.h"
#include "machine/v_m.h"
extern "C" {
#include "memory_debug.h"
}

void * VClipboard::data = 0;
int VClipboard::data_type = 0;

bool
VClipboard::is_data_type_available(int type)
{
	return UScrap::HasData(type);
}

void
VClipboard::set_data_type(int type, int len, void *data, bool clear)
{
	if ( type == VDT_STRING && ((char*)data)[len-1] == 0 )
		len--;
	LClipboard::GetClipboard()->SetData(type, (char*)data, len, clear);
}

void *
VClipboard::get_data_type(int type, int &outLen)
{
	Handle handle = NewHandle(0);
	LClipboard::GetClipboard()->GetData(type, handle);
	HLock(handle);
	outLen = GetHandleSize(handle);
	if ( outLen ) {
		data = handle;
		data_type = type;
		return *handle;
	}
	data = 0;
	DisposeHandle(handle);
	return 0;
}

void
VClipboard::release_data()
{
	if ( data == 0 )
		return;
	Handle handle = (Handle)data;
	HUnlock(handle);
	DisposeHandle(handle);
	data = 0;
	data_type = 0;
}

VImage *
VClipboard::get_image()
{
	int len;
	PicPtr pict = (PicPtr)get_data_type(VDT_IMAGE, len);
	if ( !pict )
		return 0;
	short w = pict->picFrame.right - pict->picFrame.left;
	short h = pict->picFrame.bottom - pict->picFrame.top;
	Rect r = {0, 0, h, w};

	VImage *ret = v_image_new(w,h,32);
	v_image_draw_start(ret,0);
	ret->info->BeginDrawing();
	DrawPicture(&pict,&r);
	ret->info->EndDrawing();
	v_image_draw_end(ret);
	
	release_data();
	return ret;
}

void
VClipboard::set_image(VImage *img, int *outSize, bool clear)
{
	v_image_draw_start(img, 0);
	Rect r = {0, 0, img->size.h, img->size.w};
	const BitMap * bitmap = ::GetPortBitMapForCopyBits(img->info->GetMacGWorld());
	img->info->BeginDrawing();
	PicHandle pict = ::OpenPicture(&r);
	::CopyBits(bitmap, bitmap, &r, &r, srcCopy, NULL);
	::ClosePicture();
	img->info->EndDrawing();
	v_image_draw_end(img);
	
	*outSize = GetHandleSize((Handle)pict);
	HLock((Handle)pict);

	set_data_type(VDT_IMAGE, *outSize, *pict, clear);

	HUnlock((Handle)pict);
	KillPicture(pict);
}
