/*
   Copyright (C) 1999, 2000 Marek Michalkiewicz <marekm@linux.org.pl>

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 U.S.A.

   This program may also be distributed as part of Aladdin Ghostscript,
   under the terms of the Aladdin Free Public License (the "License").

   Every copy of Aladdin Ghostscript must include a copy of the
   License, normally in a plain ASCII text file named PUBLIC.  The
   License grants you the right to copy, modify and redistribute
   Aladdin Ghostscript, but only under certain conditions described in
   the License.  Among other things, the License requires that the
   copyright notice and this notice be preserved on all copies.
 */
/*$Id: gdevhl12.c,v 1.2.2.1 2001/06/05 07:07:37 raph Exp $ */
/* gdevhl12.c - Brother HL-1250 driver for Ghostscript */

/*
   This driver handles the 1200x600 dpi mode, and some settings like
   paper source and toner save mode.  600x600 dpi and below is handled
   by gdevdjet.c (called from here with minor initialization changes).

   Additional settings (gs command line options) for this driver:

   -dEconoMode=0..3 - toner save mode (0=disabled, 1=50%, 2=25%, 3=?)
   (note the wrong order 0=off, 3, 2, 1=highest - but
   it is the same as in the PJL ECONOLEVEL=... command)
   -dSourceTray=0..5 - paper source
   (0=auto, 1=dual, 2=upper, 3=lower, 4=manual)

   (More settings could easily be added if necessary.)

   The 1200x600 dpi mode may require a lot of printer memory - the manual
   recommends at least 10MB; for me it seems to work well with 8MB: 4MB
   standard + 4MB "finally found some good use for that old PS/2 SIMM" :-).
   Even at just 600x600 dpi (normal PCL 5 control codes) print quality is
   very good, at 1200x600 dpi it is very difficult to see the difference.

   The printer also supports PCL 6 (PCL XL) but
   - I don't have the documentation for that
   - the pxlmono driver works but the output looks a bit different
   from that generated by the ljet4 or (this) 1200x600 dpi driver
   (lines appear very thin).
   so let's use the good old ljet4 (PCL 5) driver for now.
   (PCL 6 seems to offer better compression though.)

   Many thanks to Richard Thomas <richardt@brother.co.uk> for help
   (sending me the printer, documentation, answering my questions).
 */

#include "gdevprn.h"
#include "gdevdljm.h"

#ifndef X_DPI
#  define X_DPI 1200
#endif
#ifndef Y_DPI
#  define Y_DPI 600
#endif

typedef enum {
    TRAY_AUTO = 0,
    TRAY_DUAL,
    TRAY_UPPER,
    TRAY_LOWER,
    TRAY_MANUAL
} hl1250_tray_t;

typedef struct gx_device_hl1250_s {
    gx_device_common;
    gx_prn_device_common;
    int source_tray;
    int econo_mode;
} gx_device_hl1250;

private dev_proc_open_device(hl1250_open);
private dev_proc_close_device(hl1250_close);
private dev_proc_print_page(hl1250_print_page);
private dev_proc_get_params(hl1250_get_params);
private dev_proc_put_params(hl1250_put_params);

private const gx_device_procs prn_hl1250_procs =
prn_params_procs(hl1250_open, gdev_prn_output_page, hl1250_close,
		 hl1250_get_params, hl1250_put_params);

const gx_device_hl1250 gs_hl1250_device =
{
    prn_device_std_body(gx_device_hl1250, prn_hl1250_procs,
			"hl1250",
			DEFAULT_WIDTH_10THS, DEFAULT_HEIGHT_10THS,
			X_DPI, Y_DPI,
			0, 0, 0, 0,	/* margins */
			1, hl1250_print_page),
    TRAY_AUTO,			/* default source tray */
    0				/* default toner save mode */
};

/* defines for Brother HL-1250 (possibly other models too) 1200x600dpi mode */

/* max number of 16-bit words in one 1200dpi scan line */
#define SCAN_WORDS 640

/* number of scan lines per band */
#define BAND_SCANS 64

/* max number of 16-bit words in one 64-line band after compression,
   limited by 16-bit length field - 7 bytes header + 0xFFF8 bytes data -
   note that we may have to lose some data if it can't compress well
   (maximum possible uncompressed data length is about 80K).  */
#define MAX_BAND_WORDS 0x7FFC

