/*
 *
 * edit.c
 *
 * Copyright (c) 1990 by Sun Microsystems, Inc.
 */

/* 
 * Implementation of a simple "remote-control" editor. Accepts requests
 * to edit, save, and close files as well as hilite "objects" created in
 * the file. Objects are kept track of by wrapping them in C-style
 * comments with their respective object ids. 
 */
#include <stdio.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/types.h>
#include <xview/xview.h>
#include <xview/panel.h>
#include <xview/textsw.h>
#include <xview/xv_xrect.h>
#include <xview/seln.h>
#include <desktop/tt_c.h>
#include "Sun_EditDemo_opnums.h"

Xv_Server	edit_ui_xserver;
Xv_opaque	edit_ui_base_window;
Xv_opaque	edit_ui_textpane;
Xv_opaque	edit_ui_panel;
Xv_opaque	edit_ui_obj_button;

void
main(argc, argv)
	int		argc;
	char		**argv;
{
	char		*dfile;

	/*
	 * Initialize XView.
	 */
	xv_init(XV_INIT_ARGC_PTR_ARGV, &argc, argv, 0);
	
	/*
	 * Initialize user interface components.
	 */
	edit_ui_initialize();
	if (! edit_init_tt()) {
		fprintf(stderr,"%s: Can't initialize ToolTalk\n", argv[0]);
		exit(1);
	}
	/*
	 * Turn control over to XView.
	 */
	xv_main_loop(edit_ui_base_window);
	if ((dfile = tt_default_file()) != (char *)0) {
		tt_file_quit(dfile);
	}
	tt_close();
	exit(0);
}

/* 
 * Initialize our ToolTalk environment.
 */
int
edit_init_tt()
{
	int	mark;
	char	*procid = tt_open();
	int	ttfd;
	void	edit_receive_tt_message();

	mark = tt_mark();

	if (tt_pointer_error(procid) != TT_OK) {
		return 0;
	}
	if (tt_ptype_declare("Sun_EditDemo") != TT_OK) {
		fprintf(stderr,"Sun_EditDemo is not an installed ptype.\n");
		return 0;
	}
	ttfd = tt_fd();
	notify_set_input_func(edit_ui_base_window,
			      (Notify_func)edit_receive_tt_message,
			      ttfd);

	tt_session_join(tt_default_session());

	/*
	 * Note that without tt_mark() and tt_release(), the above
	 * combination would leak storage -- tt_default_session() returns
	 * a copy owned by the application, but since we don't assign the
	 * pointer to a variable we could not free it explicitly.
	 */

	tt_release(mark);
	return 1;
}


/* 
 * Handle any incoming ToolTalk messages.
 */
void
edit_receive_tt_message()
{
	Tt_message		msg_in;
	int			opnum;
	int                     opstatus;
	char 			*file;

	msg_in = tt_message_receive();
	if (msg_in == NULL) return;
	if (tt_pointer_error(msg_in) == TT_ERR_NOMP) {
		fprintf(stderr,"ToolTalk server down.\n");
		exit(0);
	}
	switch (tt_message_opnum(msg_in)) {
	      case SUN_EDITDEMO_EDIT:
	        opstatus = edit_edit(msg_in);
		break;
	      case SUN_EDITDEMO_SAVE:
		opstatus = edit_save(msg_in);
		break;
	      case SUN_EDITDEMO_SAVE_AS:
		opstatus = edit_save(msg_in);
		break;
	      case SUN_EDITDEMO_CLOSE:
		opstatus = edit_close(msg_in);
		break;
	      case SUN_EDITDEMO_HILITE_OBJ:
		opstatus = edit_hilite_obj(msg_in);
		break;
	      default:
		/* don't know what else to do with this message */
		tt_message_reject(msg_in);
		break;
	}
	if (opstatus == 0) {
		tt_message_fail(msg_in);
	} else {
		tt_message_reply(msg_in);
	}
	tt_message_destroy(msg_in);

	return;
}


/* 
 * Handle the "edit" op.
 */
