twain.c 26.8 KB
Newer Older
1
/*
2 3
 * TWAIN Plug-in
 * Copyright (C) 1999 Craig Setera
4
 * Craig Setera <setera@home.com>
5 6
 * 03/31/1999
 *
7 8 9 10
 * Updated for Mac OS X support
 * Brion Vibber <brion@pobox.com>
 * 07/22/2004
 *
11
 * This program is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation; either version 3 of the License, or
14 15 16 17 18 19 20 21
 * (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
22
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 24 25 26 27 28 29 30
 *
 *
 * Based on (at least) the following plug-ins:
 * Screenshot
 * GIF
 * Randomize
 *
 * Any suggestions, bug-reports or patches are welcome.
31
 *
32 33 34 35 36 37 38 39 40 41
 * This plug-in interfaces to the TWAIN support library in order
 * to capture images from TWAIN devices directly into GIMP images.
 * The plug-in is capable of acquiring the following type of
 * images:
 * - B/W (1 bit images translated to grayscale B/W)
 * - Grayscale up to 16 bits per pixel
 * - RGB up to 16 bits per sample (24, 30, 36, etc.)
 * - Paletted images (both Gray and RGB)
 *
 * Prerequisites:
42 43
 * Should compile and run on both Win32 and Mac OS X 10.3 (possibly
 * also on 10.2).
44 45 46 47
 *
 * Known problems:
 * - Multiple image transfers will hang the plug-in.  The current
 *   configuration compiles with a maximum of single image transfers.
48 49
 * - On Mac OS X, canceling doesn't always close things out fully.
 * - Epson TWAIN driver on Mac OS X crashes the plugin when scanning.
50 51
 */

52
/*
53 54 55 56
 * Revision history
 *  (02/07/99)  v0.1   First working version (internal)
 *  (02/09/99)  v0.2   First release to anyone other than myself
 *  (02/15/99)  v0.3   Added image dump and read support for debugging
57
 *  (03/31/99)  v0.5   Added support for multi-byte samples and paletted
58
 *                     images.
59
 *  (07/23/04)  v0.6   Added Mac OS X support.
60
 */
Tor Lillqvist's avatar
Tor Lillqvist committed
61 62
#include "config.h"

63 64 65 66 67
#include <glib.h>		/* Needed when compiling with gcc */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
68 69 70

#include "tw_platform.h"
#include "tw_local.h"
Tor Lillqvist's avatar
Tor Lillqvist committed
71

72
#include "libgimp/gimp.h"
Tor Lillqvist's avatar
Tor Lillqvist committed
73 74
#include "libgimp/stdplugins-intl.h"

75 76 77 78 79 80 81 82 83 84 85
#include "tw_func.h"
#include "tw_util.h"

#ifdef _DEBUG
#include "tw_dump.h"
#endif /* _DEBUG */

/*
 * Plug-in Definitions
 */
#define PLUG_IN_NAME        "twain-acquire"
86
#define PLUG_IN_DESCRIPTION N_("Capture an image from a TWAIN datasource")
Marc Lehmann's avatar
Marc Lehmann committed
87
#define PLUG_IN_HELP        "This plug-in will capture an image from a TWAIN datasource"
88
#define PLUG_IN_AUTHOR      "Craig Setera (setera@home.com)"
89
#define PLUG_IN_COPYRIGHT   "Craig Setera"
90
#define PLUG_IN_VERSION     "v0.6 (07/22/2004)"
91 92

#ifdef _DEBUG
93 94
#define PLUG_IN_D_NAME      "twain-acquire-dump"
#define PLUG_IN_R_NAME      "twain-acquire-read"
95 96 97 98 99 100 101 102
#endif /* _DEBUG */

/*
 * Application definitions
 */
#define MAX_IMAGES 1

/*
103
 * Definition of the run states
104 105 106 107 108 109 110 111 112
 */
#define RUN_STANDARD 0
#define RUN_DUMP 1
#define RUN_READDUMP 2

/* Global variables */
pTW_SESSION twSession = NULL;

static char        *destBuf = NULL;
113
#ifdef _DEBUG
114
static int         twain_run_mode = RUN_STANDARD;
115
#endif
116 117 118 119 120 121 122 123

