/**********************************************************************
 * File:			ocrshell.cpp
 * Description:	Code for the OCR side of the OCR API.
 * Author:		Hewlett-Packard Co
 *
 * (C) Copyright 1996, Hewlett-Packard Co.
 ** Licensed under the Apache License, Version 2.0 (the "License");
 ** you may not use this file except in compliance with the License.
 ** You may obtain a copy of the License at
 ** http://www.apache.org/licenses/LICENSE-2.0
 ** Unless required by applicable law or agreed to in writing, software
 ** distributed under the License is distributed on an "AS IS" BASIS,
 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ** See the License for the specific language governing permissions and
 ** limitations under the License.
 *
 **********************************************************************/

/**********************************************************************
 * This file contains code for the OCR side of the HP OCR interface.
 * The code is designed to be used with either an ANSI C or C++ compiler.
 * The structures are designed to allow them to be used with any
 * structure alignment upto 8.
 **********************************************************************/

#include          "mfcpch.h"
#include          "ocrshell.h"
#include          "tprintf.h"
#include          <stdlib.h>

#define EXTERN

EXTERN ESHM_INFO shm;            /*info on shm */
#define TICKS       1000

typedef enum {
  OCS_UNINIT,                    /*uninitialized */
  OCS_SETUP_SHM,                 /*shm setup done */
  OCS_SETUP_INFO,                /*startinfo sent */
  OCS_READING_STRIPS,            /*read first but more to come */
  OCS_READ_STRIPS,               /*read all but no monitor yet */
  OCS_RECOGNIZING,               /*OCR incomplete */
  OCS_SENDING_TEXT,              /*sent buffer but more to come */
  OCS_DEAD                       /*disconnected */
} OCR_STATE;

/* forward declarations - not in .h file as not needed outside this file*/
inT16 ocr_internal_shutdown();  /*closedown */

static inT32 font_count = 0;     /*number of fonts */
static inT16 lines_read = 0;     /*no read in this image */
                                 /*current state */
static OCR_STATE ocr_state = OCS_UNINIT;

#ifdef __MAC__
pascal short TerminateOCR(AppleEvent *theEvent,
                          AppleEvent *theReply,
                          long refCon) {
  ocr_internal_shutdown();
  ExitToShell();

}
#endif

/**********************************************************************
 * ocr_error
 *
 * Inform the HP side of an error.
 * The OCR engine should do any cleanup of its own and exit aferwards.
 * Uses the current state to determine how to send it and cleanup.
 **********************************************************************/

void ocr_error(                   /*send an error code */
               OCR_ERR_CODE code  /*error code */
              ) {
  ESTRIP_DESC *strip = (ESTRIP_DESC *) shm.shm_mem;
  /*strip info */
  ETEXT_DESC *monitor = (ETEXT_DESC *) shm.shm_mem;
  /*progress monitor */

  switch (ocr_state) {
    case OCS_UNINIT:             /*uninitialized */
    case OCS_DEAD:               /*uninitialized */
      return;                    /*can't do anything else */
    case OCS_SETUP_SHM:          /*shm setup done */
      if (font_count < 1)
        font_count = 1;
      ocr_setup_startinfo_ansi (-code, LANGE_NONE, "", "");
      /*report error */
      break;
    case OCS_READING_STRIPS:     /*read first but more to come */
      strip->x_size = -code;     /*report error */
      break;
    case OCS_READ_STRIPS:        /*read all but no monitor yet */
      monitor->count = 0;        /*chars in this buffer(-1) */
      monitor->progress = 0;     /*percent complete increasing (0-100) */
                                 /*text not complete */
      monitor->more_to_come = FALSE;
      monitor->ocr_alive = TRUE; /*ocr sets to 1, hp 0 */
      monitor->err_code = -code; /*report error */
      monitor->cancel = FALSE;   /*0=continue, 1=cancel */
      break;
    case OCS_RECOGNIZING:        /*OCR incomplete */
    case OCS_SENDING_TEXT:       /*sent buffer but more to come */
      monitor->err_code = -code; /*report error */
  }
  ocr_internal_shutdown();  /*get ready for exit */
}


/**********************************************************************
 * ocr_append_fontinfo
 *
 * Initialize one of the font descriptors.
 **********************************************************************/