int
edit_edit(msg)
     Tt_message msg;
{
	int	mark = tt_mark();
	char	*file = tt_message_file(msg);
	char	*dfile = tt_default_file();
	char	buf[255];

	if (access(file, R_OK) != 0) {
		tt_message_status_set(msg, TT_ERR_FILE);
		tt_message_status_string_set(msg,"Can't open file for read.");
		tt_release(mark);
		return 0;
	} else {
		if (dfile == (char *)0 || 0 != strcmp(dfile, file)) {
			/* if not already editing this file, load it */
			/* in. */
			tt_default_file_set(file);
			tt_file_join(file);
			xv_set(edit_ui_textpane, TEXTSW_FILE, file, NULL);
			sprintf(buf,"Sun_EditDemo_edit: (%s)", file);
			xv_set(edit_ui_base_window, XV_LABEL, buf, NULL);
		}
		/* in any case, open up the window if it's closed */
		xv_set(edit_ui_base_window, FRAME_CLOSED, FALSE, NULL);
		tt_release(mark);
		return 1;
	}
	
}


/* 
 * Handle the "save" op.
 */
int
edit_save(msg)
     Tt_message msg;
{
	int		mark = tt_mark();
	char		*new_file;

	if (! (int)xv_get(edit_ui_textpane, TEXTSW_MODIFIED)) {
		/* no save is needed */
		tt_release(mark);
		return 1;
	} 

	if (tt_message_opnum(msg) == SUN_EDITDEMO_SAVE) {
		if (textsw_save(edit_ui_textpane, 0, 0) == 0) {
			tt_message_reply(msg);
			tt_release(mark);
			return 1;
		}
	} else {
		/* handle SAVE_AS */
		new_file = tt_message_arg_val(msg, 0);
		if (textsw_store_file(edit_ui_textpane, new_file,0,0)==0) {
			tt_file_quit(tt_default_file());
			tt_default_file_set(new_file);
			tt_file_join(new_file);
			xv_set(edit_ui_textpane, TEXTSW_FILE,new_file,NULL);
			tt_release(mark);
			return 1;
		}
	}

	/* couldn't complete operation */
	tt_message_status_set(msg, TT_ERR_FILE);
	tt_message_status_string_set(msg, "Couldn't save file");
	tt_release(mark);
	return 0;
}


/* 
 * Handle the "close" op.
 */
int
edit_close(msg)
     Tt_message msg;
{
	if ((int)xv_get(edit_ui_textpane, TEXTSW_MODIFIED)) {
		tt_message_status_set(msg, TT_ERR_FILE);
		tt_message_status_string_set(msg, "File has been modified");
		return 0;
	} else {
		/* signal the notifier to exit after this operation is */
		/* completed. */
		notify_stop();

		return 1;
	}
}

/* 
 * Handle the "hilite_obj" op.
 */
int
edit_hilite_obj(msg)
     Tt_message msg;
{
	int	mark = tt_mark();
	char	*objid = tt_message_arg_val(msg, 0);
	char	obj_start_text[100];
	char	obj_end_text[100];

	if (tt_message_status(msg) == TT_WRN_START_MESSAGE
	    && edit_edit(msg) == 0) {
		/* we were started to hilite an object but couldn't load the */
		/* file into the textpane. */
		tt_release(mark);
		return 0;
	}

	/* expect objects to be wrapped by appropiately formatted */
	/* C-style comments. */

	sprintf(obj_start_text," /* begin_object(%s) */", objid);
	sprintf(obj_end_text,"	/* end_object(%s) */", objid);

	if (select_region(edit_ui_textpane,
			  obj_start_text,
			  obj_end_text) == 1) {
		tt_release(mark);
		return 1;
	} else {
		tt_message_status_set(msg, TT_ERR_OBJID);
		tt_message_status_string_set(msg,"Couldn't find object");

		tt_release(mark);
		return 0;
	}
}


/* 
 * Make a ToolTalk spec out of the selected text in this textpane. Once
 * the spec is succesfully created and written to a database, wrap the
 * text with C-style comments in order to delimit the object and send out
 * a notification that an object has been created in this file.
 */