/* Forward declarations */
void preTransferCallback(void *);
int  beginTransferCallback(pTW_IMAGEINFO, void *);
int  dataTransferCallback(pTW_IMAGEINFO, pTW_IMAGEMEMXFER, void *);
int  endTransferCallback(int, int, void *);
void postTransferCallback(int, void *);

124 125 126 127 128 129
static void query (void);
static void run   (const gchar      *name,
		   gint              nparams,
		   const GimpParam  *param,
		   gint             *nreturn_vals,
		   GimpParam       **return_vals);
130 131

/* This plug-in's functions */
132
const GimpPlugInInfo PLUG_IN_INFO =
133 134 135 136 137 138
{
  NULL,    /* init_proc */
  NULL,    /* quit_proc */
  query,   /* query_proc */
  run,     /* run_proc */
};
139

140
extern void set_gimp_PLUG_IN_INFO_PTR(GimpPlugInInfo *);
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157

/* Data structure holding data between runs */
/* Currently unused... Eventually may be used
 * to track dialog data.
 */
typedef struct {
  gchar  sourceName[34];
  gfloat xResolution;
  gfloat yResolution;
  gint   xOffset;
  gint   yOffset;
  gint   width;
  gint   height;
  gint   imageType;
} TwainValues;

/* Default Twain values */
158 159
static TwainValues twainvals =
{
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
  "",
  100.0, 100.0,
  0, 0,
  0, 0,
  TWPT_RGB
};

/* The standard callback functions */
TXFR_CB_FUNCS standardCbFuncs = {
  preTransferCallback,
  beginTransferCallback,
  dataTransferCallback,
  endTransferCallback,
  postTransferCallback };

/******************************************************************
 * Dump handling
 ******************************************************************/

#ifdef _DEBUG
/* The dumper callback functions */
TXFR_CB_FUNCS dumperCbFuncs = {
  dumpPreTransferCallback,
  dumpBeginTransferCallback,
  dumpDataTransferCallback,
  dumpEndTransferCallback,
  dumpPostTransferCallback };

188
void
189 190 191 192 193 194
setRunMode(char *argv[])
{
  char *exeName = strrchr(argv[0], '\\') + 1;

  LogMessage("Executable name: %s\n", exeName);

195
  if (!_stricmp(exeName, DUMP_NAME))
196 197
    twain_run_mode = RUN_DUMP;

198
  if (!_stricmp(exeName, RUNDUMP_NAME))
199 200 201
    twain_run_mode = RUN_READDUMP;
}
#endif /* _DEBUG */
202

203 204 205
#ifndef TWAIN_ALTERNATE_MAIN
MAIN()
#endif
206

207 208
int
scanImage (void)
209 210
{
#ifdef _DEBUG
211 212 213
  if (twain_run_mode == RUN_READDUMP)
    return readDumpedImage (twSession);
  else
214
#endif /* _DEBUG */
215
    return getImage (twSession);
216
}
217

218 219 220 221 222 223 224 225 226
/*
 * initTwainAppIdentity
 *
 * Initialize and return our application's identity for
 * the TWAIN runtime.
 */
static pTW_IDENTITY
getAppIdentity(void)
{
227
  pTW_IDENTITY appIdentity = g_new (TW_IDENTITY, 1);
228

229 230 231 232 233 234
  /* Set up the application identity */
  appIdentity->Id = 0;
  appIdentity->Version.MajorNum = 0;
  appIdentity->Version.MinorNum = 1;
  appIdentity->Version.Language = TWLG_USA;
  appIdentity->Version.Country = TWCY_USA;
235
  strcpy(appIdentity->Version.Info, "GIMP TWAIN 0.6");
236 237 238 239 240
  appIdentity->ProtocolMajor = TWON_PROTOCOLMAJOR;
  appIdentity->ProtocolMinor = TWON_PROTOCOLMINOR;
  appIdentity->SupportedGroups = DG_IMAGE;
  strcpy(appIdentity->Manufacturer, "Craig Setera");
  strcpy(appIdentity->ProductFamily, "GIMP");
241
  strcpy(appIdentity->ProductName, "GIMP");
242

243 244
  return appIdentity;
}
245

246 247 248 249 250 251 252 253
/*
 * initializeTwain
 *
 * Do the necessary TWAIN initialization.  This sets up
 * our TWAIN session information.  The session stuff is
 * something built by me on top of the standard TWAIN
 * datasource manager calls.
 */
