
/*
 * tgif_lib.c
 *
 * by Noritsugu Nakamura
 * from 2001.04.05
 */

#include "../tgifdefs.h"

#include "tgif_lib.h"

#include "../arc.e"
#include "../attr.e"
#include "../auxtext.e"
#include "../box.e"
#include "../color.e"
#include "../dialog.e"
#include "../file.e"
#include "../font.e"
#include "../ftp.e"
#include "../grid.e"
#include "../group.e"
#include "../http.e"
#include "../imgproc.e"
#include "../import.e"
#include "../mainloop.e"
#include "../miniline.e"
#include "../move.e"
#include "../msg.e"
#include "../names.e"
#include "../obj.e"
#include "../oval.e"
#include "../pattern.e"
#include "../poly.e"
#include "../polygon.e"
#include "../rcbox.e"
#include "../setup.e"
#include "../select.e"
#include "../stretch.e"
#include "../text.e"
#include "../util.e"
#include "../xpixmap.e"


#define THIS_TOOL_NAME "Ruby/Tgif"

/* from tgifcal-1.0.2/tgifintf.c */

int	lastFile=TRUE;

short pDrawFontAsc[] = {
    8, 10, 12, 14, 17, 22, 
    8, 10, 12, 14, 17, 22, 
    8, 10, 12, 14, 17, 23, 
    8, 10, 12, 14, 17, 22, 
    8,  9, 11, 13, 15, 19, 
    7,  9, 11, 12, 15, 20, 
    7,  9, 11, 13, 15, 19, 
    7,  9, 11, 12, 15, 20, 
    9, 11, 12, 14, 18, 24, 
    9, 11, 12, 14, 17, 24, 
    9, 11, 12, 14, 17, 24, 
    9, 11, 12, 14, 17, 24, 
    8, 11, 12, 14, 18, 23, 
    8, 11, 12, 15, 18, 24, 
    8, 11, 12, 14, 16, 23, 
    8, 11, 12, 14, 16, 24, 
    8, 10, 12, 14, 18, 24, 
    9, 14, 15, 18, 23, 30, 
   10, 14, 16, 17, 23, 30, 
    9, 13, 15, 17, 22, 30, 
    9, 13, 15, 18, 22, 30, 
    9, 12, 14, 15, 19, 26, 
    9, 12, 14, 15, 21, 26, 
    9, 12, 14, 15, 19, 26, 
    9, 12, 14, 15, 20, 26, 
   11, 14, 16, 18, 24, 31, 
   11, 14, 16, 18, 24, 31, 
   11, 14, 16, 18, 24, 31, 
   11, 14, 16, 18, 24, 31, 
   11, 14, 16, 19, 24, 32, 
   11, 15, 16, 19, 24, 33, 
   11, 14, 16, 18, 23, 32, 
   11, 15, 16, 19, 24, 32, 
   11, 12, 13, 14, 19, 27 
};
short pDrawFontDes[] = {
    2,  3,  3,  4,  4,  6, 
    2,  3,  3,  4,  4,  6, 
    2,  3,  3,  4,  5,  6, 
    2,  3,  3,  3,  4,  6, 
    2,  2,  3,  3,  4,  5, 
    2,  2,  3,  4,  5,  5, 
    2,  2,  3,  3,  4,  5, 
    2,  2,  3,  4,  5,  5, 
    2,  2,  3,  3,  4,  5, 
    2,  2,  3,  3,  5,  5, 
    2,  2,  3,  3,  5,  5, 
    2,  2,  3,  3,  5,  5, 
    2,  2,  3,  3,  4,  5, 
    2,  2,  3,  3,  4,  5, 
    2,  2,  3,  3,  6,  5, 
    2,  2,  3,  3,  6,  5, 
    3,  4,  4,  6,  7,  8, 
    3,  3,  4,  4,  6,  7, 
    3,  3,  4,  4,  6,  7, 
    3,  4,  4,  5,  6,  7, 
    3,  3,  4,  4,  6,  7, 
    2,  3,  3,  4,  5,  6, 
    2,  4,  3,  5,  5,  7, 
    2,  3,  4,  4,  5,  6, 
    2,  4,  4,  5,  5,  7, 
    2,  3,  4,  4,  5,  7, 
    2,  3,  4,  5,  5,  7, 
    2,  3,  4,  5,  5,  7, 
    2,  3,  4,  5,  5,  7, 
    2,  3,  3,  4,  5,  7, 
    2,  3,  3,  4,  5,  7, 
    2,  3,  3,  4,  5,  7, 
    2,  3,  3,  4,  5,  7, 
    4,  3,  4,  5,  5,  7 
};