/* codes (16-bit words) to send in the 1200x600dpi data block: */

/* vertical compression (copy COUNT words from the previous line) */
#define HL_VERT(count) (0xE000 | (count))

/* 16-bit horizontal compression (repeat the next word COUNT times) */
#define HL_HOR16(count) (0x8000 | (count))

/* 8-bit horiz. compression (repeat DATA byte COUNT*2 times, COUNT < 32) */
#define HL_HOR8(count, data) (0xC000 | ((count) << 8) | ((data) & 0xFF))

/* 4-bit horiz. compression (repeat DATA nibble COUNT*4 times, COUNT < 512) */
#define HL_HOR4(count, data) (0xA000 | (count) | (((data) & 0x0F) << 9))

/* no compression, COUNT words of data follow */
#define HL_COPY(count) ((count) << 4)

typedef unsigned short u16;

/* The printer expects 16-bit data words in big endian order.  */
#if arch_is_big_endian
#define cpu_to_be16(x) (x)
#else
private u16
cpu_to_be16(u16 x)
{
    return (x >> 8) | (x << 8);
}
#endif

typedef struct hl1250_state_s {
    /* area of band that contains any black dots */
    /* x = xl..xr-1, y = yt..yb-1, width=xr-xl, height=yb-yt */
    unsigned int xl, xr, yt, yb;

    /* number of words in the output buffer */
    unsigned int out_count;

    /* output buffer for compressed data */
    u16 out_buf[MAX_BAND_WORDS];

    /* input buffer for one 64-line band */
    u16 in_buf[BAND_SCANS][SCAN_WORDS];
} hl1250_state_t;

/*
   find the smallest rectangle that contains all black dots of the
   band (in other words, the outside of that rectangle is all white)
   returns 0 if the band is completely white, else 1
 */
private int
hl1250_check_area(hl1250_state_t * s)
{
    unsigned int x, y, xleft, xright, ytop, ybottom;
    int line_not_white, band_not_white;

    band_not_white = 0;
    xright = s->xl;
    xleft = s->xr;
    ybottom = s->yt;
    ytop = s->yb;
    for (y = s->yt; y < s->yb; y++) {
	line_not_white = 0;
	for (x = s->xl; x < s->xr; x++) {
	    if (s->in_buf[y][x]) {
		if (xleft > x)
		    xleft = x;
		if (xright <= x)
		    xright = x + 1;
		line_not_white = 1;
	    }
	}
	if (line_not_white) {
	    if (ytop > y)
		ytop = y;
	    if (ybottom <= y)
		ybottom = y + 1;
	    band_not_white = 1;
	}
    }
    if (band_not_white) {
	s->xl = xleft;
	s->xr = xright;
	s->yt = ytop;
	s->yb = ybottom;
    } else {
	s->xr = s->xl;
	s->yb = s->yt;
    }
    return band_not_white;
}

/*
   Compressed data of this band is larger than MAX_BAND_WORDS,
   so just send every second line and repeat it using vertical
   compression, effectively reducing resolution to 1200x300 dpi.
   XXX - probably would be better to try to reduce to 600x600
   instead; should check what the windows driver does.
   Shouldn't happen too often so it doesn't matter too much...
 */
private void
hl1250_lose_resolution(hl1250_state_t * s)
{
    unsigned int y, width;
    u16 *out;

    out = s->out_buf;
    width = s->xr - s->xl;
    for (y = s->yt; y < s->yb; y += 2) {
	*out++ = cpu_to_be16(HL_COPY(width));
	memcpy(out, &s->in_buf[y][s->xl], width * sizeof(u16));
	out += width;
	*out++ = cpu_to_be16(HL_VERT(width));
    }
    s->out_count = out - s->out_buf;
}

/*
   Try to compress a single scan line.
   Return 1 on success, 0 on failure (data doesn't compress
   well enough to fit in MAX_BAND_WORDS words, truncated).
 */
