xref: /third_party/backends/backend/p5.c (revision 141cc406)
1/* sane - Scanner Access Now Easy.
2
3   Copyright (C) 2009-12 Stéphane Voltz <stef.dev@free.fr>
4
5   This program is free software; you can redistribute it and/or
6   modify it under the terms of the GNU General Public License as
7   published by the Free Software Foundation; either version 2 of the
8   License, or (at your option) any later version.
9
10   This program is distributed in the hope that it will be useful, but
11   WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <https://www.gnu.org/licenses/>.
17*/
18/*   --------------------------------------------------------------------------
19
20*/
21
22/* ------------------------------------------------------------------------- */
23/*! \mainpage Primax PagePartner Parallel Port scanner Index Page
24 *
25 * \section intro_sec Introduction
26 *
27 * This backend provides support for the Prima PagePartner sheet fed parallel
28 * port scanner.
29 *
30 * \section sane_api SANE API
31 *
32 * \subsection sane_flow sane flow
33   SANE FLOW
34   - sane_init() : initialize backend, attach scanners.
35   	- sane_get_devices() : query list of scanner devices, backend must
36                           	probe for new devices.
37   	- sane_open() : open a particular scanner device, adding a handle
38   		     	to the opened device
39		- sane_set_io_mode() : set blocking mode
40		- sane_get_select_fd() : get scanner fd
41		- sane_get_option_descriptor() : get option information
42		- sane_control_option() : change option values
43		- sane_start() : start image acquisition
44			- sane_get_parameters() : returns actual scan parameters for the ongoing scan
45			- sane_read() : read image data
46		- sane_cancel() : cancel operation, end scan
47   	- sane_close() : close opened scanner device, freeing scanner handle
48   - sane_exit() : terminate use of backend, freeing all resources for attached
49   		   devices when last frontend quits
50 */
51
52/**
53 * the build number allow to know which version of the backend is running.
54 */
55#define BUILD 2301
56
57#include "p5.h"
58
59/**
60 * Import directly the low level part needed to
61 * operate scanner. The alternative is to prefix all public functions
62 * with sanei_p5_ ,and have all the functions prototyped in
63 * p5_device.h .
64 */
65#include "p5_device.c"
66
67/**
68 * number of time the backend has been loaded by sane_init.
69 */
70static int init_count = 0;
71
72/**
73 * NULL terminated list of opened frontend sessions. Sessions are
74 * inserted here on sane_open() and removed on sane_close().
75 */
76static P5_Session *sessions = NULL;
77
78/**
79 * NULL terminated list of detected physical devices.
80 * The same device may be opened several time by different sessions.
81 * Entry are inserted here by the attach() function.
82 * */
83static P5_Device *devices = NULL;
84
85/**
86 * NULL terminated list of devices needed by sane_get_devices(), since
87 * the result returned must stay consistent until next call.
88 */
89static const SANE_Device **devlist = 0;
90
91/**
92 * list of possible color modes
93 */
94static SANE_String_Const mode_list[] = {
95  SANE_I18N (COLOR_MODE),
96  SANE_I18N (GRAY_MODE),
97  /* SANE_I18N (LINEART_MODE), not supported yet */
98  0
99};
100
101static SANE_Range x_range = {
102  SANE_FIX (0.0),		/* minimum */
103  SANE_FIX (216.0),		/* maximum */
104  SANE_FIX (0.0)		/* quantization */
105};
106
107static SANE_Range y_range = {
108  SANE_FIX (0.0),		/* minimum */
109  SANE_FIX (299.0),		/* maximum */
110  SANE_FIX (0.0)		/* no quantization */
111};
112
113/**
114 * finds the maximum string length in a string array.
115 */
116static size_t
117max_string_size (const SANE_String_Const strings[])
118{
119  size_t size, max_size = 0;
120  SANE_Int i;
121
122  for (i = 0; strings[i]; ++i)
123    {
124      size = strlen (strings[i]) + 1;
125      if (size > max_size)
126	max_size = size;
127    }
128  return max_size;
129}
130
131/**> placeholders for decoded configuration values */
132static P5_Config p5cfg;
133
134
135/* ------------------------------------------------------------------------- */
136
137/*
138 * SANE Interface
139 */
140
141
142/**
143 * Called by SANE initially.
144 *
145 * From the SANE spec:
146 * This function must be called before any other SANE function can be
147 * called. The behavior of a SANE backend is undefined if this
148 * function is not called first. The version code of the backend is
149 * returned in the value pointed to by version_code. If that pointer
150 * is NULL, no version code is returned. Argument authorize is either
151 * a pointer to a function that is invoked when the backend requires
152 * authentication for a specific resource or NULL if the frontend does
153 * not support authentication.
154 */
155SANE_Status
156sane_init (SANE_Int * version_code, SANE_Auth_Callback authorize)
157{
158  SANE_Status status;
159
160  (void) authorize;		/* get rid of compiler warning */
161
162  init_count++;
163
164  /* init backend debug */
165  DBG_INIT ();
166  DBG (DBG_info, "SANE P5 backend version %d.%d-%d\n",
167       SANE_CURRENT_MAJOR, SANE_CURRENT_MINOR, BUILD);
168  DBG (DBG_proc, "sane_init: start\n");
169  DBG (DBG_trace, "sane_init: init_count=%d\n", init_count);
170
171  if (version_code)
172    *version_code = SANE_VERSION_CODE (SANE_CURRENT_MAJOR, SANE_CURRENT_MINOR, BUILD);
173
174  /* cold-plugging case : probe for already plugged devices */
175  status = probe_p5_devices ();
176
177  DBG (DBG_proc, "sane_init: exit\n");
178  return status;
179}
180
181
182/**
183 * Called by SANE to find out about supported devices.
184 *
185 * From the SANE spec:
186 * This function can be used to query the list of devices that are
187 * available. If the function executes successfully, it stores a
188 * pointer to a NULL terminated array of pointers to SANE_Device
189 * structures in *device_list. The returned list is guaranteed to
190 * remain unchanged and valid until (a) another call to this function
191 * is performed or (b) a call to sane_exit() is performed. This
192 * function can be called repeatedly to detect when new devices become
193 * available. If argument local_only is true, only local devices are
194 * returned (devices directly attached to the machine that SANE is
195 * running on). If it is false, the device list includes all remote
196 * devices that are accessible to the SANE library.
197 *
198 * SANE does not require that this function is called before a
199 * sane_open() call is performed. A device name may be specified
200 * explicitly by a user which would make it unnecessary and
201 * undesirable to call this function first.
202 * @param device_list pointer where to store the device list
203 * @param local_only SANE_TRUE if only local devices are required.
204 * @return SANE_STATUS_GOOD when successful
205 */
206SANE_Status
207sane_get_devices (const SANE_Device *** device_list, SANE_Bool local_only)
208{
209  int dev_num, devnr;
210  struct P5_Device *device;
211  SANE_Device *sane_device;
212  int i;
213
214  DBG (DBG_proc, "sane_get_devices: start: local_only = %s\n",
215       local_only == SANE_TRUE ? "true" : "false");
216
217  /* free existing devlist first */
218  if (devlist)
219    {
220      for (i = 0; devlist[i] != NULL; i++)
221	free ((void *)devlist[i]);
222      free (devlist);
223      devlist = NULL;
224    }
225
226  /**
227   * Since sane_get_devices() may be called repeatedly to detect new devices,
228   * the device detection must be run at each call. We are handling
229   * hot-plugging : we probe for devices plugged since sane_init() was called.
230   */
231  probe_p5_devices ();
232
233  /* if no devices detected, just return an empty list */
234  if (devices == NULL)
235    {
236      devlist = malloc (sizeof (devlist[0]));
237      if (!devlist)
238	return SANE_STATUS_NO_MEM;
239      devlist[0] = NULL;
240      *device_list = devlist;
241      DBG (DBG_proc, "sane_get_devices: exit with no device\n");
242      return SANE_STATUS_GOOD;
243    }
244
245  /* count physical devices */
246  devnr = 1;
247  device = devices;
248  while (device->next)
249    {
250      devnr++;
251      device = device->next;
252    }
253
254  /* allocate room for the list, plus 1 for the NULL terminator */
255  devlist = malloc ((devnr + 1) * sizeof (devlist[0]));
256  if (!devlist)
257    return SANE_STATUS_NO_MEM;
258
259  *device_list = devlist;
260
261  dev_num = 0;
262  device = devices;
263
264  /* we build a list of SANE_Device from the list of attached devices */
265  for (i = 0; i < devnr; i++)
266    {
267      /* add device according to local only flag */
268      if ((local_only == SANE_TRUE && device->local == SANE_TRUE)
269	  || local_only == SANE_FALSE)
270	{
271	  /* allocate memory to add the device */
272	  sane_device = malloc (sizeof (*sane_device));
273	  if (!sane_device)
274	    {
275	      return SANE_STATUS_NO_MEM;
276	    }
277
278	  /* copy data */
279	  sane_device->name = device->name;
280	  sane_device->vendor = device->model->vendor;
281	  sane_device->model = device->model->product;
282	  sane_device->type = device->model->type;
283	  devlist[dev_num] = sane_device;
284
285	  /* increment device counter */
286	  dev_num++;
287	}
288
289      /* go to next detected device */
290      device = device->next;
291    }
292  devlist[dev_num] = 0;
293
294  *device_list = devlist;
295
296  DBG (DBG_proc, "sane_get_devices: exit\n");
297
298  return SANE_STATUS_GOOD;
299}
300
301
302/**
303 * Called to establish connection with the session. This function will
304 * also establish meaningful defaults and initialize the options.
305 *
306 * From the SANE spec:
307 * This function is used to establish a connection to a particular
308 * device. The name of the device to be opened is passed in argument
309 * name. If the call completes successfully, a handle for the device
310 * is returned in *h. As a special case, specifying a zero-length
311 * string as the device requests opening the first available device
312 * (if there is such a device). Another special case is to only give
313 * the name of the backend as the device name, in this case the first
314 * available device will also be used.
315 * @param name name of the device to open
316 * @param handle opaque pointer where to store the pointer of
317 *        the opened P5_Session
318 * @return SANE_STATUS_GOOD on success
319 */
320SANE_Status
321sane_open (SANE_String_Const name, SANE_Handle * handle)
322{
323  struct P5_Session *session = NULL;
324  struct P5_Device *device = NULL;
325
326  DBG (DBG_proc, "sane_open: start (devicename=%s)\n", name);
327
328  /* check there is at least a device */
329  if (devices == NULL)
330    {
331      DBG (DBG_proc, "sane_open: exit, no device to open!\n");
332      return SANE_STATUS_INVAL;
333    }
334
335  if (name[0] == 0 || strncmp (name, "p5", strlen ("p5")) == 0)
336    {
337      DBG (DBG_info,
338	   "sane_open: no specific device requested, using default\n");
339      if (devices)
340	{
341	  device = devices;
342	  DBG (DBG_info, "sane_open: device %s used as default device\n",
343	       device->name);
344	}
345    }
346  else
347    {
348      DBG (DBG_info, "sane_open: device %s requested\n", name);
349      /* walk the device list until we find a matching name */
350      device = devices;
351      while (device && strcmp (device->name, name) != 0)
352	{
353	  DBG (DBG_trace, "sane_open: device %s doesn't match\n",
354	       device->name);
355	  device = device->next;
356	}
357    }
358
359  /* check whether we have found a match or reach the end of the device list */
360  if (!device)
361    {
362      DBG (DBG_info, "sane_open: no device found\n");
363      return SANE_STATUS_INVAL;
364    }
365
366  /* now we have a device, duplicate it and return it in handle */
367  DBG (DBG_info, "sane_open: device %s found\n", name);
368
369  /* device initialization */
370  if (device->initialized == SANE_FALSE)
371    {
372      /**
373       * call to hardware initialization function here.
374       */
375      device->fd = open_pp (device->name);
376      if (device->fd < 0)
377	{
378	  DBG (DBG_error, "sane_open: failed to open '%s' device!\n",
379	       device->name);
380	  return SANE_STATUS_INVAL;
381	}
382
383      /* now try to connect to scanner */
384      if (connect (device->fd) != SANE_TRUE)
385	{
386	  DBG (DBG_error, "sane_open: failed to connect!\n");
387	  close_pp (device->fd);
388	  return SANE_STATUS_INVAL;
389	}
390
391      /* load calibration data */
392      restore_calibration (device);
393
394      /* device link is OK now */
395      device->initialized = SANE_TRUE;
396    }
397  device->buffer = NULL;
398  device->gain = NULL;
399  device->offset = NULL;
400
401  /* prepare handle to return */
402  session = (P5_Session *) malloc (sizeof (P5_Session));
403  if (session == NULL)
404    {
405      DBG (DBG_proc, "sane_open: exit OOM\n");
406      return SANE_STATUS_NO_MEM;
407    }
408
409  /* initialize session */
410  session->dev = device;
411  session->scanning = SANE_FALSE;
412  session->non_blocking = SANE_FALSE;
413
414  /* initialize SANE options for this session */
415  init_options (session);
416
417  /* add the handle to the linked list of sessions */
418  session->next = sessions;
419  sessions = session;
420
421  /* store result */
422  *handle = session;
423
424  /* exit success */
425  DBG (DBG_proc, "sane_open: exit\n");
426  return SANE_STATUS_GOOD;
427}
428
429
430/**
431 * Set non blocking mode. In this mode, read return immediately when
432 * no data is available within sane_read(), instead of polling the scanner.
433 */
434SANE_Status
435sane_set_io_mode (SANE_Handle handle, SANE_Bool non_blocking)
436{
437  P5_Session *session = (P5_Session *) handle;
438
439  DBG (DBG_proc, "sane_set_io_mode: start\n");
440  if (session->scanning != SANE_TRUE)
441    {
442      DBG (DBG_error, "sane_set_io_mode: called out of a scan\n");
443      return SANE_STATUS_INVAL;
444    }
445  session->non_blocking = non_blocking;
446  DBG (DBG_info, "sane_set_io_mode: I/O mode set to %sblocking.\n",
447       non_blocking ? "non " : " ");
448  DBG (DBG_proc, "sane_set_io_mode: exit\n");
449  return SANE_STATUS_GOOD;
450}
451
452
453/**
454 * An advanced method we don't support but have to define. At SANE API
455 * level this function is meant to provide a file descriptor on which the
456 * frontend can do select()/poll() to wait for data.
457 */
458SANE_Status
459sane_get_select_fd (SANE_Handle handle, SANE_Int * fdp)
460{
461  /* make compiler happy ... */
462  (void) handle;
463  (void) fdp;
464
465  DBG (DBG_proc, "sane_get_select_fd: start\n");
466  DBG (DBG_warn, "sane_get_select_fd: unsupported ...\n");
467  DBG (DBG_proc, "sane_get_select_fd: exit\n");
468  return SANE_STATUS_UNSUPPORTED;
469}
470
471
472/**
473 * Returns the options we know.
474 *
475 * From the SANE spec:
476 * This function is used to access option descriptors. The function
477 * returns the option descriptor for option number n of the device
478 * represented by handle h. Option number 0 is guaranteed to be a
479 * valid option. Its value is an integer that specifies the number of
480 * options that are available for device handle h (the count includes
481 * option 0). If n is not a valid option index, the function returns
482 * NULL. The returned option descriptor is guaranteed to remain valid
483 * (and at the returned address) until the device is closed.
484 */
485const SANE_Option_Descriptor *
486sane_get_option_descriptor (SANE_Handle handle, SANE_Int option)
487{
488  struct P5_Session *session = handle;
489
490  DBG (DBG_proc, "sane_get_option_descriptor: start\n");
491
492  if ((unsigned) option >= NUM_OPTIONS)
493    return NULL;
494
495  DBG (DBG_info, "sane_get_option_descriptor: \"%s\"\n",
496       session->options[option].descriptor.name);
497
498  DBG (DBG_proc, "sane_get_option_descriptor: exit\n");
499  return &(session->options[option].descriptor);
500}
501
502/**
503 * sets automatic value for an option , called by sane_control_option after
504 * all checks have been done */
505static SANE_Status
506set_automatic_value (P5_Session * s, int option, SANE_Int * myinfo)
507{
508  SANE_Status status = SANE_STATUS_GOOD;
509  SANE_Int i, min;
510  SANE_Word *dpi_list;
511
512  switch (option)
513    {
514    case OPT_TL_X:
515      s->options[OPT_TL_X].value.w = x_range.min;
516      *myinfo |= SANE_INFO_RELOAD_PARAMS;
517      break;
518    case OPT_TL_Y:
519      s->options[OPT_TL_Y].value.w = y_range.min;
520      *myinfo |= SANE_INFO_RELOAD_PARAMS;
521      break;
522    case OPT_BR_X:
523      s->options[OPT_BR_X].value.w = x_range.max;
524      *myinfo |= SANE_INFO_RELOAD_PARAMS;
525      break;
526    case OPT_BR_Y:
527      s->options[OPT_BR_Y].value.w = y_range.max;
528      *myinfo |= SANE_INFO_RELOAD_PARAMS;
529      break;
530    case OPT_RESOLUTION:
531      /* we set up to the lowest available dpi value */
532      dpi_list =
533	(SANE_Word *) s->options[OPT_RESOLUTION].descriptor.constraint.
534	word_list;
535      min = 65536;
536      for (i = 1; i < dpi_list[0]; i++)
537	{
538	  if (dpi_list[i] < min)
539	    min = dpi_list[i];
540	}
541      s->options[OPT_RESOLUTION].value.w = min;
542      *myinfo |= SANE_INFO_RELOAD_PARAMS;
543      break;
544    case OPT_PREVIEW:
545      s->options[OPT_PREVIEW].value.w = SANE_FALSE;
546      *myinfo |= SANE_INFO_RELOAD_PARAMS;
547      break;
548    case OPT_MODE:
549      if (s->options[OPT_MODE].value.s)
550	free (s->options[OPT_MODE].value.s);
551      s->options[OPT_MODE].value.s = strdup (mode_list[0]);
552      *myinfo |= SANE_INFO_RELOAD_OPTIONS;
553      *myinfo |= SANE_INFO_RELOAD_PARAMS;
554      break;
555    default:
556      DBG (DBG_warn, "set_automatic_value: can't set unknown option %d\n",
557	   option);
558    }
559
560  return status;
561}
562
563/**
564 * sets an option , called by sane_control_option after all
565 * checks have been done */
566static SANE_Status
567set_option_value (P5_Session * s, int option, void *val, SANE_Int * myinfo)
568{
569  SANE_Status status = SANE_STATUS_GOOD;
570  SANE_Word tmpw;
571
572  switch (option)
573    {
574    case OPT_TL_X:
575    case OPT_BR_X:
576    case OPT_TL_Y:
577    case OPT_BR_Y:
578      s->options[option].value.w = *(SANE_Word *) val;
579      /* we ensure geometry is coherent */
580      /* this happens when user drags TL corner right or below the BR point */
581      if (s->options[OPT_BR_Y].value.w < s->options[OPT_TL_Y].value.w)
582	{
583	  tmpw = s->options[OPT_BR_Y].value.w;
584	  s->options[OPT_BR_Y].value.w = s->options[OPT_TL_Y].value.w;
585	  s->options[OPT_TL_Y].value.w = tmpw;
586	}
587      if (s->options[OPT_BR_X].value.w < s->options[OPT_TL_X].value.w)
588	{
589	  tmpw = s->options[OPT_BR_X].value.w;
590	  s->options[OPT_BR_X].value.w = s->options[OPT_TL_X].value.w;
591	  s->options[OPT_TL_X].value.w = tmpw;
592	}
593
594      *myinfo |= SANE_INFO_RELOAD_PARAMS;
595      break;
596
597    case OPT_RESOLUTION:
598    case OPT_PREVIEW:
599      s->options[option].value.w = *(SANE_Word *) val;
600      *myinfo |= SANE_INFO_RELOAD_PARAMS;
601      break;
602
603    case OPT_MODE:
604      if (s->options[option].value.s)
605	free (s->options[option].value.s);
606      s->options[option].value.s = strdup (val);
607      *myinfo |= SANE_INFO_RELOAD_PARAMS | SANE_INFO_RELOAD_OPTIONS;
608      break;
609
610    case OPT_CALIBRATE:
611      status = sheetfed_calibration (s->dev);
612      *myinfo |= SANE_INFO_RELOAD_OPTIONS;
613      break;
614
615    case OPT_CLEAR_CALIBRATION:
616      cleanup_calibration (s->dev);
617      *myinfo |= SANE_INFO_RELOAD_OPTIONS;
618      break;
619
620    default:
621      DBG (DBG_warn, "set_option_value: can't set unknown option %d\n",
622	   option);
623    }
624  return status;
625}
626
627/**
628 * gets an option , called by sane_control_option after all checks
629 * have been done */
630static SANE_Status
631get_option_value (P5_Session * s, int option, void *val)
632{
633  SANE_Status status;
634
635  switch (option)
636    {
637      /* word or word equivalent options: */
638    case OPT_NUM_OPTS:
639    case OPT_RESOLUTION:
640    case OPT_PREVIEW:
641    case OPT_TL_X:
642    case OPT_TL_Y:
643    case OPT_BR_X:
644    case OPT_BR_Y:
645      *(SANE_Word *) val = s->options[option].value.w;
646      break;
647
648      /* string options: */
649    case OPT_MODE:
650      strcpy (val, s->options[option].value.s);
651      break;
652
653      /* sensor options */
654    case OPT_PAGE_LOADED_SW:
655      status = test_document (s->dev->fd);
656      if (status == SANE_STATUS_GOOD)
657	s->options[option].value.b = SANE_TRUE;
658      else
659	s->options[option].value.b = SANE_FALSE;
660      *(SANE_Bool *) val = s->options[option].value.b;
661      break;
662
663    case OPT_NEED_CALIBRATION_SW:
664      *(SANE_Bool *) val = !s->dev->calibrated;
665      break;
666
667
668      /* unhandled options */
669    default:
670      DBG (DBG_warn, "get_option_value: can't get unknown option %d\n",
671	   option);
672    }
673
674  return SANE_STATUS_GOOD;
675}
676
677/**
678 * Gets or sets an option value.
679 *
680 * From the SANE spec:
681 * This function is used to set or inquire the current value of option
682 * number n of the device represented by handle h. The manner in which
683 * the option is controlled is specified by parameter action. The
684 * possible values of this parameter are described in more detail
685 * below.  The value of the option is passed through argument val. It
686 * is a pointer to the memory that holds the option value. The memory
687 * area pointed to by v must be big enough to hold the entire option
688 * value (determined by member size in the corresponding option
689 * descriptor).
690 *
691 * The only exception to this rule is that when setting the value of a
692 * string option, the string pointed to by argument v may be shorter
693 * since the backend will stop reading the option value upon
694 * encountering the first NUL terminator in the string. If argument i
695 * is not NULL, the value of *i will be set to provide details on how
696 * well the request has been met.
697 * action is SANE_ACTION_GET_VALUE, SANE_ACTION_SET_VALUE or SANE_ACTION_SET_AUTO
698 */
699SANE_Status
700sane_control_option (SANE_Handle handle, SANE_Int option,
701		     SANE_Action action, void *val, SANE_Int * info)
702{
703  P5_Session *s = handle;
704  SANE_Status status;
705  SANE_Word cap;
706  SANE_Int myinfo = 0;
707
708  DBG (DBG_io2,
709       "sane_control_option: start: action = %s, option = %s (%d)\n",
710       (action == SANE_ACTION_GET_VALUE) ? "get" : (action ==
711						    SANE_ACTION_SET_VALUE) ?
712       "set" : (action == SANE_ACTION_SET_AUTO) ? "set_auto" : "unknown",
713       s->options[option].descriptor.name, option);
714
715  if (info)
716    *info = 0;
717
718  /* do checks before trying to apply action */
719
720  if (s->scanning)
721    {
722      DBG (DBG_warn, "sane_control_option: don't call this function while "
723	   "scanning (option = %s (%d))\n",
724	   s->options[option].descriptor.name, option);
725      return SANE_STATUS_DEVICE_BUSY;
726    }
727
728  /* option must be within existing range */
729  if (option >= NUM_OPTIONS || option < 0)
730    {
731      DBG (DBG_warn,
732	   "sane_control_option: option %d >= NUM_OPTIONS || option < 0\n",
733	   option);
734      return SANE_STATUS_INVAL;
735    }
736
737  /* don't access an inactive option */
738  cap = s->options[option].descriptor.cap;
739  if (!SANE_OPTION_IS_ACTIVE (cap))
740    {
741      DBG (DBG_warn, "sane_control_option: option %d is inactive\n", option);
742      return SANE_STATUS_INVAL;
743    }
744
745  /* now checks have been done, apply action */
746  switch (action)
747    {
748    case SANE_ACTION_GET_VALUE:
749      status = get_option_value (s, option, val);
750      break;
751
752    case SANE_ACTION_SET_VALUE:
753      if (!SANE_OPTION_IS_SETTABLE (cap))
754	{
755	  DBG (DBG_warn, "sane_control_option: option %d is not settable\n",
756	       option);
757	  return SANE_STATUS_INVAL;
758	}
759
760      status =
761	sanei_constrain_value (&s->options[option].descriptor, val, &myinfo);
762      if (status != SANE_STATUS_GOOD)
763	{
764	  DBG (DBG_warn,
765	       "sane_control_option: sanei_constrain_value returned %s\n",
766	       sane_strstatus (status));
767	  return status;
768	}
769
770      /* return immediately if no change */
771      if (s->options[option].descriptor.type == SANE_TYPE_INT
772	  && *(SANE_Word *) val == s->options[option].value.w)
773	{
774	  status = SANE_STATUS_GOOD;
775	}
776      else
777	{			/* apply change */
778	  status = set_option_value (s, option, val, &myinfo);
779	}
780      break;
781
782    case SANE_ACTION_SET_AUTO:
783      /* sets automatic values */
784      if (!(cap & SANE_CAP_AUTOMATIC))
785	{
786	  DBG (DBG_warn,
787	       "sane_control_option: option %d is not autosettable\n",
788	       option);
789	  return SANE_STATUS_INVAL;
790	}
791
792      status = set_automatic_value (s, option, &myinfo);
793      break;
794
795    default:
796      DBG (DBG_error, "sane_control_option: invalid action %d\n", action);
797      status = SANE_STATUS_INVAL;
798      break;
799    }
800
801  if (info)
802    *info = myinfo;
803
804  DBG (DBG_io2, "sane_control_option: exit\n");
805  return status;
806}
807
808/**
809 * Called by SANE when a page acquisition operation is to be started.
810 * @param handle opaque handle to a frontend session
811 * @return SANE_STATUS_GOOD on success, SANE_STATUS_BUSY if the device is
812 * in use by another session or SANE_STATUS_WARMING_UP if the device is
813 * warming up. In this case the fronted as to call sane_start again until
814 * warming up is done. Any other values returned are error status.
815 */
816SANE_Status
817sane_start (SANE_Handle handle)
818{
819  struct P5_Session *session = handle;
820  int status = SANE_STATUS_GOOD;
821  P5_Device *dev = session->dev;
822
823  DBG (DBG_proc, "sane_start: start\n");
824
825  /* if already scanning, tell we're busy */
826  if (session->scanning == SANE_TRUE)
827    {
828      DBG (DBG_info, "sane_start: device is already scanning\n");
829      return SANE_STATUS_DEVICE_BUSY;
830    }
831
832  /* check that the device has been initialized */
833  if (dev->initialized == SANE_FALSE)
834    {
835      DBG (DBG_error, "sane_start: device is not initialized\n");
836      return SANE_STATUS_INVAL;
837    }
838
839  /* check if there is a document */
840  status = test_document (dev->fd);
841  if (status != SANE_STATUS_GOOD)
842    {
843      DBG (DBG_error, "sane_start: device is already scanning\n");
844      return status;
845    }
846
847  /* we compute all the scan parameters so that */
848  /* we will be able to set up the registers correctly */
849  compute_parameters (session);
850
851  /* move to scan area if needed */
852  if (dev->ystart > 0)
853    {
854      status = move (dev);
855      if (status != SANE_STATUS_GOOD)
856	{
857	  DBG (DBG_error, "sane_start: failed to move to scan area\n");
858	  return SANE_STATUS_INVAL;
859	}
860    }
861
862  /* send scan command */
863  status = start_scan (dev, dev->mode, dev->ydpi, dev->xstart, dev->pixels);
864  if (status != SANE_STATUS_GOOD)
865    {
866      DBG (DBG_error, "sane_start: failed to start scan\n");
867      return SANE_STATUS_INVAL;
868    }
869
870  /* allocates work buffer */
871  if (dev->buffer != NULL)
872    {
873      free (dev->buffer);
874    }
875
876  dev->position = 0;
877  dev->top = 0;
878  /* compute amount of lines needed for lds correction */
879  dev->bottom = dev->bytes_per_line * 2 * dev->lds;
880  /* computes buffer size, 66 color lines plus eventual amount needed for lds */
881  dev->size = dev->pixels * 3 * 66 + dev->bottom;
882  dev->buffer = (uint8_t *) malloc (dev->size);
883  if (dev->buffer == NULL)
884    {
885      DBG (DBG_error, "sane_start: failed to allocate %lu bytes\n", (unsigned long)dev->size);
886      sane_cancel (handle);
887      return SANE_STATUS_NO_MEM;
888    }
889
890  /* return now the scan has been initiated */
891  session->scanning = SANE_TRUE;
892  session->sent = 0;
893
894  DBG (DBG_io, "sane_start: to_send=%d\n", session->to_send);
895  DBG (DBG_io, "sane_start: size=%lu\n", (unsigned long)dev->size);
896  DBG (DBG_io, "sane_start: top=%lu\n", (unsigned long)dev->top);
897  DBG (DBG_io, "sane_start: bottom=%lu\n", (unsigned long)dev->bottom);
898  DBG (DBG_io, "sane_start: position=%lu\n", (unsigned long)dev->position);
899
900  DBG (DBG_proc, "sane_start: exit\n");
901  return status;
902}
903
904/** @brief compute scan parameters
905 * This function computes two set of parameters. The one for the SANE's standard
906 * and the other for the hardware. Among these parameters are the bit depth, total
907 * number of lines, total number of columns, extra line to read for data reordering...
908 * @param session fronted session to compute final scan parameters
909 * @return SANE_STATUS_GOOD on success
910 */
911static SANE_Status
912compute_parameters (P5_Session * session)
913{
914  P5_Device *dev = session->dev;
915  SANE_Int dpi;			/* dpi for scan */
916  SANE_String mode;
917  SANE_Status status = SANE_STATUS_GOOD;
918
919  int tl_x, tl_y, br_x, br_y;
920
921  mode = session->options[OPT_MODE].value.s;
922  dpi = session->options[OPT_RESOLUTION].value.w;
923
924  /* scan coordinates */
925  tl_x = SANE_UNFIX (session->options[OPT_TL_X].value.w);
926  tl_y = SANE_UNFIX (session->options[OPT_TL_Y].value.w);
927  br_x = SANE_UNFIX (session->options[OPT_BR_X].value.w);
928  br_y = SANE_UNFIX (session->options[OPT_BR_Y].value.w);
929
930  /* only single pass scanning supported */
931  session->params.last_frame = SANE_TRUE;
932
933  /* gray modes */
934  if (strcmp (mode, GRAY_MODE) == 0)
935    {
936      session->params.format = SANE_FRAME_GRAY;
937      dev->mode = MODE_GRAY;
938      dev->lds = 0;
939    }
940  else if (strcmp (mode, LINEART_MODE) == 0)
941    {
942      session->params.format = SANE_FRAME_GRAY;
943      dev->mode = MODE_LINEART;
944      dev->lds = 0;
945    }
946  else
947    {
948      /* Color */
949      session->params.format = SANE_FRAME_RGB;
950      dev->mode = MODE_COLOR;
951      dev->lds = (dev->model->lds * dpi) / dev->model->max_ydpi;
952    }
953
954  /* SANE level values */
955  session->params.lines = ((br_y - tl_y) * dpi) / MM_PER_INCH;
956  if (session->params.lines == 0)
957    session->params.lines = 1;
958  session->params.pixels_per_line = ((br_x - tl_x) * dpi) / MM_PER_INCH;
959  if (session->params.pixels_per_line == 0)
960    session->params.pixels_per_line = 1;
961
962  DBG (DBG_data, "compute_parameters: pixels_per_line   =%d\n",
963       session->params.pixels_per_line);
964
965  if (strcmp (mode, LINEART_MODE) == 0)
966    {
967      session->params.depth = 1;
968      /* in lineart, having pixels multiple of 8 avoids a costly test */
969      /* at each bit to see we must go to the next byte               */
970      /* TODO : implement this requirement in sane_control_option */
971      session->params.pixels_per_line =
972	((session->params.pixels_per_line + 7) / 8) * 8;
973    }
974  else
975    session->params.depth = 8;
976
977  /* width needs to be even */
978  if (session->params.pixels_per_line & 1)
979    session->params.pixels_per_line++;
980
981  /* Hardware settings : they can differ from the ones at SANE level */
982  /* for instance the effective DPI used by a sensor may be higher   */
983  /* than the one needed for the SANE scan parameters                */
984  dev->lines = session->params.lines;
985  dev->pixels = session->params.pixels_per_line;
986
987  /* motor and sensor DPI */
988  dev->xdpi = dpi;
989  dev->ydpi = dpi;
990
991  /* handle bounds of motor's dpi range */
992  if (dev->ydpi > dev->model->max_ydpi)
993    {
994      dev->ydpi = dev->model->max_ydpi;
995      dev->lines = (dev->lines * dev->model->max_ydpi) / dpi;
996      if (dev->lines == 0)
997	dev->lines = 1;
998
999      /* round number of lines */
1000      session->params.lines =
1001	(session->params.lines / dev->lines) * dev->lines;
1002      if (session->params.lines == 0)
1003	session->params.lines = 1;
1004    }
1005  if (dev->ydpi < dev->model->min_ydpi)
1006    {
1007      dev->ydpi = dev->model->min_ydpi;
1008      dev->lines = (dev->lines * dev->model->min_ydpi) / dpi;
1009    }
1010
1011  /* hardware values */
1012  dev->xstart =
1013    ((SANE_UNFIX (dev->model->x_offset) + tl_x) * dpi) / MM_PER_INCH;
1014  dev->ystart =
1015    ((SANE_UNFIX (dev->model->y_offset) + tl_y) * dev->ydpi) / MM_PER_INCH;
1016
1017  /* take lds correction into account when moving to scan area */
1018  if (dev->ystart > 2 * dev->lds)
1019    dev->ystart -= 2 * dev->lds;
1020
1021
1022  /* computes bytes per line */
1023  session->params.bytes_per_line = session->params.pixels_per_line;
1024  dev->bytes_per_line = dev->pixels;
1025  if (session->params.format == SANE_FRAME_RGB)
1026    {
1027      dev->bytes_per_line *= 3;
1028    }
1029
1030  /* in lineart mode we adjust bytes_per_line needed by frontend */
1031  /* we do that here because we needed sent/to_send to be as if  */
1032  /* there was no lineart                                        */
1033  if (session->params.depth == 1)
1034    {
1035      session->params.bytes_per_line =
1036	(session->params.bytes_per_line + 7) / 8;
1037    }
1038
1039  session->params.bytes_per_line = dev->bytes_per_line;
1040  session->to_send = session->params.bytes_per_line * session->params.lines;
1041  session->params.bytes_per_line = dev->bytes_per_line;
1042
1043  DBG (DBG_data, "compute_parameters: bytes_per_line    =%d\n",
1044       session->params.bytes_per_line);
1045  DBG (DBG_data, "compute_parameters: depth             =%d\n",
1046       session->params.depth);
1047  DBG (DBG_data, "compute_parameters: lines             =%d\n",
1048       session->params.lines);
1049  DBG (DBG_data, "compute_parameters: image size        =%d\n",
1050       session->to_send);
1051
1052  DBG (DBG_data, "compute_parameters: xstart            =%d\n", dev->xstart);
1053  DBG (DBG_data, "compute_parameters: ystart            =%d\n", dev->ystart);
1054  DBG (DBG_data, "compute_parameters: dev lines         =%d\n", dev->lines);
1055  DBG (DBG_data, "compute_parameters: dev bytes per line=%d\n",
1056       dev->bytes_per_line);
1057  DBG (DBG_data, "compute_parameters: dev pixels        =%d\n", dev->pixels);
1058  DBG (DBG_data, "compute_parameters: lds               =%d\n", dev->lds);
1059
1060  return status;
1061}
1062
1063
1064/**
1065 * Called by SANE to retrieve information about the type of data
1066 * that the current scan will return.
1067 *
1068 * From the SANE spec:
1069 * This function is used to obtain the current scan parameters. The
1070 * returned parameters are guaranteed to be accurate between the time
1071 * a scan has been started (sane_start() has been called) and the
1072 * completion of that request. Outside of that window, the returned
1073 * values are best-effort estimates of what the parameters will be
1074 * when sane_start() gets invoked.
1075 *
1076 * Calling this function before a scan has actually started allows,
1077 * for example, to get an estimate of how big the scanned image will
1078 * be. The parameters passed to this function are the handle of the
1079 * device for which the parameters should be obtained and a pointer
1080 * to a parameter structure.
1081 */
1082SANE_Status
1083sane_get_parameters (SANE_Handle handle, SANE_Parameters * params)
1084{
1085  SANE_Status status;
1086  struct P5_Session *session = (struct P5_Session *) handle;
1087
1088  DBG (DBG_proc, "sane_get_parameters: start\n");
1089
1090  /* call parameters computing function */
1091  status = compute_parameters (session);
1092  if (status == SANE_STATUS_GOOD && params)
1093    *params = session->params;
1094
1095  DBG (DBG_proc, "sane_get_parameters: exit\n");
1096  return status;
1097}
1098
1099
1100/**
1101 * Called by SANE to read data.
1102 *
1103 * From the SANE spec:
1104 * This function is used to read image data from the device
1105 * represented by handle h.  Argument buf is a pointer to a memory
1106 * area that is at least maxlen bytes long.  The number of bytes
1107 * returned is stored in *len. A backend must set this to zero when
1108 * the call fails (i.e., when a status other than SANE_STATUS_GOOD is
1109 * returned).
1110 *
1111 * When the call succeeds, the number of bytes returned can be
1112 * anywhere in the range from 0 to maxlen bytes.
1113 *
1114 * Returned data is read from working buffer.
1115 */
1116SANE_Status
1117sane_read (SANE_Handle handle, SANE_Byte * buf,
1118	   SANE_Int max_len, SANE_Int * len)
1119{
1120  struct P5_Session *session = (struct P5_Session *) handle;
1121  struct P5_Device *dev = session->dev;
1122  SANE_Status status = SANE_STATUS_GOOD;
1123  int count;
1124  int size, lines;
1125  SANE_Bool x2;
1126  SANE_Int i;
1127
1128  DBG (DBG_proc, "sane_read: start\n");
1129  DBG (DBG_io, "sane_read: up to %d bytes required by frontend\n", max_len);
1130
1131  /* some sanity checks first to protect from would be buggy frontends */
1132  if (!session)
1133    {
1134      DBG (DBG_error, "sane_read: handle is null!\n");
1135      return SANE_STATUS_INVAL;
1136    }
1137
1138  if (!buf)
1139    {
1140      DBG (DBG_error, "sane_read: buf is null!\n");
1141      return SANE_STATUS_INVAL;
1142    }
1143
1144  if (!len)
1145    {
1146      DBG (DBG_error, "sane_read: len is null!\n");
1147      return SANE_STATUS_INVAL;
1148    }
1149
1150  /* no data read yet */
1151  *len = 0;
1152
1153  /* check if session is scanning */
1154  if (!session->scanning)
1155    {
1156      DBG (DBG_warn,
1157	   "sane_read: scan was cancelled, is over or has not been initiated yet\n");
1158      return SANE_STATUS_CANCELLED;
1159    }
1160
1161  /* check for EOF, must be done before any physical read */
1162  if (session->sent >= session->to_send)
1163    {
1164      DBG (DBG_io, "sane_read: end of scan reached\n");
1165      return SANE_STATUS_EOF;
1166    }
1167
1168  /* if working buffer is empty, we do a physical data read */
1169  if (dev->top <= dev->bottom)
1170    {
1171      DBG (DBG_io, "sane_read: physical data read\n");
1172      /* check is there is data available. In case of non-blocking mode we return
1173       * as soon it is detected there is no data yet. Reads must by done line by
1174       * line, so we read only when count is bigger than bytes per line
1175       * */
1176      count = available_bytes (dev->fd);
1177      DBG (DBG_io, "sane_read: count=%d bytes\n", count);
1178      if (count < dev->bytes_per_line && session->non_blocking == SANE_TRUE)
1179	{
1180	  DBG (DBG_io, "sane_read: scanner hasn't enough data available\n");
1181	  DBG (DBG_proc, "sane_read: exit\n");
1182	  return SANE_STATUS_GOOD;
1183	}
1184
1185      /* now we can wait for data here */
1186      while (count < dev->bytes_per_line)
1187	{
1188	  /* test if document left the feeder, so we have to terminate the scan */
1189	  status = test_document (dev->fd);
1190	  if (status == SANE_STATUS_NO_DOCS)
1191	    {
1192	      session->to_send = session->sent;
1193	      return SANE_STATUS_EOF;
1194	    }
1195
1196	  /* don't call scanner too often */
1197	  usleep (10000);
1198	  count = available_bytes (dev->fd);
1199	}
1200
1201      /** compute size of physical data to read
1202       * on first read, position will be 0, while it will be 'bottom'
1203       * for the subsequent reads.
1204       * We try to read a complete buffer */
1205      size = dev->size - dev->position;
1206
1207      if (session->to_send - session->sent < size)
1208	{
1209	  /* not enough data left, so read remainder of scan */
1210	  size = session->to_send - session->sent;
1211	}
1212
1213      /* 600 dpi is 300x600 physical, and 400 is 200x400 */
1214      if (dev->ydpi > dev->model->max_xdpi)
1215	{
1216	  x2 = SANE_TRUE;
1217	}
1218      else
1219	{
1220	  x2 = SANE_FALSE;
1221	}
1222      lines = read_line (dev,
1223			 dev->buffer + dev->position,
1224			 dev->bytes_per_line,
1225			 size / dev->bytes_per_line,
1226			 SANE_TRUE, x2, dev->mode, dev->calibrated);
1227
1228      /* handle document end detection TODO try to recover the partial
1229       * buffer already read before EOD */
1230      if (lines == -1)
1231	{
1232	  DBG (DBG_io, "sane_read: error reading line\n");
1233	  return SANE_STATUS_IO_ERROR;
1234	}
1235
1236      /* gather lines until we have more than needed for lds */
1237      dev->position += lines * dev->bytes_per_line;
1238      dev->top = dev->position;
1239      if (dev->position > dev->bottom)
1240	{
1241	  dev->position = dev->bottom;
1242	}
1243      DBG (DBG_io, "sane_read: size    =%lu\n", (unsigned long)dev->size);
1244      DBG (DBG_io, "sane_read: bottom  =%lu\n", (unsigned long)dev->bottom);
1245      DBG (DBG_io, "sane_read: position=%lu\n", (unsigned long)dev->position);
1246      DBG (DBG_io, "sane_read: top     =%lu\n", (unsigned long)dev->top);
1247    }				/* end of physical data reading */
1248
1249  /* logical data reading */
1250  /* check if there data available in working buffer */
1251  if (dev->position < dev->top && dev->position >= dev->bottom)
1252    {
1253      DBG (DBG_io, "sane_read: logical data read\n");
1254      /* we have more data in internal buffer than asked ,
1255       * then send only max data */
1256      size = dev->top - dev->position;
1257      if (max_len < size)
1258	{
1259	  *len = max_len;
1260	}
1261      else
1262	/* if we don't have enough, send all what we have */
1263	{
1264	  *len = dev->top - dev->position;
1265	}
1266
1267      /* data copy */
1268      if (dev->lds == 0)
1269	{
1270	  memcpy (buf, dev->buffer + dev->position, *len);
1271	}
1272      else
1273	{
1274	  /* compute count of bytes for lds */
1275	  count = dev->lds * dev->bytes_per_line;
1276
1277	  /* adjust for lds as we copy data to frontend */
1278	  for (i = 0; i < *len; i++)
1279	    {
1280	      switch ((dev->position + i) % 3)
1281		{
1282		  /* red */
1283		case 0:
1284		  buf[i] = dev->buffer[dev->position + i - 2 * count];
1285		  break;
1286		  /* green */
1287		case 1:
1288		  buf[i] = dev->buffer[dev->position + i - count];
1289		  break;
1290		  /* blue */
1291		default:
1292		  buf[i] = dev->buffer[dev->position + i];
1293		  break;
1294		}
1295	    }
1296	}
1297      dev->position += *len;
1298
1299      /* update byte accounting */
1300      session->sent += *len;
1301      DBG (DBG_io, "sane_read: sent %d bytes from buffer to frontend\n",
1302	   *len);
1303      return SANE_STATUS_GOOD;
1304    }
1305
1306  /* check if we exhausted working buffer */
1307  if (dev->position >= dev->top && dev->position >= dev->bottom)
1308    {
1309      /* copy extra lines needed for lds in next buffer */
1310      if (dev->position > dev->bottom && dev->lds > 0)
1311	{
1312	  memcpy (dev->buffer,
1313		  dev->buffer + dev->position - dev->bottom, dev->bottom);
1314	}
1315
1316      /* restart buffer */
1317      dev->position = dev->bottom;
1318      dev->top = 0;
1319    }
1320
1321  DBG (DBG_io, "sane_read: size    =%lu\n", (unsigned long)dev->size);
1322  DBG (DBG_io, "sane_read: bottom  =%lu\n", (unsigned long)dev->bottom);
1323  DBG (DBG_io, "sane_read: position=%lu\n", (unsigned long)dev->position);
1324  DBG (DBG_io, "sane_read: top     =%lu\n", (unsigned long)dev->top);
1325
1326  DBG (DBG_proc, "sane_read: exit\n");
1327  return status;
1328}
1329
1330
1331/**
1332 * Cancels a scan.
1333 *
1334 * From the SANE spec:
1335 * This function is used to immediately or as quickly as possible
1336 * cancel the currently pending operation of the device represented by
1337 * handle h.  This function can be called at any time (as long as
1338 * handle h is a valid handle) but usually affects long-running
1339 * operations only (such as image is acquisition). It is safe to call
1340 * this function asynchronously (e.g., from within a signal handler).
1341 * It is important to note that completion of this operation does not
1342 * imply that the currently pending operation has been cancelled. It
1343 * only guarantees that cancellation has been initiated. Cancellation
1344 * completes only when the cancelled call returns (typically with a
1345 * status value of SANE_STATUS_CANCELLED).  Since the SANE API does
1346 * not require any other operations to be re-entrant, this implies
1347 * that a frontend must not call any other operation until the
1348 * cancelled operation has returned.
1349 */
1350void
1351sane_cancel (SANE_Handle handle)
1352{
1353  P5_Session *session = handle;
1354
1355  DBG (DBG_proc, "sane_cancel: start\n");
1356
1357  /* if scanning, abort and park head */
1358  if (session->scanning == SANE_TRUE)
1359    {
1360      /* detects if we are called after the scan is finished,
1361       * or if the scan is aborted */
1362      if (session->sent < session->to_send)
1363	{
1364	  DBG (DBG_info, "sane_cancel: aborting scan.\n");
1365	  /* device hasn't finished scan, we are aborting it
1366	   * and we may have to do something specific for it here */
1367	}
1368      else
1369	{
1370	  DBG (DBG_info, "sane_cancel: cleaning up after scan.\n");
1371	}
1372      session->scanning = SANE_FALSE;
1373    }
1374  eject (session->dev->fd);
1375
1376  DBG (DBG_proc, "sane_cancel: exit\n");
1377}
1378
1379
1380/**
1381 * Ends use of the session.
1382 *
1383 * From the SANE spec:
1384 * This function terminates the association between the device handle
1385 * passed in argument h and the device it represents. If the device is
1386 * presently active, a call to sane_cancel() is performed first. After
1387 * this function returns, handle h must not be used anymore.
1388 *
1389 * Handle resources are free'd before disposing the handle. But devices
1390 * resources must not be mdofied, since it could be used or reused until
1391 * sane_exit() is called.
1392 */
1393void
1394sane_close (SANE_Handle handle)
1395{
1396  P5_Session *prev, *session;
1397
1398  DBG (DBG_proc, "sane_close: start\n");
1399
1400  /* remove handle from list of open handles: */
1401  prev = NULL;
1402  for (session = sessions; session; session = session->next)
1403    {
1404      if (session == handle)
1405	break;
1406      prev = session;
1407    }
1408  if (!session)
1409    {
1410      DBG (DBG_error0, "close: invalid handle %p\n", handle);
1411      return;			/* oops, not a handle we know about */
1412    }
1413
1414  /* cancel any active scan */
1415  if (session->scanning == SANE_TRUE)
1416    {
1417      sane_cancel (handle);
1418    }
1419
1420  if (prev)
1421    prev->next = session->next;
1422  else
1423    sessions = session->next;
1424
1425  /* close low level device */
1426  if (session->dev->initialized == SANE_TRUE)
1427    {
1428      if (session->dev->calibrated == SANE_TRUE)
1429	{
1430	  save_calibration (session->dev);
1431	}
1432      disconnect (session->dev->fd);
1433      close_pp (session->dev->fd);
1434      session->dev->fd = -1;
1435      session->dev->initialized = SANE_FALSE;
1436
1437      /* free device data */
1438      if (session->dev->buffer != NULL)
1439	{
1440	  free (session->dev->buffer);
1441	}
1442      if (session->dev->buffer != NULL)
1443	{
1444	  free (session->dev->gain);
1445	  free (session->dev->offset);
1446	}
1447      if (session->dev->calibrated == SANE_TRUE)
1448	{
1449	  cleanup_calibration (session->dev);
1450	}
1451    }
1452
1453  /* free per session data */
1454  free (session->options[OPT_MODE].value.s);
1455  free ((void *)session->options[OPT_RESOLUTION].descriptor.constraint.word_list);
1456
1457  free (session);
1458
1459  DBG (DBG_proc, "sane_close: exit\n");
1460}
1461
1462
1463/**
1464 * Terminates the backend.
1465 *
1466 * From the SANE spec:
1467 * This function must be called to terminate use of a backend. The
1468 * function will first close all device handles that still might be
1469 * open (it is recommended to close device handles explicitly through
1470 * a call to sane_close(), but backends are required to release all
1471 * resources upon a call to this function). After this function
1472 * returns, no function other than sane_init() may be called
1473 * (regardless of the status value returned by sane_exit(). Neglecting
1474 * to call this function may result in some resources not being
1475 * released properly.
1476 */
1477void
1478sane_exit (void)
1479{
1480  struct P5_Session *session, *next;
1481  struct P5_Device *dev, *nextdev;
1482  int i;
1483
1484  DBG (DBG_proc, "sane_exit: start\n");
1485  init_count--;
1486
1487  if (init_count > 0)
1488    {
1489      DBG (DBG_info,
1490	   "sane_exit: still %d fronteds to leave before effective exit.\n",
1491	   init_count);
1492      return;
1493    }
1494
1495  /* free session structs */
1496  for (session = sessions; session; session = next)
1497    {
1498      next = session->next;
1499      sane_close ((SANE_Handle *) session);
1500      free (session);
1501    }
1502  sessions = NULL;
1503
1504  /* free devices structs */
1505  for (dev = devices; dev; dev = nextdev)
1506    {
1507      nextdev = dev->next;
1508      free (dev->name);
1509      free (dev);
1510    }
1511  devices = NULL;
1512
1513  /* now list of devices */
1514  if (devlist)
1515    {
1516      i = 0;
1517      while ((SANE_Device *) devlist[i])
1518	{
1519	  free ((SANE_Device *) devlist[i]);
1520	  i++;
1521	}
1522      free (devlist);
1523      devlist = NULL;
1524    }
1525
1526  DBG (DBG_proc, "sane_exit: exit\n");
1527}
1528
1529
1530/** @brief probe for all supported devices
1531 * This functions tries to probe if any of the supported devices of
1532 * the backend is present. Each detected device will be added to the
1533 * 'devices' list
1534 */
1535static SANE_Status
1536probe_p5_devices (void)
1537{
1538  /**> configuration structure used during attach */
1539  SANEI_Config config;
1540  /**> list of configuration options */
1541  SANE_Option_Descriptor *cfg_options[NUM_CFG_OPTIONS];
1542  /**> placeholders pointers for option values */
1543  void *values[NUM_CFG_OPTIONS];
1544  int i;
1545  SANE_Status status;
1546
1547  DBG (DBG_proc, "probe_p5_devices: start\n");
1548
1549  /* initialize configuration options */
1550  cfg_options[CFG_MODEL_NAME] =
1551    (SANE_Option_Descriptor *) malloc (sizeof (SANE_Option_Descriptor));
1552  cfg_options[CFG_MODEL_NAME]->name = "modelname";
1553  cfg_options[CFG_MODEL_NAME]->desc = "user provided scanner's model name";
1554  cfg_options[CFG_MODEL_NAME]->type = SANE_TYPE_INT;
1555  cfg_options[CFG_MODEL_NAME]->unit = SANE_UNIT_NONE;
1556  cfg_options[CFG_MODEL_NAME]->size = sizeof (SANE_Word);
1557  cfg_options[CFG_MODEL_NAME]->cap = SANE_CAP_SOFT_SELECT;
1558  cfg_options[CFG_MODEL_NAME]->constraint_type = SANE_CONSTRAINT_NONE;
1559  values[CFG_MODEL_NAME] = &p5cfg.modelname;
1560
1561  /* set configuration options structure */
1562  config.descriptors = cfg_options;
1563  config.values = values;
1564  config.count = NUM_CFG_OPTIONS;
1565
1566  /* generic configure and attach function */
1567  status = sanei_configure_attach (P5_CONFIG_FILE, &config,
1568                                   config_attach, NULL);
1569  /* free allocated options */
1570  for (i = 0; i < NUM_CFG_OPTIONS; i++)
1571    {
1572      free (cfg_options[i]);
1573    }
1574
1575  DBG (DBG_proc, "probe_p5_devices: end\n");
1576  return status;
1577}
1578
1579/** This function is called by sanei_configure_attach to try
1580 * to attach the backend to a device specified by the configuration file.
1581 *
1582 * @param config configuration structure filled with values read
1583 * 	         from configuration file
1584 * @param devname name of the device to try to attach to, it is
1585 * 	          the unprocessed line of the configuration file
1586 *
1587 * @return status SANE_STATUS_GOOD if no errors (even if no matching
1588 * 	    devices found)
1589 * 	   SANE_STATUS_INVAL in case of error
1590 */
1591static SANE_Status
1592config_attach (SANEI_Config __sane_unused__ * config, const char *devname,
1593               void __sane_unused__ *data)
1594{
1595  /* currently, the config is a global variable so config is useless here */
1596  /* the correct thing would be to have a generic sanei_attach_matching_devices
1597   * using an attach function with a config parameter */
1598  (void) config;
1599
1600  /* the devname has been processed and is ready to be used
1601   * directly. The config struct contains all the configuration data for
1602   * the corresponding device. Since there is no resources common to each
1603   * backends regarding parallel port, we can directly call the attach
1604   * function. */
1605  attach_p5 (devname, config);
1606
1607  return SANE_STATUS_GOOD;
1608}
1609
1610/** @brief try to attach to a device by its name
1611 * The attach tries to open the given device and match it
1612 * with devices handled by the backend. The configuration parameter
1613 * contains the values of the already parsed configuration options
1614 * from the conf file.
1615 * @param config configuration structure filled with values read
1616 * 	         from configuration file
1617 * @param devicename name of the device to try to attach to, it is
1618 * 	          the unprocessed line of the configuration file
1619 *
1620 * @return status SANE_STATUS_GOOD if no errors (even if no matching
1621 * 	    devices found)
1622 * 	   SANE_STATUS_NOM_MEM if there isn't enough memory to allocate the
1623 * 	   			device structure
1624 * 	   SANE_STATUS_UNSUPPORTED if the device if unknown by the backend
1625 * 	   SANE_STATUS_INVAL in case of other error
1626 */
1627static SANE_Status
1628attach_p5 (const char *devicename, SANEI_Config * config)
1629{
1630  struct P5_Device *device;
1631  struct P5_Model *model;
1632
1633  DBG (DBG_proc, "attach(%s): start\n", devicename);
1634  if(config==NULL)
1635    {
1636      DBG (DBG_warn, "attach: config is NULL\n");
1637    }
1638
1639  /* search if we already have it attached */
1640  for (device = devices; device; device = device->next)
1641    {
1642      if (strcmp (device->name, devicename) == 0)
1643	{
1644	  DBG (DBG_info, "attach: device already attached\n");
1645	  DBG (DBG_proc, "attach: exit\n");
1646	  return SANE_STATUS_GOOD;
1647	}
1648    }
1649
1650  /**
1651   * do physical probe of the device here. In case the device is recognized,
1652   * we allocate a device struct and give it options and model.
1653   * Else we return SANE_STATUS_UNSUPPORTED.
1654   */
1655  model = probe (devicename);
1656  if (model == NULL)
1657    {
1658      DBG (DBG_info,
1659	   "attach: device %s is not managed by the backend\n", devicename);
1660      DBG (DBG_proc, "attach: exit\n");
1661      return SANE_STATUS_UNSUPPORTED;
1662    }
1663
1664  /* allocate device struct */
1665  device = malloc (sizeof (*device));
1666  if (device == NULL)
1667    {
1668      return SANE_STATUS_NO_MEM;
1669      DBG (DBG_proc, "attach: exit\n");
1670    }
1671  memset (device, 0, sizeof (*device));
1672  device->model = model;
1673
1674  /* name of the device */
1675  device->name = strdup (devicename);
1676
1677  DBG (DBG_info, "attach: found %s %s %s at %s\n",
1678       device->model->vendor, device->model->product, device->model->type,
1679       device->name);
1680
1681  /* we insert new device at start of the chained list */
1682  /* head of the list becomes the next, and start is replaced */
1683  /* with the new session struct */
1684  device->next = devices;
1685  devices = device;
1686
1687  /* initialization is done at sane_open */
1688  device->initialized = SANE_FALSE;
1689  device->calibrated = SANE_FALSE;
1690
1691  DBG (DBG_proc, "attach: exit\n");
1692  return SANE_STATUS_GOOD;
1693}
1694
1695
1696/** @brief set initial value for the scanning options
1697 * for each sessions, control options are initialized based on the capability
1698 * of the model of the physical device.
1699 * @param session scanner session to initialize options
1700 * @return SANE_STATUS_GOOD on success
1701 */
1702static SANE_Status
1703init_options (struct P5_Session *session)
1704{
1705  SANE_Int option, i, min, idx;
1706  SANE_Word *dpi_list;
1707  P5_Model *model = session->dev->model;
1708
1709  DBG (DBG_proc, "init_options: start\n");
1710
1711  /* we first initialize each options with a default value */
1712  memset (session->options, 0, sizeof (session->options[OPT_NUM_OPTS]));
1713  for (option = 0; option < NUM_OPTIONS; option++)
1714    {
1715      session->options[option].descriptor.size = sizeof (SANE_Word);
1716      session->options[option].descriptor.cap =
1717	SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
1718    }
1719
1720  /* we set up all the options listed in the P5_Option enum */
1721
1722  /* last option / end of list marker */
1723  session->options[OPT_NUM_OPTS].descriptor.name = SANE_NAME_NUM_OPTIONS;
1724  session->options[OPT_NUM_OPTS].descriptor.title = SANE_TITLE_NUM_OPTIONS;
1725  session->options[OPT_NUM_OPTS].descriptor.desc = SANE_DESC_NUM_OPTIONS;
1726  session->options[OPT_NUM_OPTS].descriptor.type = SANE_TYPE_INT;
1727  session->options[OPT_NUM_OPTS].descriptor.cap = SANE_CAP_SOFT_DETECT;
1728  session->options[OPT_NUM_OPTS].value.w = NUM_OPTIONS;
1729
1730  /* "Standard" group: */
1731  session->options[OPT_STANDARD_GROUP].descriptor.title = SANE_TITLE_STANDARD;
1732  session->options[OPT_STANDARD_GROUP].descriptor.name = SANE_NAME_STANDARD;
1733  session->options[OPT_STANDARD_GROUP].descriptor.desc = SANE_DESC_STANDARD;
1734  session->options[OPT_STANDARD_GROUP].descriptor.type = SANE_TYPE_GROUP;
1735  session->options[OPT_STANDARD_GROUP].descriptor.size = 0;
1736  session->options[OPT_STANDARD_GROUP].descriptor.cap = 0;
1737  session->options[OPT_STANDARD_GROUP].descriptor.constraint_type =
1738    SANE_CONSTRAINT_NONE;
1739
1740  /* scan mode */
1741  session->options[OPT_MODE].descriptor.name = SANE_NAME_SCAN_MODE;
1742  session->options[OPT_MODE].descriptor.title = SANE_TITLE_SCAN_MODE;
1743  session->options[OPT_MODE].descriptor.desc = SANE_DESC_SCAN_MODE;
1744  session->options[OPT_MODE].descriptor.type = SANE_TYPE_STRING;
1745  session->options[OPT_MODE].descriptor.cap |= SANE_CAP_AUTOMATIC;
1746  session->options[OPT_MODE].descriptor.constraint_type =
1747    SANE_CONSTRAINT_STRING_LIST;
1748  session->options[OPT_MODE].descriptor.size = max_string_size (mode_list);
1749  session->options[OPT_MODE].descriptor.constraint.string_list = mode_list;
1750  session->options[OPT_MODE].value.s = strdup (mode_list[0]);
1751
1752  /* preview */
1753  session->options[OPT_PREVIEW].descriptor.name = SANE_NAME_PREVIEW;
1754  session->options[OPT_PREVIEW].descriptor.title = SANE_TITLE_PREVIEW;
1755  session->options[OPT_PREVIEW].descriptor.desc = SANE_DESC_PREVIEW;
1756  session->options[OPT_PREVIEW].descriptor.type = SANE_TYPE_BOOL;
1757  session->options[OPT_PREVIEW].descriptor.cap |= SANE_CAP_AUTOMATIC;
1758  session->options[OPT_PREVIEW].descriptor.unit = SANE_UNIT_NONE;
1759  session->options[OPT_PREVIEW].descriptor.constraint_type =
1760    SANE_CONSTRAINT_NONE;
1761  session->options[OPT_PREVIEW].value.w = SANE_FALSE;
1762
1763  /** @brief build resolution list
1764   * We merge xdpi and ydpi list to provide only one resolution option control.
1765   * This is the most common case for backends and fronteds and give 'square'
1766   * pixels. The SANE API allow to control x and y dpi independently, but this is
1767   * rarely done and may confuse both frontends and users. In case a dpi value exists
1768   * for one but not for the other, the backend will have to crop data so that the
1769   * frontend is unaffected. A common case is that motor resolution (ydpi) is higher
1770   * than sensor resolution (xdpi), so scan lines must be scaled up to keep square
1771   * pixel when doing sane_read().
1772   * TODO this deserves a dedicated function and some unit testing
1773   */
1774
1775  /* find minimum first */
1776  min = 65535;
1777  for (i = 0; i < MAX_RESOLUTIONS && model->xdpi_values[i] > 0; i++)
1778    {
1779      if (model->xdpi_values[i] < min)
1780	min = model->xdpi_values[i];
1781    }
1782  for (i = 0; i < MAX_RESOLUTIONS && model->ydpi_values[i] > 0; i++)
1783    {
1784      if (model->ydpi_values[i] < min)
1785	min = model->ydpi_values[i];
1786    }
1787
1788  dpi_list = malloc ((MAX_RESOLUTIONS * 2 + 1) * sizeof (SANE_Word));
1789  if (!dpi_list)
1790    return SANE_STATUS_NO_MEM;
1791  dpi_list[1] = min;
1792  idx = 2;
1793
1794  /* find any value greater than the last used min and
1795   * less than the max value
1796   */
1797  do
1798    {
1799      min = 65535;
1800      for (i = 0; i < MAX_RESOLUTIONS && model->xdpi_values[i] > 0; i++)
1801	{
1802	  if (model->xdpi_values[i] < min
1803	      && model->xdpi_values[i] > dpi_list[idx - 1])
1804	    min = model->xdpi_values[i];
1805	}
1806      for (i = 0; i < MAX_RESOLUTIONS && model->ydpi_values[i] > 0; i++)
1807	{
1808	  if (model->ydpi_values[i] < min
1809	      && model->ydpi_values[i] > dpi_list[idx - 1])
1810	    min = model->ydpi_values[i];
1811	}
1812      if (min < 65535)
1813	{
1814	  dpi_list[idx] = min;
1815	  idx++;
1816	}
1817    }
1818  while (min != 65535);
1819  dpi_list[idx] = 0;
1820  /* the count of different resolution is put at the beginning */
1821  dpi_list[0] = idx - 1;
1822
1823  session->options[OPT_RESOLUTION].descriptor.name =
1824    SANE_NAME_SCAN_RESOLUTION;
1825  session->options[OPT_RESOLUTION].descriptor.title =
1826    SANE_TITLE_SCAN_RESOLUTION;
1827  session->options[OPT_RESOLUTION].descriptor.desc =
1828    SANE_DESC_SCAN_RESOLUTION;
1829  session->options[OPT_RESOLUTION].descriptor.type = SANE_TYPE_INT;
1830  session->options[OPT_RESOLUTION].descriptor.cap |= SANE_CAP_AUTOMATIC;
1831  session->options[OPT_RESOLUTION].descriptor.unit = SANE_UNIT_DPI;
1832  session->options[OPT_RESOLUTION].descriptor.constraint_type =
1833    SANE_CONSTRAINT_WORD_LIST;
1834  session->options[OPT_RESOLUTION].descriptor.constraint.word_list = dpi_list;
1835
1836  /* initial value is lowest available dpi */
1837  session->options[OPT_RESOLUTION].value.w = min;
1838
1839  /* "Geometry" group: */
1840  session->options[OPT_GEOMETRY_GROUP].descriptor.title = SANE_TITLE_GEOMETRY;
1841  session->options[OPT_GEOMETRY_GROUP].descriptor.name = SANE_NAME_GEOMETRY;
1842  session->options[OPT_GEOMETRY_GROUP].descriptor.desc = SANE_DESC_GEOMETRY;
1843  session->options[OPT_GEOMETRY_GROUP].descriptor.type = SANE_TYPE_GROUP;
1844  session->options[OPT_GEOMETRY_GROUP].descriptor.cap = SANE_CAP_ADVANCED;
1845  session->options[OPT_GEOMETRY_GROUP].descriptor.size = 0;
1846  session->options[OPT_GEOMETRY_GROUP].descriptor.constraint_type =
1847    SANE_CONSTRAINT_NONE;
1848
1849  /* adapt the constraint range to the detected model */
1850  x_range.max = model->x_size;
1851  y_range.max = model->y_size;
1852
1853  /* top-left x */
1854  session->options[OPT_TL_X].descriptor.name = SANE_NAME_SCAN_TL_X;
1855  session->options[OPT_TL_X].descriptor.title = SANE_TITLE_SCAN_TL_X;
1856  session->options[OPT_TL_X].descriptor.desc = SANE_DESC_SCAN_TL_X;
1857  session->options[OPT_TL_X].descriptor.type = SANE_TYPE_FIXED;
1858  session->options[OPT_TL_X].descriptor.cap |= SANE_CAP_AUTOMATIC;
1859  session->options[OPT_TL_X].descriptor.unit = SANE_UNIT_MM;
1860  session->options[OPT_TL_X].descriptor.constraint_type =
1861    SANE_CONSTRAINT_RANGE;
1862  session->options[OPT_TL_X].descriptor.constraint.range = &x_range;
1863  session->options[OPT_TL_X].value.w = 0;
1864
1865  /* top-left y */
1866  session->options[OPT_TL_Y].descriptor.name = SANE_NAME_SCAN_TL_Y;
1867  session->options[OPT_TL_Y].descriptor.title = SANE_TITLE_SCAN_TL_Y;
1868  session->options[OPT_TL_Y].descriptor.desc = SANE_DESC_SCAN_TL_Y;
1869  session->options[OPT_TL_Y].descriptor.type = SANE_TYPE_FIXED;
1870  session->options[OPT_TL_Y].descriptor.cap |= SANE_CAP_AUTOMATIC;
1871  session->options[OPT_TL_Y].descriptor.unit = SANE_UNIT_MM;
1872  session->options[OPT_TL_Y].descriptor.constraint_type =
1873    SANE_CONSTRAINT_RANGE;
1874  session->options[OPT_TL_Y].descriptor.constraint.range = &y_range;
1875  session->options[OPT_TL_Y].value.w = 0;
1876
1877  /* bottom-right x */
1878  session->options[OPT_BR_X].descriptor.name = SANE_NAME_SCAN_BR_X;
1879  session->options[OPT_BR_X].descriptor.title = SANE_TITLE_SCAN_BR_X;
1880  session->options[OPT_BR_X].descriptor.desc = SANE_DESC_SCAN_BR_X;
1881  session->options[OPT_BR_X].descriptor.type = SANE_TYPE_FIXED;
1882  session->options[OPT_BR_X].descriptor.cap |= SANE_CAP_AUTOMATIC;
1883  session->options[OPT_BR_X].descriptor.unit = SANE_UNIT_MM;
1884  session->options[OPT_BR_X].descriptor.constraint_type =
1885    SANE_CONSTRAINT_RANGE;
1886  session->options[OPT_BR_X].descriptor.constraint.range = &x_range;
1887  session->options[OPT_BR_X].value.w = x_range.max;
1888
1889  /* bottom-right y */
1890  session->options[OPT_BR_Y].descriptor.name = SANE_NAME_SCAN_BR_Y;
1891  session->options[OPT_BR_Y].descriptor.title = SANE_TITLE_SCAN_BR_Y;
1892  session->options[OPT_BR_Y].descriptor.desc = SANE_DESC_SCAN_BR_Y;
1893  session->options[OPT_BR_Y].descriptor.type = SANE_TYPE_FIXED;
1894  session->options[OPT_BR_Y].descriptor.cap |= SANE_CAP_AUTOMATIC;
1895  session->options[OPT_BR_Y].descriptor.unit = SANE_UNIT_MM;
1896  session->options[OPT_BR_Y].descriptor.constraint_type =
1897    SANE_CONSTRAINT_RANGE;
1898  session->options[OPT_BR_Y].descriptor.constraint.range = &y_range;
1899  session->options[OPT_BR_Y].value.w = y_range.max;
1900
1901  /* sensor group */
1902  session->options[OPT_SENSOR_GROUP].descriptor.name = SANE_NAME_SENSORS;
1903  session->options[OPT_SENSOR_GROUP].descriptor.title = SANE_TITLE_SENSORS;
1904  session->options[OPT_SENSOR_GROUP].descriptor.desc = SANE_DESC_SENSORS;
1905  session->options[OPT_SENSOR_GROUP].descriptor.type = SANE_TYPE_GROUP;
1906  session->options[OPT_SENSOR_GROUP].descriptor.constraint_type =
1907    SANE_CONSTRAINT_NONE;
1908
1909  /* page loaded sensor */
1910  session->options[OPT_PAGE_LOADED_SW].descriptor.name =
1911    SANE_NAME_PAGE_LOADED;
1912  session->options[OPT_PAGE_LOADED_SW].descriptor.title =
1913    SANE_TITLE_PAGE_LOADED;
1914  session->options[OPT_PAGE_LOADED_SW].descriptor.desc =
1915    SANE_DESC_PAGE_LOADED;
1916  session->options[OPT_PAGE_LOADED_SW].descriptor.type = SANE_TYPE_BOOL;
1917  session->options[OPT_PAGE_LOADED_SW].descriptor.unit = SANE_UNIT_NONE;
1918  session->options[OPT_PAGE_LOADED_SW].descriptor.cap =
1919    SANE_CAP_SOFT_DETECT | SANE_CAP_HARD_SELECT | SANE_CAP_ADVANCED;
1920  session->options[OPT_PAGE_LOADED_SW].value.b = 0;
1921
1922  /* calibration needed */
1923  session->options[OPT_NEED_CALIBRATION_SW].descriptor.name =
1924    "need-calibration";
1925  session->options[OPT_NEED_CALIBRATION_SW].descriptor.title =
1926    SANE_I18N ("Need calibration");
1927  session->options[OPT_NEED_CALIBRATION_SW].descriptor.desc =
1928    SANE_I18N ("The scanner needs calibration for the current settings");
1929  session->options[OPT_NEED_CALIBRATION_SW].descriptor.type = SANE_TYPE_BOOL;
1930  session->options[OPT_NEED_CALIBRATION_SW].descriptor.unit = SANE_UNIT_NONE;
1931  session->options[OPT_NEED_CALIBRATION_SW].descriptor.cap =
1932    SANE_CAP_SOFT_DETECT | SANE_CAP_HARD_SELECT | SANE_CAP_ADVANCED;
1933  session->options[OPT_NEED_CALIBRATION_SW].value.b = 0;
1934
1935  /* button group */
1936  session->options[OPT_BUTTON_GROUP].descriptor.name = "Buttons";
1937  session->options[OPT_BUTTON_GROUP].descriptor.title = SANE_I18N ("Buttons");
1938  session->options[OPT_BUTTON_GROUP].descriptor.desc = SANE_I18N ("Buttons");
1939  session->options[OPT_BUTTON_GROUP].descriptor.type = SANE_TYPE_GROUP;
1940  session->options[OPT_BUTTON_GROUP].descriptor.constraint_type =
1941    SANE_CONSTRAINT_NONE;
1942
1943  /* calibrate button */
1944  session->options[OPT_CALIBRATE].descriptor.name = "calibrate";
1945  session->options[OPT_CALIBRATE].descriptor.title = SANE_I18N ("Calibrate");
1946  session->options[OPT_CALIBRATE].descriptor.desc =
1947    SANE_I18N ("Start calibration using special sheet");
1948  session->options[OPT_CALIBRATE].descriptor.type = SANE_TYPE_BUTTON;
1949  session->options[OPT_CALIBRATE].descriptor.unit = SANE_UNIT_NONE;
1950  session->options[OPT_CALIBRATE].descriptor.cap =
1951    SANE_CAP_SOFT_DETECT | SANE_CAP_SOFT_SELECT | SANE_CAP_ADVANCED |
1952    SANE_CAP_AUTOMATIC;
1953  session->options[OPT_CALIBRATE].value.b = 0;
1954
1955  /* clear calibration cache button */
1956  session->options[OPT_CLEAR_CALIBRATION].descriptor.name = "clear";
1957  session->options[OPT_CLEAR_CALIBRATION].descriptor.title =
1958    SANE_I18N ("Clear calibration");
1959  session->options[OPT_CLEAR_CALIBRATION].descriptor.desc =
1960    SANE_I18N ("Clear calibration cache");
1961  session->options[OPT_CLEAR_CALIBRATION].descriptor.type = SANE_TYPE_BUTTON;
1962  session->options[OPT_CLEAR_CALIBRATION].descriptor.unit = SANE_UNIT_NONE;
1963  session->options[OPT_CLEAR_CALIBRATION].descriptor.cap =
1964    SANE_CAP_SOFT_DETECT | SANE_CAP_SOFT_SELECT | SANE_CAP_ADVANCED |
1965    SANE_CAP_AUTOMATIC;
1966  session->options[OPT_CLEAR_CALIBRATION].value.b = 0;
1967
1968  /* until work on calibration isfinished */
1969  DISABLE (OPT_CALIBRATE);
1970  DISABLE (OPT_CLEAR_CALIBRATION);
1971
1972  DBG (DBG_proc, "init_options: exit\n");
1973  return SANE_STATUS_GOOD;
1974}
1975
1976/** @brief physical probe of a device
1977 * This function probes for a scanning device using the given name. If the
1978 * device is managed, a model structure describing the device will be returned.
1979 * @param devicename low level device to access to probe hardware
1980 * @return NULL is the device is unsupported, or a model struct describing the
1981 * device.
1982 */
1983P5_Model *
1984probe (const char *devicename)
1985{
1986  int fd;
1987
1988  /* open parallel port device */
1989  fd = open_pp (devicename);
1990  if (fd < 0)
1991    {
1992      DBG (DBG_error, "probe: failed to open '%s' device!\n", devicename);
1993      return NULL;
1994    }
1995
1996  /* now try to connect to scanner */
1997  if (connect (fd) != SANE_TRUE)
1998    {
1999      DBG (DBG_error, "probe: failed to connect!\n");
2000      close_pp (fd);
2001      return NULL;
2002    }
2003
2004  /* set up for memory test */
2005  write_reg (fd, REG1, 0x00);
2006  write_reg (fd, REG7, 0x00);
2007  write_reg (fd, REG0, 0x00);
2008  write_reg (fd, REG1, 0x00);
2009  write_reg (fd, REGF, 0x80);
2010  if (memtest (fd, 0x0100) != SANE_TRUE)
2011    {
2012      disconnect (fd);
2013      close_pp (fd);
2014      DBG (DBG_error, "probe: memory test failed!\n");
2015      return NULL;
2016    }
2017  else
2018    {
2019      DBG (DBG_info, "memtest() OK...\n");
2020    }
2021  write_reg (fd, REG7, 0x00);
2022
2023  /* check for document presence 0xC6: present, 0xC3 no document */
2024  test_document (fd);
2025
2026  /* release device and parport for next uses */
2027  disconnect (fd);
2028  close_pp (fd);
2029
2030  /* for there is only one supported model, so we use hardcoded values */
2031  DBG (DBG_proc, "probe: exit\n");
2032  return &pagepartner_model;
2033}
2034
2035
2036/* vim: set sw=2 cino=>2se-1sn-1s{s^-1st0(0u0 smarttab expandtab: */
2037