static int Tgif_save_textJust, Tgif_save_textVSpace,
  Tgif_save_penPat, Tgif_save_lineStyle,
  Tgif_save_curDash, Tgif_save_lineWidth,
  Tgif_save_curSpline, Tgif_save_colorIndex;

/* from tgifcal-1.0.2/tgifintf.c */
int InitTgifInterface()
{
  int new_alloc=FALSE;

  PRTGIF = TRUE;
  cmdLineOpenDisplay = TRUE;
  InitPaperSize();
  JustInit(NULL, NULL);

  /* things that never change */
  textJust = JUST_L;
  textVSpace = 0;
  penPat = SOLIDPAT;
  lineStyle = LS_RIGHT;
  curDash = 0;
  lineWidth = 0; /* this is the line width index */
  curSpline = LT_STRAIGHT;
  rcbRadius = 16;
  colorIndex = QuickFindColorIndex(NULL, "Black", &new_alloc, TRUE);

  zoomedIn = FALSE;
  zoomScale = 1;

  printMag = (float)180.0;
  UpdPageStyle(PORTRAIT);

  debugHttp = debugFtp = 0;

  return TRUE;
}

/* from tgif-4.1.40/file.c LoadFile */
int TgifLoadFile(FullName)
	 char *FullName;
{
  struct ObjRec *obj_ptr=NULL;
  char file_name[MAXPATHLENGTH+1];
  int read_status, interrupted;
  FILE *fp=NULL;

  strcpy(file_name, FullName);
  if ((fp=fopen(file_name, "r")) == NULL) {
  }

  while ((read_status=ReadObj(fp, &obj_ptr)) == TRUE) {
	if (obj_ptr != NULL) {
	  obj_ptr->tmp_parent = NULL;
	  AdjForOldVersion(obj_ptr);
	  AddObj(NULL, topObj, obj_ptr);
	  if (!interrupted && readingPageNum == loadedCurPageNum &&
		  (PointInBBox(obj_ptr->x, obj_ptr->y, drawWinBBox) ||
		   BBoxIntersect(obj_ptr->bbox, drawWinBBox))) {
		if (!DrawObj(drawWindow, obj_ptr)) interrupted = TRUE;
		if (CheckInterrupt(TRUE)) interrupted = TRUE;
	  }
	}
  }
  fclose(fp);
  
}

/* from tgifcal-1.0.2/tgifintf.c TgifGenerate */
int TgifOutObj(fp, psz_format)
	 FILE *fp;
	 char *psz_format;
{
  if (UtilStrICmp(psz_format, "obj") == 0) {
	Save(fp, botObj, 0, 1);
  } else {
	fprintf(stderr, "Unrecognized format '%s'.\n",
            (psz_format==NULL ? "(unknown)" : psz_format));
	return FALSE;
  }
  return TRUE;
}