254
pTW_SESSION
255 256 257
initializeTwain(void)
{
  pTW_IDENTITY appIdentity;
258

259 260
  /* Get our application's identity */
  appIdentity = getAppIdentity();
261

262 263
  /* Create a new session object */
  twSession = newSession(appIdentity);
264

265 266 267 268 269 270 271
  /* Register our image transfer callback functions */
#ifdef _DEBUG
  if (twain_run_mode == RUN_DUMP)
    registerTransferCallbacks(twSession, &dumperCbFuncs, NULL);
  else
#endif /* _DEBUG */
    registerTransferCallbacks(twSession, &standardCbFuncs, NULL);
272
  return twSession;
273
}
274

275 276 277
/******************************************************************
 * GIMP Plug-in entry points
 ******************************************************************/
278

279 280 281 282
/*
 * Plug-in Parameter definitions
 */
#define NUMBER_IN_ARGS 1
283
#define IN_ARGS { GIMP_PDB_INT32, "run-mode", "The run mode { RUN-INTERACTIVE (0), RUN-NONINTERACTIVE (1) }" }
284 285
#define NUMBER_OUT_ARGS 2
#define OUT_ARGS \
286 287
	{ GIMP_PDB_INT32, "image-count", "Number of acquired images" }, \
	{ GIMP_PDB_INT32ARRAY, "image-ids", "Array of acquired image identifiers" }
288

289

290 291 292 293 294 295
/*
 * query
 *
 * The plug-in is being queried.  Install our procedure for
 * acquiring.
 */
296
static void
297
query (void)
298
{
299 300
  static const GimpParamDef args[] = { IN_ARGS };
  static const GimpParamDef return_vals[] = { OUT_ARGS };
301 302 303

#ifdef _DEBUG
  if (twain_run_mode == RUN_DUMP)
304 305 306 307 308 309 310 311
    {
      /* the installation of the plugin */
      gimp_install_procedure(PLUG_IN_D_NAME,
                             PLUG_IN_DESCRIPTION,
                             PLUG_IN_HELP,
                             PLUG_IN_AUTHOR,
                             PLUG_IN_COPYRIGHT,
                             PLUG_IN_VERSION,
312
                             "TWAIN (Dump)...",
313 314 315 316 317 318 319
                             NULL,
                             GIMP_PLUGIN,
                             NUMBER_IN_ARGS,
                             NUMBER_OUT_ARGS,
                             args,
                             return_vals);

320
      gimp_plugin_menu_register (PLUG_IN_D_NAME, "<Image>/File/Create/Acquire");
321
    }
322
  else if (twain_run_mode == RUN_READDUMP)
323 324 325 326 327 328 329 330
    {
      /* the installation of the plugin */
      gimp_install_procedure(PLUG_IN_R_NAME,
                             PLUG_IN_DESCRIPTION,
                             PLUG_IN_HELP,
                             PLUG_IN_AUTHOR,
                             PLUG_IN_COPYRIGHT,
                             PLUG_IN_VERSION,
331
                             "TWAIN (Read)...",
332 333 334 335 336 337 338
                             NULL,
                             GIMP_PLUGIN,
                             NUMBER_IN_ARGS,
                             NUMBER_OUT_ARGS,
                             args,
                             return_vals);

339
      gimp_plugin_menu_register (PLUG_IN_R_NAME, "<Image>/File/Create/Acquire");
340
    }
341 342
  else
#endif /* _DEBUG */
343 344 345 346 347 348 349 350
    {
      /* the installation of the plugin */
      gimp_install_procedure(PLUG_IN_NAME,
                             PLUG_IN_DESCRIPTION,
                             PLUG_IN_HELP,
                             PLUG_IN_AUTHOR,
                             PLUG_IN_COPYRIGHT,
                             PLUG_IN_VERSION,
351
                             N_("_Scanner/Camera..."),
352 353 354 355 356 357 358
                             NULL,
                             GIMP_PLUGIN,
                             NUMBER_IN_ARGS,
                             NUMBER_OUT_ARGS,
                             args,
                             return_vals);

359
      gimp_plugin_menu_register (PLUG_IN_NAME, "<Image>/File/Create/Acquire");
360
    }
361
}
362 363


364
/* Return values storage */
365
static GimpParam values[3];
366 367 368 369 370 371 372

/*
 * run
 *
 * The plug-in is being requested to run.
 * Capture an image from a TWAIN datasource
 */
