/*
 *	File mledit.c
 *	Demonstrates the use of the MULTI LINE EDIT Object
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "mgui.h"

#define IsEven(a)	(!((a)&1))

/*
 *	Callback for closing and destroying a generic dialog
 */
extern void CloseDialogCB(MOBJECT p, void *s, void *v);

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

/*****************************************************
 *	This Callback is called by the EDIT
 *	when its cursor position changes.
 *****************************************************/
void MLCursorPositionCB(MOBJECT edit, EDIT_CURS *ec, void *lbl)
{
	char str[128];

	sprintf(str, "Pos: %4d X: %3d Y: %3d", ec->pos, ec->pos_x, ec->pos_y);
        MObjectSetText((MOBJECT )lbl, str);
}

/*****************************************************
 *	This Callback is called by the EDIT when its
 *	text value has changed.
 *****************************************************/
void MLNewValueCB(MOBJECT edit, char *new_value, void *label)
{
/*
 * The EDIT Text has been modified!
 */
	if (MObjectGetUserData(edit) == NULL)
		MObjectSetText((MOBJECT )label, "Modified");
	MObjectSetUserData(edit, (void *)True);
}

/*****************************************************
 *	This callback opens the dialog when the
 *	corresponding menu item is selected
 *****************************************************/
void MLEditCB(MOBJECT obj, void *a, void *b)
{
	MOBJECT shell, pb, edit, cform, mod_label, curs_label;
	FILE *fp;
	char *buff;
	int flen, nr;

	shell = MCreateShell("Multi Line Edit", 0);

	cform = MCreateColForm(shell);
	mod_label = MCreateLabel(cform, "Unmodified", HELV_L_FONT);
	MObjectSetResize(mod_label, False, False);
	curs_label = MCreateLabel(cform, "", DEFAULT_FONT);
	buff = NULL;
	if ((fp = fopen(__FILE__, "r")) != NULL) {
                flen = 32000;
		if ((buff = (char *)malloc(flen)) != NULL) {
			nr = fread(buff, 1, flen-1, fp);
			buff[nr] = '\0';
		}
		fclose(fp);
	}

	edit = MCreateScrolledMLEdit(shell,
		(buff != NULL ? buff : ""), 40, 20, DEFAULT_FONT);
	if (buff != NULL)
		free(buff);
        MObjectSetColor(edit, seagreen, black);
	MEditSetCursorPosCallback(edit, MLCursorPositionCB, curs_label);
	MEditSetNewValueCallback(edit, MLNewValueCB, mod_label);

/*
 * This PUSH BUTTON closes the dialog
 */
	pb = MCreatePButton(shell, "Close", TIMES_L_FONT);
	MPButtonSetCallback(pb, CloseDialogCB, 0L);

	MShellRealize(shell);
}