inT16 ocr_append_fontinfo(                    /*put info into shm */
                          uinT16 language,    /*default language */
                          uinT8 font_family,  /*serif/not, fixed/not */
                          uinT8 char_set,     /*character set standard */
                          uinT8 pitch,        /*fixed or prop */
                          const char *name    /*plain ascii name */
                         ) {
  EOCR_DESC *desc;               /*ocr engine info */
  int index;                     /*char index */
  inT32 font_index;              /*which font */

  if (ocr_state != OCS_SETUP_SHM) {
    ocr_error(OCR_ERR_BAD_STATE);
    return OCR_API_BAD_STATE;    /*incorrect state */
  }

                                 /*turn to right type */
  desc = (EOCR_DESC *) shm.shm_mem;
  if (font_count >
    (inT32) ((shm.shm_size - sizeof (EOCR_DESC)) / sizeof (EFONT_DESC)))
    return OCR_API_NO_MEM;       /*insufficient space */
  font_index = font_count++;     /*add a font */
                                 /*setup structure */
  desc->fonts[font_index].language = language;
                                 /*setup structure */
  desc->fonts[font_index].font_family = font_family;
                                 /*setup structure */
  desc->fonts[font_index].char_set = char_set;
                                 /*setup structure */
  desc->fonts[font_index].pitch = pitch;
  if (name != NULL) {
    for (index = 0; index < MAX_FONT_NAME && name[index] != 0; index++)
      desc->fonts[font_index].name[index] = name[index];
  }
  else
    index = 0;
  desc->fonts[font_index].name[index] = 0;
  return OKAY;
}


/**********************************************************************
 * ocr_setup_startinfo
 *
 * Setup the info on the OCR engine. Uses 16 bit chars to name the
 * engine.
 **********************************************************************/

inT16 ocr_setup_startinfo(                       /*put info into shm */
                          inT32 protocol,        /*interface version */
                          uinT16 language,       /*default language */
                          const uinT16 *name,    /*name of engine */
                          const uinT16 *version  /*version of engine */
                         ) {
  EOCR_DESC *desc;               /*ocr engine info */
  int index;                     /*char index */
  inT16 result;                  /*from open */

  if (ocr_state != OCS_SETUP_SHM || font_count < 1) {
    ocr_error(OCR_ERR_BAD_STATE);
    return OCR_API_BAD_STATE;    /*incorrect state */
  }

                                 /*turn to right type */
  desc = (EOCR_DESC *) shm.shm_mem;
  desc->protocol = protocol;     /*setup structure */
  desc->font_count = font_count;
  desc->language = language;
  for (index = 0; index < MAX_OCR_NAME && name[index] != 0; index++)
    desc->name[index] = name[index];
  desc->name[index] = 0;
  for (index = 0; index < MAX_OCR_VERSION && version[index] != 0; index++)
    desc->version[index] = version[index];
  desc->version[index] = 0;

  ocr_state = OCS_SETUP_INFO;    /*record state */
  return OKAY;
}


/**********************************************************************
 * ocr_setup_startinfo_ansi
 *
 * Setup the info on the OCR engine. Uses 8 bit chars to name the
 * engine.
 **********************************************************************/

inT16 ocr_setup_startinfo_ansi(                     /*put info into shm */
                               uinT32 protocol,     /*interface version */
                               uinT16 language,     /*default language */
                               const char *name,    /*name of engine */
                               const char *version  /*version of engine */
                              ) {
  EOCR_DESC *desc;               /*ocr engine info */
  int index;                     /*char index */
  inT16 result;                  /*from open */

  if (ocr_state != OCS_SETUP_SHM || font_count < 1) {
    ocr_error(OCR_ERR_BAD_STATE);
    return OCR_API_BAD_STATE;    /*incorrect state */
  }

                                 /*turn to right type */
  desc = (EOCR_DESC *) shm.shm_mem;
  desc->protocol = protocol;     /*setup structure */
  desc->font_count = font_count;
  desc->language = language;
  for (index = 0; index < MAX_OCR_NAME && name[index] != 0; index++)
    desc->name[index] = name[index];
  desc->name[index] = 0;
  for (index = 0; index < MAX_OCR_VERSION && version[index] != 0; index++)
    desc->version[index] = version[index];
  desc->version[index] = 0;

  ocr_state = OCS_SETUP_INFO;    /*record state */
  return OKAY;
}