373
static void
374 375 376 377 378
run (const gchar      *name,
     gint              nparams,
     const GimpParam  *param,
     gint             *nreturn_vals,
     GimpParam       **return_vals)
379
{
380
  GimpRunMode run_mode = param[0].data.d_int32;
381 382

  /* Initialize the return values
383
   * Always return at least the status to the caller.
384
   */
385 386
  values[0].type = GIMP_PDB_STATUS;
  values[0].data.d_status = GIMP_PDB_SUCCESS;
387 388 389
  *nreturn_vals = 1;
  *return_vals = values;

390 391
  INIT_I18N ();

392 393 394 395 396
  /* Before we get any further, verify that we have
   * TWAIN and that there is actually a datasource
   * to be used in doing the acquire.
   */
  if (!twainIsAvailable()) {
397
    values[0].data.d_status = GIMP_PDB_EXECUTION_ERROR;
398 399 400 401
    return;
  }

  /* Set up the rest of the return parameters */
402
  values[1].type = GIMP_PDB_INT32;
403
  values[1].data.d_int32 = 0;
404
  values[2].type = GIMP_PDB_INT32ARRAY;
405
  values[2].data.d_int32array = g_new (gint32, MAX_IMAGES);
406

407 408
  /* How are we running today? */
  switch (run_mode) {
409
  case GIMP_RUN_INTERACTIVE:
410 411 412 413 414
    /* Retrieve values from the last run...
     * Currently ignored
     */
    gimp_get_data(PLUG_IN_NAME, &twainvals);
    break;
415

416
  case GIMP_RUN_NONINTERACTIVE:
417 418 419
    /* Currently, we don't do non-interactive calls.
     * Bail if someone tries to call us non-interactively
     */
420
    values[0].data.d_status = GIMP_PDB_CALLING_ERROR;
421
    return;
422

423
  case GIMP_RUN_WITH_LAST_VALS:
424 425 426 427 428
    /* Retrieve values from the last run...
     * Currently ignored
     */
    gimp_get_data(PLUG_IN_NAME, &twainvals);
    break;
429

430 431 432
  default:
    break;
  } /* switch */
433

434
  /* Have we succeeded so far? */
435
  if (values[0].data.d_status == GIMP_PDB_SUCCESS)
436
    twainMain ();
437

438 439 440 441 442 443 444 445
  /* Check to make sure we got at least one valid
   * image.
   */
  if (values[1].data.d_int32 > 0) {
    /* An image was captured from the TWAIN
     * datasource.  Do final Interactive
     * steps.
     */
446
    if (run_mode == GIMP_RUN_INTERACTIVE) {
447 448 449
      /* Store variable states for next run */
      gimp_set_data(PLUG_IN_NAME, &twainvals, sizeof (TwainValues));
    }
450

451 452 453
    /* Set return values */
    *nreturn_vals = 3;
  } else {
454
    values[0].data.d_status = GIMP_PDB_EXECUTION_ERROR;
455 456
  }
}
457

458 459 460
/***********************************************************************
 * Image transfer callback functions
 ***********************************************************************/
461

462 463 464 465 466 467
/* Data used to carry data between each of
 * the callback function calls.
 */
typedef struct {
  gint32 image_id;
  gint32 layer_id;
468 469
  GimpPixelRgn pixel_rgn;
  GimpDrawable *drawable;
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
  pTW_PALETTE8 paletteData;
  int totalPixels;
  int completedPixels;
} ClientDataStruct, *pClientDataStruct;

/*
 * preTransferCallback
 *
 * This callback function is called before any images
 * are transferred.  Set up the one time only stuff.
 */
void
preTransferCallback(void *clientData)
{
  /* Initialize our progress dialog */
485
  gimp_progress_init (_("Transferring data from scanner/camera"));
486 487 488 489 490 491 492 493 494 495 496 497 498
}

/*
 * beginTransferCallback
 *
 * The following function is called at the beginning
 * of each image transfer.
 */