Menu_item
edit_ui_make_object(item, event)
     Panel_item		item;
     Event		*event;
{
	int		mark = tt_mark();
	char		*objid;
	char		*file;
	char		*sel;
	Textsw_index	first, last;
	char		obj_start_text[100];
	char		obj_end_text[100];
	Tt_message	msg;

	if (! get_selection(edit_ui_xserver, edit_ui_textpane,
			    &sel, &first, &last)) {
		xv_set(edit_ui_base_window, FRAME_LEFT_FOOTER,
		       "First select some text", NULL);
		tt_release(mark);
		return item;
	}
	file = tt_default_file();

	if (file == (char *)0) {
		xv_set(edit_ui_base_window, FRAME_LEFT_FOOTER,
		       "Not editing any file", NULL);
		tt_release(mark);
		return item;
	}

	/* create a new spec */

	objid = tt_spec_create(tt_default_file());
	if (tt_pointer_error(objid) != TT_OK) {
		xv_set(edit_ui_base_window, FRAME_LEFT_FOOTER,
		       "Couldn't create object", NULL);
		tt_release(mark);
		return item;
	}


	/* set its otype */

	tt_spec_type_set(objid, "Sun_EditDemo_object");
	if (tt_spec_write(objid) != TT_OK) {
		xv_set(edit_ui_base_window, FRAME_LEFT_FOOTER,
		       "Couldn't write out object", NULL);
		tt_release(mark);
		return item;
	}

	/* wrap spec's contents (the selected text) with C-style */
	/* comments. */

	sprintf(obj_start_text," /* begin_object(%s) */", objid);
	sprintf(obj_end_text,"	/* end_object(%s) */", objid);
	(void)wrap_selection(edit_ui_xserver, edit_ui_textpane,
			     obj_start_text, obj_end_text);
	
	/* now send out a notification that we've added a new object */

	msg = tt_pnotice_create(TT_FILE_IN_SESSION,"Sun_EditDemo_new_object");
	tt_message_file_set(msg, file);
	tt_message_send(msg);

	tt_release(mark);
	return item;
}



/* 
 * Get the current selection. Returns 1 if the selection is in the passed
 * in textsw.
 */
int
get_selection(server, textsw, selection, first_ptr, last_ptr)
     Xv_server		server;
     Textsw		textsw;
     char		**selection;
     Textsw_index	*first_ptr;
     Textsw_index	*last_ptr;
{
	Textsw_index		first, last;
	Seln_holder		holder;
	Seln_request		*response;
	char			*ptr;

	holder = selection_inquire(server, SELN_PRIMARY);
	if (! seln_holder_same_client(&holder, (char *)textsw)) {
		return 0;
	}
	response = selection_ask(server, &holder,
				 SELN_REQ_FIRST,	      NULL,
				 SELN_REQ_LAST,		      NULL,
				 SELN_REQ_CONTENTS_ASCII,     NULL,
				 SELN_REQ_FAKE_LEVEL,	      SELN_LEVEL_LINE,
				 NULL);
	ptr = response->data;
	first = *(Textsw_index *)(ptr += sizeof(SELN_REQ_FIRST));
	ptr += sizeof(Textsw_index);
	last = *(Textsw_index *)(ptr += sizeof(SELN_REQ_LAST));
	ptr += sizeof(Textsw_index);
	ptr += sizeof(SELN_REQ_CONTENTS_ASCII);
	*selection = malloc(strlen(ptr) + 1);
	if (*selection == (char *)0) {
		return -1;
	}
	(void)strcpy(*selection, ptr);
	*first_ptr = first;
	*last_ptr = last;

	return 1;
}



/* 
 * Selects region between "begin" and "end" in textsw. Returns 1 if
 * successful. 
 */