private int
hl1250_compress_line(hl1250_state_t * s, unsigned int y)
{
    unsigned int total_len;	/* total data words after compression */
    unsigned int copy_len;	/* number of words to copy uncompressed */
    unsigned int hlen, vlen;	/* length for hor. and vert. compression */
    unsigned int clen, ulen;	/* compressed and uncompressed words */
    u16 hl_code;		/* code to send */
    int x, i;
    u16 *out;
    unsigned int width = s->xr - s->xl;
    const u16 *line = &s->in_buf[y][s->xl];
    const u16 *prev = (y > s->yt ? &s->in_buf[y - 1][s->xl] : NULL);

    out = &s->out_buf[s->out_count];
    x = 0;
    copy_len = 0;
    total_len = s->out_count;
    while (x < width) {
	/* how many words (hlen >= 1) to repeat */
	for (i = x + 1; i < width; i++) {
	    if (line[i] != line[x])
		break;
	}
	hlen = i - x;
	/* if not the first line, try vertical compression */
	vlen = 0;
	if (prev) {
	    for (i = x; i < width; i++) {
		if (line[i] != prev[i])
		    break;
	    }
	    vlen = i - x;
	}
	/* find the best method to encode the data */
	ulen = hlen;
	clen = 1;
	if (vlen >= hlen) {
	    /* vertical compression */
	    ulen = vlen;
	    hl_code = HL_VERT(vlen);
	} else if ((line[x] ^ (line[x] >> 8)) & 0xFF) {
	    /* 16-bit horizontal compression */
	    hl_code = HL_HOR16(hlen);
	    clen = 2;
	} else if ((line[x] ^ (line[x] >> 4)) & 0x0F) {
	    /* 8-bit horizontal compression (if possible) */
	    if (hlen < 32) {
		hl_code = HL_HOR8(hlen, line[x]);
	    } else {
		hl_code = HL_HOR16(hlen);
		clen = 2;
	    }
	} else {
	    /* 4-bit horizontal compression (if possible) */
	    if (hlen < 512) {
		hl_code = HL_HOR4(hlen, line[x]);
	    } else {
		hl_code = HL_HOR16(hlen);
		clen = 2;
	    }
	}
	/*
	   now see if we should copy the word without compression
	   (the cost of leaving/re-entering copy mode is one word).
	 */
	if (ulen < clen + (copy_len > 0)) {
	    /* yes, copy */
	    copy_len += ulen;
	} else {
	    if (copy_len) {
		/* first, copy data (if any) */
		total_len += copy_len + 1;
		if (total_len > MAX_BAND_WORDS)
		    goto error_out;
		*out++ = cpu_to_be16(HL_COPY(copy_len));
		memcpy(out, &line[x - copy_len], copy_len * sizeof(u16));
		out += copy_len;
		copy_len = 0;
	    }
	    /* now send the current code */
	    total_len += clen;
	    if (total_len > MAX_BAND_WORDS)
		goto error_out;
	    *out++ = cpu_to_be16(hl_code);
	    if (clen == 2) {
		/* 16-bit compression */
		*out++ = line[x];
	    }
	}
	/* move to the next word to process */
	x += ulen;
    }
    /* copy anything left at the end */
    if (copy_len) {
	total_len += copy_len + 1;
	if (total_len > MAX_BAND_WORDS)
	    goto error_out;
	*out++ = cpu_to_be16(HL_COPY(copy_len));
	memcpy(out, &line[width - copy_len], copy_len * sizeof(u16));
	out += copy_len;
    }
    s->out_count = out - s->out_buf;
  error_out:
    return (total_len <= MAX_BAND_WORDS);
}

/*
   send a 16-bit big endian value
 */
private void
put_be16(FILE * fp, u16 data)
{
    putc(data >> 8, fp);
    putc(data & 0xFF, fp);
}

/*
   prn_stream = data sent to the printer
   s->xl,xr,yt,yb,in_buf = band (max 64 lines), coordinates band-relative
   band = Y coordinate of the band from top of page
 */
private void
hl1250_compress_band(FILE * prn_stream, hl1250_state_t * s, unsigned int band)
{
    unsigned int y, ytop, ybottom;

    s->out_count = 0;

    if (!hl1250_check_area(s))
	return;

    /*
       It seems HL-1250 1200x600 dpi mode has an undocumented feature -
       it rounds the X left coordinate of the image up to next 32 dots.
       Probably the RISC inside likes 32-bit alignment.  No big problem,
       we just have to round it down (it's in 16-bit words here).
     */
    s->xl &= ~1;

    ytop = s->yt;
    ybottom = s->yb;
    for (y = ytop; y < ybottom; y++) {
	if (hl1250_compress_line(s, y))
	    continue;
#if 1
	/* XXX - please report if you ever see this, then change to #if 0 */
	fprintf(stderr,
		"hl1250: compression failed (y=%u), doing 1200x300 dpi\n",
		band + y);
#endif
	hl1250_lose_resolution(s);
	break;
    }
    if (s->out_count) {
	fprintf(prn_stream, "\033*b%uW", s->out_count * sizeof(u16) + 9);
	put_be16(prn_stream, s->out_count * sizeof(u16) + 7);
	put_be16(prn_stream, s->xl * 16);
	put_be16(prn_stream, band + ytop);
	putc(ybottom - ytop, prn_stream);
	put_be16(prn_stream, s->xr - s->xl);
	fwrite(s->out_buf, sizeof(u16), s->out_count, prn_stream);
    }
}