int
beginTransferCallback(pTW_IMAGEINFO imageInfo, void *clientData)
{
  int imageType, layerType;

499
  pClientDataStruct theClientData = g_new (ClientDataStruct, 1);
500

501
#ifdef _DEBUG
502 503
  logBegin(imageInfo, clientData);
#endif
504

505 506 507 508 509
  /* Decide on the image type */
  switch (imageInfo->PixelType) {
  case TWPT_BW:
  case TWPT_GRAY:
    /* Set up the image and layer types */
510 511
    imageType = GIMP_GRAY;
    layerType = GIMP_GRAY_IMAGE;
512
    break;
513

514 515
  case TWPT_RGB:
    /* Set up the image and layer types */
516 517
    imageType = GIMP_RGB;
    layerType = GIMP_RGB_IMAGE;
518 519 520 521
    break;

  case TWPT_PALETTE:
    /* Get the palette data */
522
    theClientData->paletteData = g_new (TW_PALETTE8, 1);
523 524 525 526 527 528 529 530 531
    twSession->twRC = callDSM(APP_IDENTITY(twSession), DS_IDENTITY(twSession),
			      DG_IMAGE, DAT_PALETTE8, MSG_GET,
			      (TW_MEMREF) theClientData->paletteData);
    if (twSession->twRC != TWRC_SUCCESS)
      return FALSE;

    switch (theClientData->paletteData->PaletteType) {
    case TWPA_RGB:
      /* Set up the image and layer types */
532 533
      imageType = GIMP_RGB;
      layerType = GIMP_RGB_IMAGE;
534 535 536 537
      break;

    case TWPA_GRAY:
      /* Set up the image and layer types */
538 539
      imageType = GIMP_GRAY;
      layerType = GIMP_GRAY_IMAGE;
540 541 542 543 544 545 546 547 548 549 550 551 552 553
      break;

    default:
      return FALSE;
    }
    break;

  default:
    /* We don't know how to deal with anything other than
     * the types listed above.  Bail for any other image
     * type.
     */
    return FALSE;
  }
554

555
  /* Create the GIMP image */
556
  theClientData->image_id = gimp_image_new(imageInfo->ImageWidth,
557
					   imageInfo->ImageLength, imageType);
558

559 560 561 562 563
  /* Set the actual resolution */
  gimp_image_set_resolution (theClientData->image_id,
                             FIX32ToFloat(imageInfo->XResolution),
                             FIX32ToFloat(imageInfo->YResolution));
  gimp_image_set_unit (theClientData->image_id, GIMP_UNIT_INCH);
564

565 566
  /* Create a layer */
  theClientData->layer_id = gimp_layer_new(theClientData->image_id,
Tor Lillqvist's avatar
Tor Lillqvist committed
567
					   _("Background"),
568
					   imageInfo->ImageWidth,
569
					   imageInfo->ImageLength,
570
					   layerType, 100, GIMP_LAYER_MODE_NORMAL);
571

572
  /* Add the layer to the image */
573 574
  gimp_image_insert_layer(theClientData->image_id,
                          theClientData->layer_id, -1, 0);
575

576 577 578 579
  /* Update the progress dialog */
  theClientData->totalPixels = imageInfo->ImageWidth * imageInfo->ImageLength;
  theClientData->completedPixels = 0;
  gimp_progress_update((double) 0);
580

581 582
  /* Get our drawable */
  theClientData->drawable = gimp_drawable_get(theClientData->layer_id);
583

584
  /* Initialize a pixel region for writing to the image */
585
  gimp_pixel_rgn_init(&(theClientData->pixel_rgn), theClientData->drawable,
586 587
		      0, 0, imageInfo->ImageWidth, imageInfo->ImageLength,
		      TRUE, FALSE);
588

589 590
  /* Store our client data for the data transfer callbacks */
  if (clientData)
591
    g_free (clientData);
592
  setClientData(twSession, (void *) theClientData);
593

594 595 596 597 598
  /* Make sure to return TRUE to continue the image
   * transfer
   */
  return TRUE;
}
599

600 601 602 603 604 605 606 607 608 609 610 611
/*
 * bitTransferCallback
 *
 * The following function is called for each memory
 * block that is transferred from the data source if
 * the image type is Black/White.
 *
 * Black and white data is unpacked from bit data
 * into byte data and written into a gray scale GIMP
 * image.
 */