int TgifOutPS(filename, psz_format)
	 char *filename, *psz_format;
{
  char *psz = NULL;
  int len = strlen(filename);

  if (UtilStrICmp(psz_format, "ps") == 0) {
	char saved_print_command[MAXSTRING+1];

	UtilStrCpyN(saved_print_command, sizeof(saved_print_command),
				printCommand);
	/*PRTGIF = FALSE;*/
	PRTGIF = TRUE;
	/*whereToPrint = PRINTER;*/
	whereToPrint = PS_FILE;
	colorDump = TRUE;
	/*strcpy(printCommand, "cat");*/
	strcpy(printCommand, "");
	/*fprintf(stderr, "curFileName %s\n", curFileName);*/
	/*strcpy(curFileName, "tmp");*/
	/*curFileDefined = TRUE;*/
	/*fprintf(stderr, "curFileDefined %d\n", curFileDefined);*/
	/*	if ((psz = strstr(filename, ".ps")) != NULL &&
		strcmp(psz, ".ps") == 0) {*/
	if ((psz = strstr(filename, ".ps")) != NULL) {
      filename[len - strlen(".ps")] = '\0';
	}
	/*fprintf(stderr, "filename %s\n", filename);*/
	Dump(filename);
	strcpy(printCommand, saved_print_command);
	PRTGIF = TRUE;
	/*curFileDefined = FALSE;*/
  } else {
	fprintf(stderr, "Unrecognized format '%s'.\n",
            (psz_format==NULL ? "(unknown)" : psz_format));
	return FALSE;
  }
  return TRUE;
}


/* from tgifcal-1.0.2/tgifintf.c TgifBox */
int TgifBox(ltx, lty, rbx, rby, rotate)
	 float *ltx, *lty, *rbx, *rby;
	 int rotate;
{
  struct BBRec bbox;

  bbox.ltx = round(*ltx); bbox.lty = round(*lty);
  bbox.rbx = round(*rbx); bbox.rby = round(*rby);
  CreateBoxObj(bbox.ltx, bbox.lty, bbox.rbx, bbox.rby, TRUE);
  if (rotate != 0) {
	fprintf(stderr, "\n%s Error in %s - %s: %1d (yet).\n",
            THIS_TOOL_NAME, "Tgif#box()",
            "Don't know how to handle rotate having value", rotate);
	return FALSE;
  }

  return TRUE;
}

/* from tgifcal-1.0.2/tgifintf.c TgifBox + alpha */
int TgifRCBox(ltx, lty, rbx, rby, rotate)
	 float *ltx, *lty, *rbx, *rby;
	 int rotate;
{
  struct BBRec bbox;

  bbox.ltx = round(*ltx); bbox.lty = round(*lty);
  bbox.rbx = round(*rbx); bbox.rby = round(*rby);
  CreateRCBoxObj(bbox.ltx, bbox.lty, bbox.rbx, bbox.rby, TRUE);
  if (rotate != 0) {
	fprintf(stderr, "\n%s Error in %s - %s: %1d (yet).\n",
            THIS_TOOL_NAME, "Tgif#rcbox()",
            "Don't know how to handle rotate having value", rotate);
	return FALSE;
  }

  return TRUE;
}

/* from tgifcal-1.0.2/tgifintf.c TgifOval */
int TgifOval(ltx, lty, rbx, rby)
	 float *ltx, *lty, *rbx, *rby;
{
  struct BBRec bbox;

  bbox.ltx = round(*ltx); bbox.lty = round(*lty);
  bbox.rbx = round(*rbx); bbox.rby = round(*rby);
  CreateOvalObj(&bbox, TRUE);

  return TRUE;
}

/* from tgifcal-1.0.2/tgifintf.c TgifStartVertex */
static int gnNumVertices=0;

int TgifStartVertex(x, y)
	 float *x, *y;
{
  if (gnNumVertices != 0) {
	fprintf(stderr, "\n%s Error in %s - %s.\n",
            THIS_TOOL_NAME, "TgifStartVertex()", "gnNumVertices is not 0");
	return FALSE;
  }
  gnNumVertices = 0;
  ResetCreatePoly();
  if (x != NULL && y != NULL) {
	AddPtToCreatePoly(round(*x), round(*y));
	gnNumVertices++;
  }
  return TRUE;
}

/* from tgifcal-1.0.2/tgifintf.c TgifAddVertex */
int TgifAddVertex(x, y)
	 float *x, *y;
{
  AddPtToCreatePoly(round(*x), round(*y));
  gnNumVertices++;

  return TRUE;
}

