/*
 *	@(#)jed.c 1.39 91/09/14 Copyright 1990-91 Sun Microsystems
 *
 * This file is a product of Sun Microsystems, Inc. and is provided for
 * unrestricted use provided that this legend is included on all tape
 * media and as a part of the software program in whole or part.  Users
 * may copy or modify this file without charge, but are not authorized to
 * license or distribute it to anyone else except as part of a product
 * or program developed by the user.
 * 
 * THIS FILE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
 * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
 * 
 * This file is provided with no support and without any obligation on the
 * part of Sun Microsystems, Inc. to assist in its use, correction,
 * modification or enhancement.
 * 
 * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
 * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS FILE
 * OR ANY PART THEREOF.
 * 
 * In no event will Sun Microsystems, Inc. be liable for any lost revenue
 * or profits or other special, indirect and consequential damages, even
 * if Sun has been advised of the possibility of such damages.
 * 
 * Sun Microsystems, Inc.
 * 2550 Garcia Avenue
 * Mountain View, California  94043
 */

#include <string.h>
#include <signal.h>
#include <setjmp.h>
#include <stdarg.h>
#include <sys/time.h>
#include <wire/wire.h>
#include "buffer.h"
#include "keymap.h"
#include "jed_cps.h"

int	Frame_Id;
JotView	*The_View;
Buffer	*current_buffer;

static char	*force_package_reload = NULL;
static char	*default_file = 0;
int		repeat_rate = 20;

#define NEW_MESG    1
#define OLD_MESG    2
#define NO_MESG	    3

#ifdef SVR4
#   define getwd(b)	getcwd(b, sizeof(b))
#endif

static boolean	message_status = NO_MESG;

jmp_buf	mainloop;

#include "jed.6.h"

char *DEFAULT_FONT = "font";
char *DEFAULT_FONT_SIZE = "font-size";
char *SAVE_ATTRIBUTES = "save-attributes?";

void
checkpoint_then_quit(int sig)
{
    Buffer_Checkpoint(current_buffer);
    if (sig != 0)
	abort();
    exit(1);
}

void
frame_Message(char *fmt, ...)
{
    char    buffer[256];
    va_list ap;

    va_start(ap, fmt);
    sprintf(buffer, fmt, va_arg(ap, int), va_arg(ap, int), va_arg(ap, int));
    va_end(ap);
    ps_frame_footer(Frame_Id, buffer, "");
    message_status = NEW_MESG;
}

char *
basename(char *name)
{
    char    *cp;

    if (name == 0)
	return "No File";
    if (cp = strrchr(name, '/'))
	name = cp + 1;
    return name;
}

frame_Modeline()
{
    JotText *text;
    Buffer  *b;
    char    buffer[256];

    b = current_buffer;
    text = b->text;
    sprintf(buffer, "JED%s - %s, %s dir; %s",
	    kbd_macro_define ? " (Macro Define)" : "",
	    b->filename == 0 ? "(NONE)" : b->filename,
	    b->last_saved != JotText_Modified(text) ? "(Edited)" : "",
	    b->directory);
    ps_frame_label(Frame_Id, buffer);
    ps_icon_label(Frame_Id, basename(b->filename));
    b->update_modeline = 0;
}

static void
dispatch_key(JotView *v, int key, int shift_state)
{
    if (shift_state & Jot_META)
	keymap_Dispatch('\033', 0);
    keymap_Dispatch(key, shift_state);
    if (message_status == NEW_MESG)
	message_status = OLD_MESG;
    else if (message_status == OLD_MESG) {
	frame_Message("");
	message_status = NO_MESG;
    }
}

static int  V3 = FALSE;

initialize_server()
{
    ps_init_tnt(&V3);
}

static void
initialize_jed_package()
{
    int	    loaded;
    char    *force = force_package_reload ? "true" : "false";

    ps_check_package_status(&loaded);
    if (!loaded || force_package_reload) {
	if (V3)
	    load_jed_package(force);
	else
	    load_jed_package_for_v2(force);
    }
    begin_jed_package();
}

static boolean	in_repeating_scroll = FALSE;
static int	scroll_direction, scroll_start_tag = -1;

static void
scroll_repeat_start(int tag, caddr_t data)
{
    if (tag == scroll_start_tag) {
	in_repeating_scroll = TRUE;
	scroll_direction = wire_ReadInt();
    } else
	in_repeating_scroll = FALSE;
}

static void
scroll_view()
{
    JotView_ScrollRelative(The_View, Jot_LINES, scroll_direction);
    The_View->sbarwarp = TRUE;
    cps_catchup(scroll_start_tag + 2);
}

static void
init_scrolling()
{
    scroll_start_tag = wire_AllocateTags(3);
    wire_RegisterTag(scroll_start_tag, scroll_repeat_start, 0);
    wire_RegisterTag(scroll_start_tag + 1, scroll_repeat_start, 0);
}

int
parse_font(int argc, char *argv[], char *values)
{
    set_variable(object_find(DEFAULT_FONT), argv[1]);
    return 1;
}