static char bitMasks[] = { 128, 64, 32, 16, 8, 4, 2, 1 };
612
static int
613 614 615 616 617 618 619 620 621
bitTransferCallback(pTW_IMAGEINFO imageInfo,
		    pTW_IMAGEMEMXFER imageMemXfer,
		    void *clientData)
{
  int row, col, offset;
  char *srcBuf;
  int rows = imageMemXfer->Rows;
  int cols = imageMemXfer->Columns;
  pClientDataStruct theClientData = (pClientDataStruct) clientData;
622

623 624
  /* Allocate a buffer as necessary */
  if (!destBuf)
625
    destBuf = g_new (char, rows * cols);
626

627 628 629 630 631 632 633 634 635
  /* Unpack the image data from bits into bytes */
  srcBuf = (char *) imageMemXfer->Memory.TheMem;
  offset = 0;
  for (row = 0; row < rows; row++) {
    for (col = 0; col < cols; col++) {
      char byte = srcBuf[(row * imageMemXfer->BytesPerRow) + (col / 8)];
      destBuf[offset++] = ((byte & bitMasks[col % 8]) != 0) ? 255 : 0;
    }
  }
636

637
  /* Update the complete chunk */
638
  gimp_pixel_rgn_set_rect(&(theClientData->pixel_rgn),
639 640 641
			  (guchar *) destBuf,
			  imageMemXfer->XOffset, imageMemXfer->YOffset,
			  cols, rows);
642

643 644
  /* Update the user on our progress */
  theClientData->completedPixels += (cols * rows);
645
  gimp_progress_update((double) theClientData->completedPixels /
646
		       (double) theClientData->totalPixels);
647

648 649
  return TRUE;
}
650

651 652 653 654 655 656 657 658
/*
 * oneBytePerSampleTransferCallback
 *
 * The following function is called for each memory
 * block that is transferred from the data source if
 * the image type is Grayscale or RGB.  This transfer
 * mode is quicker than the modes that require translation
 * from a greater number of bits per sample down to the
659
 * 8 bits per sample understood by GIMP.
660
 */
661
static int
662 663 664 665 666 667 668 669 670 671
oneBytePerSampleTransferCallback(pTW_IMAGEINFO imageInfo,
		     pTW_IMAGEMEMXFER imageMemXfer,
		     void *clientData)
{
  int row;
  char *srcBuf;
  int bytesPerPixel = imageInfo->BitsPerPixel / 8;
  int rows = imageMemXfer->Rows;
  int cols = imageMemXfer->Columns;
  pClientDataStruct theClientData = (pClientDataStruct) clientData;
672

673 674
  /* Allocate a buffer as necessary */
  if (!destBuf)
675
    destBuf = g_new (char, rows * cols * bytesPerPixel);
676

677
  /* The bytes coming from the source may not be padded in
678
   * a way that GIMP is terribly happy with.  It is
679 680 681 682
   * possible to transfer row by row, but that is particularly
   * expensive in terms of performance.  It is much cheaper
   * to rearrange the data and transfer it in one large chunk.
   * The next chunk of code rearranges the incoming data into
683
   * a non-padded chunk for GIMP.
684 685 686 687 688 689 690 691
   */
  srcBuf = (char *) imageMemXfer->Memory.TheMem;
  for (row = 0; row < rows; row++) {
    /* Copy the current row */
    memcpy((destBuf + (row * bytesPerPixel * cols)),
	   (srcBuf + (row * imageMemXfer->BytesPerRow)),
	   (bytesPerPixel * cols));
  }
692

693
  /* Update the complete chunk */
694
  gimp_pixel_rgn_set_rect(&(theClientData->pixel_rgn),
695 696 697
			  (guchar *) destBuf,
			  imageMemXfer->XOffset, imageMemXfer->YOffset,
			  cols, rows);
698

699 700
  /* Update the user on our progress */
  theClientData->completedPixels += (cols * rows);
701
  gimp_progress_update((double) theClientData->completedPixels /
702
		       (double) theClientData->totalPixels);
703

704 705
  return TRUE;
}
706

707 708 709 710 711 712
/*
 * twoBytesPerSampleTransferCallback
 *
 * The following function is called for each memory
 * block that is transferred from the data source if
 * the image type is Grayscale or RGB.
713 714
 */
