/*
 * 	File sform.c
 *	Demonstrates the use of the SCROLLEDFORM Object
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "mgui.h"

extern MTColor black, white, darkblue, cadetblue, seagreen;
extern int LowRes;

/**********************************************************
 *	Callback that Destroys the dialog and frees the
 *	image loaded
 **********************************************************/
void CloseSFormCB(MOBJECT p, void *s, void *adata)
{
	MOBJECT pixmap = (MOBJECT )adata;
	void *udata;

	p = MObjectShell(p);
	udata = MObjectGetUserData(pixmap);
	if (udata != NULL)
		MFreeImage((MIMAGE)udata);
	MShellUnrealize(p);
	MShellDestroy(p);
}

/**********************************************************
 *	This callback changes the image viewed
 **********************************************************/
void ChangeImageCB(MOBJECT p, void *s, void *adata)
{
	char fname[128], dirname[128];
	MIMAGE mpd, old_image;
	MOBJECT pixmap = (MOBJECT )adata;

#ifdef UNIX
#define stricmp	strcasecmp
#endif

	dirname[0] = '\0';
	fname[0] = '\0';
	if (MFileSelection("Select New Image", "", fname, dirname, True)) {
		strcat(dirname, fname);
#if defined JPEG_SUPPORTED
		if (!stricmp(fname + strlen(fname) - 3, "jpg"))
			mpd = MReadJPEGFile(dirname);
		else
#endif
#if defined TIFF_SUPPORTED
		if (!stricmp(fname + strlen(fname) - 3, "tif"))
			mpd = MReadTIFFFile(dirname);
		else
#endif
		if (!stricmp(fname + strlen(fname) - 3, "gif"))
			mpd = MReadGIFFile(dirname);
		else
			mpd = MReadBMPFile(dirname);

		if (mpd != NULL) {
			old_image = (MIMAGE)MObjectGetUserData(pixmap);
			if (old_image != NULL)
				MFreeImage(old_image);
			MObjectSetUserData(pixmap, (void *)mpd);
			MInstallImage(mpd);
			MPixmapSetImage(pixmap, mpd);
		}
	}
}

/*****************************************************
 *	This callback opens the dialog when the
 *	corresponding menu item is selected
 *****************************************************/
void ScrolledFormCB(MOBJECT o, void *o_data, void *a_data)
{
	MOBJECT shell, form, sform, pixmap;
	MOBJECT pbutton, sfile;
	MIMAGE image;

	shell = MCreateShell("Test Scrolled Form", 0);

	form = MCreateColForm(shell);

	sform = MCreateScrolledForm(form, 200, 250);

	MCreateLabel(sform, "Label inside the scrolled form", TIMES_L_FONT);
	image = MReadBMPFile("paulina1.bmp");
	if (image != NULL)
		MInstallImage(image);
	pixmap = MCreatePixmapFromData(sform, image);
	MObjectSetUserData(pixmap, (void *)image);

	sfile = MCreateSFile(form, __FILE__,
			(LowRes ? SMALL_FONT : DEFAULT_FONT),
			15, 54);
	MObjectSetColor(sfile, darkblue, white);

	form = MCreateColForm(shell);

	pbutton = MCreatePButton(form, "New Image", TIMES_L_FONT);
	MPButtonSetCallback(pbutton, ChangeImageCB, (void *)pixmap);
	pbutton = MCreatePButton(form, "Close", TIMES_L_FONT);
	MPButtonSetCallback(pbutton, CloseSFormCB, (void *)pixmap);

	MShellRealize(shell);
}