int
parse_file(int argc, char *argv[], char *values)
{
    default_file = argv[0];
    return 1;
}

int
parse_size(int argc, char *argv[], char *values)
{
    set_variable(object_find(DEFAULT_FONT_SIZE), argv[1]);
    return 0;
}

char	initial_working_directory[256];

main(int argc, char *argv[])
{
    wire_Wire	    wire;
    JotText	    *text;
    boolean	    last_modified = FALSE;
    Buffer	    *buffer;
    JotFont	    *ff;
    JotRuler	    *ruler;
    struct timeval  scrolling_tv;

    define_variable(DEFAULT_FONT, string, copystr("LucidaSans-Typewriter"));
    define_variable(DEFAULT_FONT_SIZE, number, 12);

    wire_AddOption("-Wt", NULL, parse_font, NULL);
    wire_AddOption("-fn", NULL, parse_font, NULL);
    wire_AddOption("-font", NULL, parse_font,
		   "-font font - specify font to use");
    wire_AddOption("-s %d", NULL, parse_size,
		   "-s size - specify font size");
    wire_AddOption("-p", (caddr_t) &force_package_reload, ((int (*)()) 0),
		   "-p - force reload of jed package");
    wire_AddOption("ARGUMENT", NULL, parse_file, NULL);

    if ((wire = wire_Open(wire_Display())) == wire_INVALID_WIRE) {
	wire_Perror("jed:");
	exit(1);
    }

    initialize_server();
    initialize_jed_package();
    Jot_Initialize(wire);
    The_View = JotView_New((JotText *) 0, TRUE);

    keymap_init();
    style_init();
    menu_cmds_init();
    Buffer_init();
    cmds_init();
    preview_init();

    parse_rc_file((char *) 0);
    if (!wire_ParseArguments(argc, argv))
	exit(1);
    extras_menu_init();
    init_scrolling();
    wire_ExecuteArguments();

    /* now create a text and The_View object, and assign a buffer
       to the new view */
    JotView_SetEventHandlers(The_View,
			     Jot_SHIFTED_KEYBOARD_EVENT, dispatch_key,
			     Jot_NULL_EVENT);
    buffer = Buffer_New();
    Buffer_SetBuffer(buffer);
    Buffer_SetDirectory(buffer, (char *) getwd(initial_working_directory));

    ff = JotFont_New(get_string_var(DEFAULT_FONT));
    if (ff == NULL) {
	fprintf(stderr, "%s: Cannot find font %s\n", argv[0],
		get_string_var(DEFAULT_FONT));
	exit(1);
    }
    ruler = JotRuler_New();
    JotRuler_SetParameters(ruler,
			   Jot_FONT, ff,
			   Jot_FONT_SIZE, get_number_var(DEFAULT_FONT_SIZE),
			   Jot_LINE_STYLE, Jot_LEFT_ALIGN,
			   Jot_NULL_PARAMETER);
    JotText_SetDefaultRuler(JotView_Text(The_View), ruler);

    Buffer_EnableUndo(buffer);
    ps_set_preferred_size(JotView_Canvas(The_View), 575, 600);
    Frame_Id = wire_AllocateTokens(wire, 1);
    ps_initcanvas(JotView_Canvas(The_View), Frame_Id, scroll_start_tag);
    ps_place_frame(Frame_Id);
    ps_map_frame(Frame_Id);
    droptgt_init(Frame_Id);

    text = buffer->text;

    if (setjmp(mainloop) == 0) {
	signal(SIGHUP, checkpoint_then_quit);
	signal(SIGSEGV, checkpoint_then_quit);
	signal(SIGINT, checkpoint_then_quit);
	if (default_file != 0)
	    Buffer_LoadFile(buffer, default_file);
	else {
	    JotText_ReadRtfFromString(buffer->text, 0, helptext);
	    Buffer_UnModified(buffer);
	}
    } else
	macro_unwind();

    /* "Off on your way
	hit the open road
	there is magic at your fingers
	For the spirit ever lingers
	undemanding contact
	in your happy solitude"

	(Rush - The Spirit of Radio) */

    scrolling_tv.tv_sec = 0;
    scrolling_tv.tv_usec = repeat_rate * 1000;
    for (;;) {
	struct timeval	*tp;

	if (in_repeating_scroll)
	    tp = &scrolling_tv;
	else
	    tp = NULL;
	if (!wire_Notify(tp)) {
	    if (wire_Errno == wire_EINTR)
		continue;
	    if (wire_Errno == wire_ETIMEOUT)
		scroll_view();
	    else
		break;
	}
	if (wire_WouldNotify(wire))
	    continue;
	if (JotView_PendingUpdates()) {
	    update_page_preview();
	    JotView_UpdateViews();
	}
	if ((buffer->update_modeline) ||
	    ((buffer->last_saved != JotText_Modified(text)) != last_modified)) {
	    last_modified = (buffer->last_saved != JotText_Modified(text));
	    frame_Modeline();
	}
    }
    /* NOTREACHED */
    checkpoint_then_quit(0);	/* connection to server died? */
}