/* from tgifcal-1.0.2/tgifintf.c TgifPoly */
int TgifPoly()
{
  if (gnNumVertices <= 1) {
	fprintf(stderr, "\n%s Error in %s - %s: %1d.\n",
            THIS_TOOL_NAME, "TgifPoly()",
            "Too few points", gnNumVertices);
	return FALSE;
  }
  CreatePolyObj(gnNumVertices, TRUE);
  gnNumVertices = 0;

  return TRUE;
}

int TgifPolygon()
{
  if (gnNumVertices <= 1) {
	fprintf(stderr, "\n%s Error in %s - %s: %1d.\n",
            THIS_TOOL_NAME, "TgifPolygon()",
            "Too few points", gnNumVertices);
	return FALSE;
  }

  CreatePolygonObj(gnNumVertices, TRUE);
  gnNumVertices = 0;

  return TRUE;
}

int TgifArc(xc, yc, x1, y1, x2, y2, dir, ltx, lty, w, h, angle1, angle2)
	 float *xc, *yc, *x1, *y1, *x2, *y2, *dir, *ltx, *lty, *w, *h, *angle1, *angle2;
{

  CreateArcObj(round(*xc), round(*yc), round(*x1), round(*y1), round(*x2), round(*y2), round(*dir),
			   round(*ltx), round(*lty), round(*w), round(*h), round(*angle1), round(*angle2), TRUE);

  return TRUE;
}

/* from tgifcal-1.0.2/tgifintf.c TgifText */
int TgifText(x, baseline_y, font_name, font_size, buf)
	 float *x, *baseline_y;
	 int font_size;
	 char *font_name, *buf;
{
  int saved_font=curFont, saved_style=curStyle, saved_sz_unit=curSzUnit;

  if (strcmp(font_name, "Courier") == 0) {
	curFont = FONT_COU;
	curStyle = STYLE_NR;
  } else if (strcmp(font_name, "Times-BoldItalic") == 0) {
	curFont = FONT_TIM;
	curStyle = STYLE_BI;
  } else if (strcmp(font_name, "Times-Bold") == 0) {
	curFont = FONT_TIM;
	curStyle = STYLE_BR;
  } else if (strcmp(font_name, "Ryumin-Light-EUC-H") == 0) {
	curFont = 5;
	curStyle = STYLE_NR;
  } else if (strcmp(font_name, "GothicBBB-Medium-EUC-H") == 0) {
	curFont = 6;
	curStyle = STYLE_NR;
  } else {
	fprintf(stderr, "\n%s Error in %s - Unrecognized font_name: '%s'\n",
            THIS_TOOL_NAME, "Tgif#text()", font_name);
	return FALSE;
  }
  curSzUnit = FontSizeToSzUnit(font_size);

  SetCanvasFont();
  NewCurText();
  DynStrSet(&topObj->detail.t->minilines.first->first_block->seg->dyn_str,
			buf);
  RecalcTextMetrics(topObj->detail.t, topObj->x, topObj->detail.t->baseline_y);
  UpdTextBBox(topObj);
  MoveObj(topObj, round(*x)-topObj->x,
		  round(*baseline_y)-topObj->detail.t->baseline_y);

  curFont = saved_font;
  curStyle = saved_style;
  curSzUnit = saved_sz_unit;
  SetCanvasFont();

  return TRUE;
}

/* image */
#define TOL_ASPECT_RATIO (0.04)

