/*
 *	@(#)preview.c 1.10 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 <math.h>
#include "buffer.h"
#include "jed_cps.h"
#include "preview_cps.h"
#include <assert.h>

static void setup_view_for_printing(JotView *view);

struct pageinfo {
    JotSpan *text;	    /* text in this page */
};

static Bytestring   page_info;	    /* array of struct pageinfo's */
static int	    page_count;
static int	    current_page = -1;
static JotView	    *page_view;
static JotView	    *alignment_view;
static boolean	    preview_visible = FALSE;

#define page_ref(n) ((struct pageinfo *)  \
		     &Bytestring_CharAt(&page_info, (n) * sizeof (struct pageinfo)));

static struct pageinfo *
get_page_n(int n)
{
    struct pageinfo new;

    assert(n <= page_count);
    if (n == page_count) {
	new.text = JotSpan_New(current_buffer->text, 0, 0);
	new.text->modified = TRUE;
	Bytestring_Insert(&page_info, Bytestring_Length(&page_info),
			  (char *) &new, sizeof (new));
	page_count += 1;
    }
    return page_ref(n);
}

static void
set_numeric_range(int n)
{
    char	buf[128];

    sprintf(buf, "1 %d /setrange PageNumeric send", n);
    cps_exec(buf);
}

static void
set_page_count(int n)
{
    assert(n <= page_count);
    if (n != page_count) {
	while (n != page_count) {
	    struct pageinfo	*p;

	    p = get_page_n(n);
	    JotSpan_Free(p->text);
	    Bytestring_Delete(&page_info, sizeof (struct pageinfo) * n,
			      sizeof (struct pageinfo));
	    page_count -= 1;
	}
	if (current_page >= page_count)
	    current_page = page_count - 1;
    }
}

static void
init_alignment_view()
{
    int	pos, limit, page;

    if (alignment_view == 0)
	alignment_view = JotView_New((JotText *) 0, FALSE);
    JotView_SetShape(alignment_view, (int) (8.5 * 72), 11 * 72);
    setup_view_for_printing(alignment_view);
}

static int
parse_margin(char *string)
{
    char    number[64], *src, *dest;
    int	    c;
    double  value, multiply;

    src = string;
    dest = number;
    while (isdigit((c = *src)) || c == '-' || c == '.') {
	*dest++ = c;
	src += 1;
    }
    *dest = '\0';

    while (!isalpha(*src) && *src != '\0')
	src += 1;
    if (*src == '\0')
	*(--src) = 'i';

    value = atof(number);
    multiply = (*src == 'i') ? 72.0 : (*src == 'p') ? 1 : 0;
    return (int) (value * multiply);
}

static int  LeftMargin = 36;
static int  RightMargin = 36;
static int  TopMargin = 36;
static int  BottomMargin = 36;

static char PrinterName[128];
static char FileName[256];
static int  Copies;

static int  print_tag;
static boolean	print_popup_created = FALSE;

void
print_document()
{
    if (!print_popup_created) {
	char	buf[128];

	sprintf(buf, "%d Jed_create_printer_popup", print_tag);
	cps_exec(buf);
	print_popup_created = TRUE;
    }
    cps_exec("/open print_popup send");
}	

static void
get_print_values()
{
    char    buf[512];

    if (!print_popup_created)
	return;
    cps_get_print_values(print_tag + 1);
    LeftMargin = parse_margin(wire_ReadString(buf));
    RightMargin = parse_margin(wire_ReadString(buf));
    TopMargin = parse_margin(wire_ReadString(buf));
    BottomMargin = parse_margin(wire_ReadString(buf));
    (void) wire_ReadString(PrinterName);
    (void) wire_ReadString(FileName);
    Copies = wire_ReadInt();
}

static void
printer_callback(int tag, caddr_t data)
{
    boolean print = wire_ReadInt() == 0;
    char    template[] = "/tmp/JedXXXXXX";
    char    filename[128];
    FILE    *fp;

    get_print_values();
    if (print) {
	strcpy(filename, template);
	mktemp(filename);
    } else
	strcpy(filename, FileName);
    if ((fp = fopen(filename, "w")) == NULL)
	signal_warning("Cannot create %s for printing output!");
    init_alignment_view();
    JotView_Print(alignment_view, fp);
    fclose(fp);

    if (print) {
	char	cmd[128];

	strcpy(cmd, "lpr");
	if (PrinterName[0] != '\0')
	    sprintf(&cmd[strlen(cmd)], " -P %s", PrinterName);
	if (Copies > 1)
	    sprintf(&cmd[strlen(cmd)], " -#%d", Copies);
	sprintf(&cmd[strlen(cmd)], " %s", filename);
	system(cmd);
	unlink(filename);
    }
}