private int
hl1250_print_1200dpi(gx_device_printer * pdev, FILE * prn_stream,
		     const char *page_init)
{
    int band, lnum;
    int code = 0;
    hl1250_state_t *s;
    int line_size = gdev_prn_raster(pdev);
    int num_rows = dev_print_scan_lines(pdev);
    int paper_size = gdev_pcl_paper_size((gx_device *) pdev);

    s = (hl1250_state_t *) gs_alloc_byte_array(pdev->memory, 1, sizeof(*s),
					       "hl1250_print_1200dpi");
    if (!s)
	return_error(gs_error_VMerror);

    memset(s, 0, sizeof(*s));

    if (line_size > sizeof(s->in_buf[0]))
	line_size = sizeof(s->in_buf[0]);

    if (pdev->PageCount == 0) {
	fputs("\033E", prn_stream);
	fprintf(prn_stream, "\033&l%dA", paper_size);
	fputs(page_init, prn_stream);
	fputs("\033&l1X", prn_stream);
    }
    fputs("\033&u1200D", prn_stream);
    fputs("\033&l0o0l0E", prn_stream);
    fputs("\033*rB\033*p0x0Y", prn_stream);
    fputs("\033*t600R", prn_stream);

    fputs("\033*r1A", prn_stream);
    fputs("\033*b1027M", prn_stream);

    for (band = 0; band < num_rows; band += BAND_SCANS) {
	int next_band = band + BAND_SCANS;

	if (next_band > num_rows)
	    next_band = num_rows;
	for (lnum = band; lnum < next_band; lnum++) {
	    code = gdev_prn_copy_scan_lines(pdev, lnum,
			      (byte *) (s->in_buf[lnum - band]), line_size);
	    if (code < 0)
		goto error_out;
	}
	s->yt = 0;
	s->yb = next_band - band;
	s->xl = 0;
	s->xr = 635;		/* max width */
	hl1250_compress_band(prn_stream, s, band);
    }
  error_out:
    fputs("\033*rB\f", prn_stream);
    gs_free_object(pdev->memory, s, "hl1250_print_page");
    return code;
}


private int
hl1250_open(gx_device * pdev)
{
    /* margins: left, bottom, right, top */
    /* XXX - only A4 tested, letter size margins likely need to be tweaked */
    static const float margins_a4_600[4] = {0.05, 0.15, 0.25, 0.15};
    static const float margins_a4_1200[4] = {0.05, 0.2, 0.1, 0.15};
    static const float margins_letter_600[4] = {0.05, 0.15, 0.25, 0.15};
    static const float margins_letter_1200[4] = {0.05, 0.2, 0.1, 0.15};

    int x_dpi = (int)((gx_device_printer *) pdev)->x_pixels_per_inch;
    int paper_size = gdev_pcl_paper_size(pdev);

    if (x_dpi == 1200) {
	if (paper_size == PAPER_SIZE_A4)
	    gx_device_set_margins(pdev, margins_a4_1200, true);
	else
	    gx_device_set_margins(pdev, margins_letter_1200, true);
    } else {
	if (paper_size == PAPER_SIZE_A4)
	    gx_device_set_margins(pdev, margins_a4_600, false);
	else
	    gx_device_set_margins(pdev, margins_letter_600, false);
    }
    return gdev_prn_open(pdev);
}

private int
hl1250_close(gx_device * pdev)
{
    int code = gdev_prn_open_printer(pdev, 1);

    if (code < 0)
	return code;
    /* job separation, reset, UEL */
    fputs("\033&l1T\033E\033%-12345X", ((gx_device_printer *) pdev)->file);
    return gdev_prn_close(pdev);
}