/* from tgifcal-1.0.2/tgifintf.c FinishImport */
static
int FinishImport(path, x, y, w, h, gamma, fit)
   char *path;
   float *x, *y, *w, *h;
   char *gamma;
   int fit;
{
   int nW=round(*w), nH=round(*h), final_x=0, final_y=0, final_w=0, final_h=0;
   float orig_aspect_ratio=(float)0, aspect_ratio=(*w)/(*h);

   orig_aspect_ratio = ((float)(topObj->detail.xpm->image_w)) /
         ((float)(topObj->detail.xpm->image_h));
   final_w = nW;
   final_h = nH;
   final_x = round(*x);
   final_y = round(*y);
   if (fit) {
      if (fabs(orig_aspect_ratio-aspect_ratio) > TOL_ASPECT_RATIO) {
         fprintf(stderr, "%s: aspect ratio adjusted from %.2f to %.2f\n",
               THIS_TOOL_NAME, orig_aspect_ratio, aspect_ratio);
      }
   } else {
      if (topObj->detail.xpm->image_w == nW &&
            topObj->detail.xpm->image_h == nH) {
      } else if (orig_aspect_ratio > aspect_ratio) {
         final_w = nW;
         final_h = round(((float)nW) / orig_aspect_ratio);
         final_x = round(*x);
         final_y = round(*y) + ((nH-final_h)>>1);
      } else {
         final_h = nH;
         final_w = round(((float)nH) * orig_aspect_ratio);
         final_y = round(*y);
         final_x = round(*x) + ((nW-final_w)>>1);
      }
   }
   SelectTopObj();
   if (topObj->detail.xpm->image_w != nW || topObj->detail.xpm->image_h != nH) {
      fprintf(stderr, "%s: resizing image...\n", THIS_TOOL_NAME);
      SizeAllSelToGivenWidthHeight(final_w, final_h);
      MoveObj(topObj, final_x-topObj->x, final_y-topObj->y);
   }
#if 0
   if (gamma != NULL && *gamma != '\0') {
      fprintf(stderr, "%s: applying gamma correction...\n", THIS_TOOL_NAME);
      Gamma(gamma);
   }
#endif
   MakeQuiescent();
   AdjObjBBox(topObj);

   return TRUE;
}

/* from tgifcal-1.0.2/tgifintf.c TgifImportGIF */
int TgifImportGIF(path, x, y, w, h, gamma, fit)
   char *path;
   float *x, *y, *w, *h;
   char *gamma;
   int fit;
{
   int saved_color_index=colorIndex, rc=TRUE;

   fprintf(stderr, "%s: importing image...\n", THIS_TOOL_NAME);

#if 0
   if (!ImportSpecifiedFileType(path, "GIF")) {
	 fprintf(stderr, "Fail to import '%s'.\n", path);
	 return FALSE;
   }
#endif
   rc = FinishImport(path, x, y, w, h, gamma, fit);
   colorIndex = saved_color_index;

   return rc;
}

/* from tgifcal-1.0.2/tgifintf.c TgifImportJPEG */
int TgifImportJPEG(path, x, y, w, h, gamma, fit)
   char *path;
   float *x, *y, *w, *h;
   char *gamma;
   int fit;
{
   int saved_color_index=colorIndex, rc=TRUE;

   fprintf(stderr, "%s: importing image...\n", THIS_TOOL_NAME);
   if (!ImportSpecifiedFileType(path, "JPEG")) {
      fprintf(stderr, "Fail to import '%s'.\n", path);
      return FALSE;
   }
   rc = FinishImport(path, x, y, w, h, gamma, fit);
   colorIndex = saved_color_index;

   return rc;
}

void TgifSaveState()
{
  Tgif_save_textJust   = textJust;
  Tgif_save_textVSpace = textVSpace;
  Tgif_save_penPat     = penPat;
  Tgif_save_lineStyle  = lineStyle;
  Tgif_save_curDash    = curDash;
  Tgif_save_lineWidth  = lineWidth;
  Tgif_save_curSpline  = curSpline;
  Tgif_save_colorIndex = colorIndex;
}

void TgifRestoreState()
{
  textJust   = Tgif_save_textJust;
  textVSpace = Tgif_save_textVSpace;
  penPat     = Tgif_save_penPat;
  lineStyle  = Tgif_save_lineStyle;
  curDash    = Tgif_save_curDash;
  lineWidth  = Tgif_save_lineWidth;
  curSpline  = Tgif_save_curSpline;
  colorIndex = Tgif_save_colorIndex;
}