/**********************************************************************
 * ocr_get_next_image_strip
 *
 * Wait for the master to send the next image strip and return a
 * pointer to it. The result is NULL if it is time to exit.
 **********************************************************************/

ESTRIP_DESC *ocr_get_next_image_strip() {  /*get image strip */
  ESTRIP_DESC *strip;            /*strip info */
  inT16 result;                  /*of wait/release */

  if (ocr_state != OCS_READING_STRIPS) {
    ocr_error(OCR_ERR_BAD_STATE);
    return NULL;                 /*incorrect state */
  }

                                 /*strip info */
  strip = (ESTRIP_DESC *) shm.shm_mem;
                                 /*lines read so far */
  lines_read += strip->strip_size;
  if (lines_read < strip->y_size)
                                 /*record state */
      ocr_state = OCS_READING_STRIPS;
  else
    ocr_state = OCS_READ_STRIPS;

  return strip;
}


/**********************************************************************
 * ocr_setup_monitor
 *
 * Setup the progress monitor. Call before starting the recognize task.
 **********************************************************************/

ETEXT_DESC *ocr_setup_monitor() {  /*setup monitor */
  ETEXT_DESC *monitor;           /*progress monitor */

                                 /*text info */
  monitor = (ETEXT_DESC *) shm.shm_mem;
  monitor->count = 0;            /*chars in this buffer(-1) */
  monitor->progress = 0;         /*percent complete increasing (0-100) */
  monitor->more_to_come = TRUE;  /*text not complete */
  monitor->ocr_alive = TRUE;     /*ocr sets to 1, hp 0 */
  monitor->err_code = 0;         /*used by ocr_error */
  monitor->cancel = FALSE;       /*0=continue, 1=cancel */


  ocr_state = OCS_RECOGNIZING;   /*record state */
  return monitor;
}


/**********************************************************************
 * ocr_char_space
 *
 * Return the number of chars that can be fitted into the buffer.
 **********************************************************************/

inT32 ocr_char_space() {  /*put char into shm */
  ETEXT_DESC *buf;               /*text buffer */
  int result;

                                 /*progress info */
  buf = (ETEXT_DESC *) shm.shm_mem;
  if (buf == NULL)
    return 0;

  result =
    (shm.shm_size - sizeof (ETEXT_DESC)) / sizeof (EANYCODE_CHAR) -
    buf->count + 1;

  //      while (buf->hp_alive==-1)
  //              Sleep(50);                                                                              /*wait for HP*/

  return result;
}


/**********************************************************************
 * ocr_append_char
 *
 * Add a character to the output. Returns OKAY if successful, OCR_API_NO_MEM
 * if there was insufficient room in the buffer.
 **********************************************************************/

inT16 ocr_append_char(                              /*put char into shm */
                      uinT16 char_code,             /*character itself */
                      inT16 left,                   /*of char (-1) */
                      inT16 right,                  /*of char (-1) */
                      inT16 top,                    /*of char (-1) */
                      inT16 bottom,                 /*of char (-1) */
                      inT16 font_index,             /*what font (-1) */
                      uinT8 confidence,             /*0=perfect, 100=reject (0/100) */
                      uinT8 point_size,             /*of char, 72=i inch, (10) */
                      inT8 blanks,                  /*no of spaces before this char (1) */
                      uinT8 enhancement,            /*char enhancement (0) */
                      OCR_CHAR_DIRECTION text_dir,  /*rendering direction (OCR_CDIR_RIGHT_LEFT) */
                      OCR_LINE_DIRECTION line_dir,  /*line rendering direction (OCR_LDIR_DOWN_RIGHT) */
                      OCR_NEWLINE_TYPE nl_type      /*type of newline (if any) (OCR_NL_NONE) */
                     ) {
  ETEXT_DESC *buf;               /*text buffer */
  int index;                     /*char index */
  inT16 result;                  /*of callback */

  if (ocr_state != OCS_RECOGNIZING && ocr_state != OCS_SENDING_TEXT) {
    ocr_error(OCR_ERR_BAD_STATE);
    return OCR_API_BAD_STATE;    /*incorrect state */
  }

  if (char_code == ' ' || char_code == '\n' || char_code == '\r'
    || char_code == '\t')
    return OCR_API_BAD_CHAR;     /*illegal char */

                                 /*progress info */
  buf = (ETEXT_DESC *) shm.shm_mem;

  result =
    (shm.shm_size - sizeof (ETEXT_DESC)) / sizeof (EANYCODE_CHAR) -
    buf->count;
  if (result < 1)
    return OCR_API_NO_MEM;       /*insufficient room */

  index = buf->count++;          /*count of chars */
                                 /*setup structure */
  buf->text[index].char_code = char_code;
  buf->text[index].left = left;  /*setup structure */
  buf->text[index].right = right;/*setup structure */
  buf->text[index].top = top;    /*setup structure */
                                 /*setup structure */
  buf->text[index].bottom = bottom;
                                 /*setup structure */
  buf->text[index].font_index = font_index;
                                 /*setup structure */
  buf->text[index].confidence = confidence;
                                 /*setup structure */
  buf->text[index].point_size = point_size;
                                 /*setup structure */
  buf->text[index].blanks = blanks;
  if (nl_type == OCR_NL_NONE) {
    if (text_dir == OCR_CDIR_TOP_BOTTOM || text_dir == OCR_CDIR_BOTTOM_TOP)
      buf->text[index].formatting = (text_dir << 5) | 128;
    /*setup structure */
    else
                                 /*setup structure */
      buf->text[index].formatting = text_dir << 5;
  }
  else {
    buf->text[index].formatting = (nl_type << 6) | (line_dir << 5);
    /*setup structure */
  }
  buf->text[index].formatting |= enhancement & (~EUC_FORMAT_MASK);
  return OKAY;
}