private int
hl1250_print_page(gx_device_printer * pdev, FILE * prn_stream)
{
    int x_dpi = (int)pdev->x_pixels_per_inch;
    int y_dpi = (int)pdev->y_pixels_per_inch;
    const char *tray_pjl;
    const char *tray_pcl;
    const gx_device_hl1250 *hl1250 = (gx_device_hl1250 *) pdev;
    hl1250_tray_t source_tray = hl1250->source_tray;
    int econo_mode = hl1250->econo_mode;

    tray_pjl = "AUTO";
    tray_pcl = "";
    switch (source_tray) {
	case TRAY_DUAL:
	    tray_pcl = "\033&l0H";
	    break;
	case TRAY_UPPER:
	    tray_pjl = "TRAY1";
	    tray_pcl = "\033&l1H";
	    break;
	case TRAY_LOWER:
	    tray_pjl = "TRAY2";
	    tray_pcl = "\033&l5H";
	    break;
	case TRAY_MANUAL:
	    tray_pcl = "\033&l2H";
	    break;
	default:
    }
    if (pdev->PageCount == 0) {
	/* initialize printer */
	fputs("\033%-12345X@PJL \r\n", prn_stream);
	fprintf(prn_stream, "@PJL SET SOURCETRAY=%s\n", tray_pjl);
	fprintf(prn_stream, "@PJL SET RAS1200MODE=%s\n",
		(x_dpi == 1200 ? "ON" : "OFF"));
	fprintf(prn_stream, "@PJL SET ECONOMODE=%s\n",
		(econo_mode ? "ON" : "OFF"));
	if (econo_mode)
	    fprintf(prn_stream, "@PJL SET ECONOLEVEL=%d\n", econo_mode);
	/* other PJL settings can be added here later */
	fputs("@PJL ENTER LANGUAGE=PCL\n", prn_stream);
    }
    if (x_dpi != 1200) {
	char page_init[100];

	/* We get the printer to translate the coordinate system for us.
	   It seems the HL-1250 needs a slightly different translation
	   (-120, 0) compared to the one in the ljet4 driver (-180, 36)
	   (X, Y coordinates here are specified in 1/720-inch units).  */

	sprintf(page_init, "\033&l-120U\033*r0F\033&u%dD%s", y_dpi, tray_pcl);
	return dljet_mono_print_page(pdev, prn_stream, y_dpi,
				     PCL_LJ4_FEATURES, page_init);
    }
    return hl1250_print_1200dpi(pdev, prn_stream, tray_pcl);
}

private int
hl1250_put_param_int(gs_param_list * plist, gs_param_name pname,
		     int *pvalue, int minval, int maxval, int ecode)
{
    int code, value;

    code = param_read_int(plist, pname, &value);
    switch (code) {
	case 0:
	    if (value < minval || value > maxval)
		param_signal_error(plist, pname, gs_error_rangecheck);
	    *pvalue = value;
	    return (ecode < 0 ? ecode : 1);
	case 1:
	    return ecode;
	default:
	    return code;
    }
}

private int
hl1250_get_params(gx_device * pdev, gs_param_list * plist)
{
    gx_device_hl1250 *hl1250 = (gx_device_hl1250 *) pdev;
    int code = gdev_prn_get_params(pdev, plist);

    if (code < 0)
	return code;
    code = param_write_int(plist, "SourceTray", &hl1250->source_tray);
    if (code < 0)
	return code;
    code = param_write_int(plist, "EconoMode", &hl1250->econo_mode);
    return code;
}

private int
hl1250_put_params(gx_device * pdev, gs_param_list * plist)
{
    int code = 0;
    gx_device_hl1250 *hl1250 = (gx_device_hl1250 *) pdev;
    int source_tray = hl1250->source_tray;
    int econo_mode = hl1250->econo_mode;

    code = hl1250_put_param_int(plist, "SourceTray", &source_tray,
				TRAY_AUTO, TRAY_MANUAL, code);
    code = hl1250_put_param_int(plist, "EconoMode", &econo_mode, 0, 3, code);
    if (code < 0)
	return code;
    code = gdev_prn_put_params(pdev, plist);
    if (code < 0)
	return code;
    hl1250->source_tray = source_tray;
    hl1250->econo_mode = econo_mode;
    return 0;
}