int
select_region(textsw, begin, end)
     Textsw		textsw;
     char		*begin;
     char		*end;
{
	Textsw_index		bfirst, blast, efirst, elast;
	Textsw_index            inspoint;
	int			status;

	inspoint = (Textsw_index)xv_get(textsw, TEXTSW_INSERTION_POINT);
	/* Find the "begin" text */

	/* first search forward */
	bfirst = inspoint;
	status = textsw_find_bytes(textsw, &bfirst, &blast,
				   begin, strlen(begin),0);
	if (status == -1) {
	        bfirst = inspoint;
		/* search failed, search backwards */
		status = textsw_find_bytes(textsw, &bfirst, &blast,
					   begin, strlen(begin),1);
		if (status == -1) {
			return 0;
		}
	}

	/* Find the "end" text */

	efirst = inspoint;
	/* first search forward */
	status = textsw_find_bytes(textsw, &efirst, &elast,
				   end, strlen(end),0);
	if (status == -1) {
	        efirst = inspoint;
		/* search failed, search backwards */
		status =textsw_find_bytes(textsw, &efirst, &elast,
					  end, strlen(end),1);
		if (status == -1) {
			return 0;
		}
	}
	textsw_set_selection(textsw,
			     (inspoint = (blast < elast) ? blast : elast),
			     (efirst > bfirst) ? efirst : bfirst,
			     1);

	xv_set(textsw, TEXTSW_INSERTION_POINT, inspoint, NULL);
	textsw_possibly_normalize(textsw, inspoint);
	return 1;
}

/* 
 * Wraps the selected text in textsw with the begin and end strings
 * supplied. Returns 1 if successful.
 */
int
wrap_selection(server, textsw, begin, end)
     Xv_server		server;
     Textsw		textsw;
     char		*begin;
     char		*end;
{
	char			*buf;
	char			*sel;
	Textsw_index		sel_first, sel_last;
	int			sel_status;


	if (! (sel_status = get_selection(server, textsw,
					  &sel, &sel_first, &sel_last))) {
		return sel_status;
	}
		
	buf = malloc(strlen(sel) + strlen(begin) + strlen(end) + 3);
	if (buf == (char *)0) {
		return -1;
	}
	sprintf(buf,"%s\n%s\n%s", begin, sel, end);
	sel_status = (0 != textsw_replace_bytes(textsw,
						sel_first, sel_last + 1,
						buf, strlen(buf)));
	free(buf);
	free(sel);
	
	return sel_status;
}



/* 
 * Initialize our ui environment.
 */
edit_ui_initialize()
{
	static unsigned short	icon_bits[] = {
#include <images/document.icon>
	};
	static unsigned short	icon_mask_bits[] = {
#include <images/doc.mask.icon>
	};

	edit_ui_base_window = xv_create(NULL, FRAME,
					XV_WIDTH, 509,
					XV_HEIGHT, 462,
					XV_LABEL, "Sun_EditDemo_edit",
					FRAME_CLOSED, FALSE,
					FRAME_SHOW_FOOTER, TRUE,
					FRAME_SHOW_RESIZE_CORNER,
					TRUE,
					FRAME_ICON,
					xv_create(XV_NULL, ICON,
						  ICON_IMAGE,
						  xv_create(XV_NULL,
							    SERVER_IMAGE,
							    SERVER_IMAGE_BITS,
							    icon_bits,
							    SERVER_IMAGE_DEPTH,
							    1,
							    XV_WIDTH, 32,
							    XV_HEIGHT, 32,
							    NULL),
						  ICON_MASK_IMAGE,
						  xv_create(XV_NULL,
							    SERVER_IMAGE,
							    SERVER_IMAGE_BITS,
							    icon_mask_bits,
							    SERVER_IMAGE_DEPTH,
							    1,
							    XV_WIDTH, 64,
							    XV_HEIGHT, 64,
							    NULL),
						  NULL),
					NULL);

	edit_ui_xserver =(Xv_Server)xv_get(xv_get(edit_ui_base_window,
						  XV_SCREEN), SCREEN_SERVER);
	
	edit_ui_panel = xv_create(edit_ui_base_window, PANEL,
				  XV_X, 0,
				  XV_Y, 0,
				  XV_WIDTH, WIN_EXTEND_TO_EDGE,
				  XV_HEIGHT, 30,
				  NULL);

	edit_ui_obj_button = xv_create(edit_ui_panel, PANEL_BUTTON,
				       PANEL_LABEL_STRING, "Make object",
				       PANEL_NOTIFY_PROC,
				       edit_ui_make_object,
				       NULL);

	edit_ui_textpane =  xv_create(edit_ui_base_window, TEXTSW,
				      XV_X, 0,
				      XV_Y, 30,
				      XV_WIDTH, WIN_EXTEND_TO_EDGE,
				      XV_HEIGHT, 442,
				      OPENWIN_SHOW_BORDERS, TRUE,
				      NULL);
}