static int
715 716 717 718 719 720
twoBytesPerSampleTransferCallback(pTW_IMAGEINFO imageInfo,
		     pTW_IMAGEMEMXFER imageMemXfer,
		     void *clientData)
{
  static float ratio = 0.00390625;
  int row, col, sample;
721
  char *destByte;
722 723 724 725 726 727
  int rows = imageMemXfer->Rows;
  int cols = imageMemXfer->Columns;

  TW_UINT16 *samplePtr;

  pClientDataStruct theClientData = (pClientDataStruct) clientData;
728

729 730
  /* Allocate a buffer as necessary */
  if (!destBuf)
731
    destBuf = g_new (char, rows * cols * imageInfo->SamplesPerPixel);
732

733
  /* The bytes coming from the source may not be padded in
734
   * a way that GIMP is terribly happy with.  It is
735 736 737 738
   * possible to transfer row by row, but that is particularly
   * expensive in terms of performance.  It is much cheaper
   * to rearrange the data and transfer it in one large chunk.
   * The next chunk of code rearranges the incoming data into
739
   * a non-padded chunk for GIMP.  This function must also
740 741 742 743 744 745
   * reduce from multiple bytes per sample down to single byte
   * per sample.
   */
  /* Work through the rows */
  for (row = 0; row < rows; row++) {
    /* The start of this source row */
746
    samplePtr = (TW_UINT16 *)
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
      ((char *) imageMemXfer->Memory.TheMem + (row * imageMemXfer->BytesPerRow));

    /* The start of this dest row */
    destByte = destBuf + (row * imageInfo->SamplesPerPixel * cols);

    /* Work through the columns */
    for (col = 0; col < cols; col++) {
      /* Finally, work through each of the samples */
      for (sample = 0; sample < imageInfo->SamplesPerPixel; sample++) {
				/* Get the value */
	TW_UINT16 value = *samplePtr;

				/* Move the sample pointer */
	samplePtr++;

				/* Place in the destination */
	*destByte = (char) ((float) value * (float) ratio);
	destByte++;
      }
    }
  }
768

769
  /* Send the complete chunk */
770
  gimp_pixel_rgn_set_rect(&(theClientData->pixel_rgn),
771 772 773
			  (guchar *) destBuf,
			  imageMemXfer->XOffset, imageMemXfer->YOffset,
			  cols, rows);
774

775 776
  /* Update the user on our progress */
  theClientData->completedPixels += (cols * rows);
777
  gimp_progress_update((double) theClientData->completedPixels /
778
		       (double) theClientData->totalPixels);
779

780 781
  return TRUE;
}
782

783 784 785 786 787 788
/*
 * palettedTransferCallback
 *
 * The following function is called for each memory
 * block that is transferred from the data source if
 * the image type is paletted.  This does not create
789
 * an indexed image type in GIMP because for some
790 791 792 793
 * reason it does not allow creation of a specific
 * palette.  This function will create an RGB or Gray
 * image and use the palette to set the details of
 * the pixels.
794 795
 */
static int
796 797 798 799 800 801 802 803 804 805 806 807
palettedTransferCallback(pTW_IMAGEINFO imageInfo,
			 pTW_IMAGEMEMXFER imageMemXfer,
			 void *clientData)
{
  int channelsPerEntry;
  int row, col;
  int rows = imageMemXfer->Rows;
  int cols = imageMemXfer->Columns;
  char *destPtr = NULL, *srcPtr = NULL;

  /* Get the client data */
  pClientDataStruct theClientData = (pClientDataStruct) clientData;
808

809
  /* Look up the palette entry size */
810
  channelsPerEntry =
811 812 813 814
    (theClientData->paletteData->PaletteType == TWPA_RGB) ? 3 : 1;

  /* Allocate a buffer as necessary */
  if (!destBuf)
815
    destBuf = g_new (char, rows * cols * channelsPerEntry);
816 817 818 819

  /* Work through the rows */
  destPtr = destBuf;
  for (row = 0; row < rows; row++) {
820
    srcPtr = (char *) ((char *) imageMemXfer->Memory.TheMem +
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
		       (row * imageMemXfer->BytesPerRow));

    /* Work through the columns */
    for (col = 0; col < cols; col++) {
      /* Get the palette index */
      int index = (unsigned char) *srcPtr;
      srcPtr++;

      switch (theClientData->paletteData->PaletteType) {
      case TWPA_GRAY:
	*destPtr = theClientData->paletteData->Colors[index].Channel1;
	destPtr++;
	break;

      case TWPA_RGB:
	*destPtr = theClientData->paletteData->Colors[index].Channel1;
	destPtr++;
	*destPtr = theClientData->paletteData->Colors[index].Channel2;
	destPtr++;
	*destPtr = theClientData->paletteData->Colors[index].Channel3;
	destPtr++;
      }
    }
  }
845

846
  /* Send the complete chunk */
847
  gimp_pixel_rgn_set_rect(&(theClientData->pixel_rgn),
848 849 850
			  (guchar *) destBuf,
			  imageMemXfer->XOffset, imageMemXfer->YOffset,
			  cols, rows);
851

852 853
  /* Update the user on our progress */
  theClientData->completedPixels += (cols * rows);
854
  gimp_progress_update((double) theClientData->completedPixels /
855
		       (double) theClientData->totalPixels);
856

857 858
  return TRUE;
}
859