static void
setup_view_for_printing(JotView *view)
{
    JotRuler		*view_ruler;

    JotView_SetMargins(view, LeftMargin, RightMargin, TopMargin, BottomMargin);
    JotView_SetPrinterMatchFonts(view, TRUE);
    JotView_SetText(view, current_buffer->text);
}

static int
View_LastPosition(JotView *view)
{
    return JotView_PositionFromLine(view, 0) +
		JotView_Characters(view);
}    

static void
format_document()
{
    JotText *text;
    int	    pos, limit, page, previous_page_count;

    previous_page_count = page_count;
    pos = 0;
    text = current_buffer->text;
    limit = JotText_Characters(text);
    page = 0;
    while (pos <= limit) {
	JotSpan	*page_span;
	int	lastpos;

	page_span = get_page_n(page)->text;
	if (pos != JotSpan_Position(page_span) ||
	    page_span->modified) {
	    JotSpan_SetText(page_span, text, pos, 0);
	    JotView_ScrollAbsolute(alignment_view, pos, Jot_TOP);
	    JotView_Update(alignment_view);
	    page_span->modified = 0;
	    lastpos = View_LastPosition(alignment_view);
	} else
	    lastpos = pos + JotSpan_Length(page_span);
	JotSpan_SetLength(page_span, lastpos - pos);
	pos = lastpos + 1;
	page += 1;
    }
    JotView_Unmodify(alignment_view);
    if (previous_page_count != page)
	set_numeric_range(page);
    set_page_count(page);
}

static void
preview_footer()
{
    char	    buf[256];
    static short    displayed_page = -1, displayed_page_count = -1;

    if (displayed_page != current_page ||
	displayed_page_count != page_count) {
	sprintf(buf, "() (Page %d of %d) /setfooter pp_popup send\
 %d /setvalue PageNumeric send",
		current_page + 1, page_count, current_page + 1);
	cps_exec(buf);
	displayed_page = current_page;
	displayed_page_count = page_count;
    }
}

static void
goto_page(int n)
{
    JotSpan *sp;
    int	    new_top;

    if (n < 0 || n >= page_count) {
	ring_bell();
	return;
    }
    current_page = n;
    preview_footer();
    sp = get_page_n(n)->text;
    new_top = JotSpan_Position(sp);
    if (new_top != JotSpan_Position(page_view->top)) {
	JotSpan_SetPosition(page_view->top, JotSpan_Position(sp));
	JotView_Modify(page_view);
    }
}

static void
pp_kbd_event(JotView *v, int c)
{
    if (c == ' ')
	goto_page(current_page + 1);
    else if (c == '\b')
	goto_page(current_page - 1);
}

static void
pp_mouse_event(JotView *v, int button, int action, int pos)
{
    Buffer_SetCaret(current_buffer, pos);
}

static int
find_page(int pos)
{
    JotSpan *sp;
    int	    i;

    format_document();
    for (i = 0; i < page_count; i++) {
	sp = get_page_n(i)->text;
	if (pos >= JotSpan_Position(sp) &&
	    pos < JotSpan_Position(sp) + JotSpan_Length(sp))
	    return i;
    }
    return 0;
}

void
update_page_preview()
{
    int	top_pos, i;

    if (!preview_visible)
	return;

    format_document();
    goto_page(current_page);
    preview_footer();
}

static void
openedness(int tag, caddr_t foo)
{
    preview_visible = (wire_ReadInt() == 1);
    if (!preview_visible)
	JotView_SetText(page_view, (JotText *) 0);
    else {
	get_print_values();
	setup_view_for_printing(page_view);
	setup_view_for_printing(alignment_view);
	JotView_SetEventHandlers(page_view, Jot_KEYBOARD_EVENT, pp_kbd_event,
				 Jot_MOUSE_EVENT, pp_mouse_event,
				 Jot_NULL_EVENT);
	if (current_page == -1)
	    current_page = find_page(JotText_Caret(JotView_Text(page_view)));
    }
}	

static void
page_numeric()
{
    goto_page(wire_ReadInt() - 1);
}

static void
preview_pages()
{
    if (page_view == 0) {
	int tag;

	tag = wire_AllocateTags(2);
	wire_RegisterTag(tag, openedness, (caddr_t) 0);
	wire_RegisterTag(tag + 1, page_numeric, (caddr_t) 0);
	cps_preview_init(tag, tag + 1);
	page_view = JotView_New((JotText *) 0, TRUE);
	cps_init_pp_popup(JotView_Canvas(page_view));
	current_page = 0;
	page_count = 0;
	init_alignment_view();
    }
    if (!preview_visible)
	cps_exec("/pin pp_popup send /open pp_popup send");
}

void
preview_init()
{
    print_tag = wire_AllocateTags(2);
    wire_RegisterTag(print_tag, printer_callback, NULL);
    define_cmd("print", print_document, "^X^P", (char *) 0);
    define_cmd("preview-pages", preview_pages, (char *) 0);
}