/**********************************************************************
 * ocr_send_text
 *
 * Send the text to the host and wait for the ack.
 * Use this function after a sequence of ocr_append_char calls to
 * actually sent the text to the master process.
 * Set more to come TRUE if there is more text in this page, FALSE
 * if the OCR engine is now ready to receive another image.
 **********************************************************************/

inT16 ocr_send_text(                    /*send shm */
                    BOOL8 more_to_come  /*any text left */
                   ) {
  ETEXT_DESC *buf;               /*text buffer */

  if (ocr_state != OCS_RECOGNIZING && ocr_state != OCS_SENDING_TEXT) {
    ocr_error(OCR_ERR_BAD_STATE);
    return OCR_API_BAD_STATE;    /*incorrect state */
  }

                                 /*progress info */
  buf = (ETEXT_DESC *) shm.shm_mem;

                                 /*setup structure */
  buf->more_to_come = more_to_come;
  if (more_to_come) {
    if ((buf->text[buf->count - 1].formatting >> 6) != OCR_NL_NEWLINE
    && (buf->text[buf->count - 1].formatting >> 6) != OCR_NL_NEWPARA) {
                                 /*force line end */
      buf->text[buf->count - 1].formatting &= 63;
      buf->text[buf->count - 1].formatting |= OCR_NL_NEWLINE << 6;
    }
  }
  else {
    if (buf->count < 1)
      ocr_append_char ('~', -1, -1, -1, -1, 0, 100, 10, 0,
        0, OCR_CDIR_RIGHT_LEFT, OCR_LDIR_DOWN_RIGHT,
        OCR_NL_NEWPARA);
    /*dummy character */
    else if ((buf->text[buf->count - 1].formatting >> 6) != OCR_NL_NEWPARA) {
                                 /*force para end */
      buf->text[buf->count - 1].formatting &= 63;
      buf->text[buf->count - 1].formatting |= OCR_NL_NEWPARA << 6;
    }
  }

  if (more_to_come) {
    buf->count = 0;              /*setup structure */
    ocr_state = OCS_SENDING_TEXT;/*record state */
  }
  else
    ocr_state = OCS_SETUP_INFO;  /*record state */
  return OKAY;
}

/**********************************************************************
 * ocr_internal_shutdown
 *
 * Free up handles or whatever to clean up without attempting to communicate.
 **********************************************************************/

inT16 ocr_internal_shutdown() {  /*closedown */
  ocr_state = OCS_DEAD;          /*record state */
  #ifdef __MSW32__
  if (shm.shm_mem != NULL) {
	  delete [] shm.shm_mem;
	  shm.shm_mem = NULL;
	  shm.shm_size = 0;
  }
  #elif defined (__MAC__)
  shm.OCRProcess.lowLongOfPSN = kNoProcess;
  shm.OCRProcess.highLongOfPSN = 0;
  #endif
  return OKAY;
}