860 861 862 863 864 865
/*
 * dataTransferCallback
 *
 * The following function is called for each memory
 * block that is transferred from the data source.
 */
866
int
867 868 869 870 871 872 873
dataTransferCallback(pTW_IMAGEINFO imageInfo,
		     pTW_IMAGEMEMXFER imageMemXfer,
		     void *clientData)
{
#ifdef _DEBUG
  logData(imageInfo, imageMemXfer, clientData);
#endif
874

875 876 877 878 879 880 881
  /* Choose the appropriate transfer handler */
  switch (imageInfo->PixelType) {
  case TWPT_PALETTE:
    return palettedTransferCallback(imageInfo, imageMemXfer, clientData);

  case TWPT_BW:
    return bitTransferCallback(imageInfo, imageMemXfer, clientData);
882

883 884 885 886 887
  case TWPT_GRAY:
  case TWPT_RGB:
    switch (imageInfo->BitsPerPixel / imageInfo->SamplesPerPixel) {
    case 8:
      return oneBytePerSampleTransferCallback(imageInfo, imageMemXfer, clientData);
888

889 890 891 892 893 894
    case 16:
      return twoBytesPerSampleTransferCallback(imageInfo, imageMemXfer, clientData);

    default:
      return FALSE;
    }
895

896 897 898 899
  default:
    return FALSE;
  }
}
900

901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
/*
 * endTransferCallback
 *
 * The following function is called at the end of the
 * image transfer.  The caller will be handed
 * the image transfer completion state.  The
 * following values (defined in twain.h) are
 * possible:
 *
 * TWRC_XFERDONE
 *  The transfer completed successfully
 * TWRC_CANCEL
 *  The transfer was completed by the user
 * TWRC_FAILURE
 *  The transfer failed.
 */
int
endTransferCallback(int completionState, int pendingCount, void *clientData)
{
  pClientDataStruct theClientData = (pClientDataStruct) clientData;
921

922 923 924 925 926
  LogMessage("endTransferCallback: CompState = %d, pending = %d\n",
	     completionState, pendingCount);

  /* Clean up and detach from the drawable */
  if (destBuf) {
927
    g_free (destBuf);
928 929 930 931 932 933 934 935
    destBuf = NULL;
  }
  gimp_drawable_flush(theClientData->drawable);
  gimp_drawable_detach(theClientData->drawable);

  /* Make sure to check our return code */
  if (completionState == TWRC_XFERDONE) {
    /* We have a completed image transfer */
936
    values[2].type = GIMP_PDB_INT32ARRAY;
937 938
    values[2].data.d_int32array[values[1].data.d_int32++] =
      theClientData->image_id;
939

940 941
    /* Display the image */
    LogMessage("Displaying image %d\n", theClientData->image_id);
942
    gimp_display_new (theClientData->image_id);
943 944 945 946 947
  } else {
    /* The transfer did not complete successfully */
    LogMessage("Deleting image\n");
    gimp_image_delete(theClientData->image_id);
  }
948

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
  /* Shut down if we have received all of the possible images */
  return (values[1].data.d_int32 < MAX_IMAGES);
}

/*
 * postTransferCallback
 *
 * This callback function will be called
 * after all possible images have been
 * transferred.
 */
void
postTransferCallback(int pendingCount, void *clientData)
{
  /* Shut things down. */
  if (pendingCount != 0)
    cancelPendingTransfers(twSession);

  /* This will close the datasource and datasource
   * manager.  Then the message queue will be shut
   * down and the run() procedure will finally be
   * able to finish.
   */
  disableDS(twSession);
  closeDS(twSession);
  closeDSM(twSession);
975

976
  /* Post a message to close up the application */
977
  twainQuitApplication ();
978
}