• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* SANE - Scanner Access Now Easy.
2 
3    Copyright (C) 2011-2020 Rolf Bensch <rolf at bensch hyphen online dot de>
4    Copyright (C) 2007-2008 Nicolas Martin, <nicols-guest at alioth dot debian dot org>
5    Copyright (C) 2006-2007 Wittawat Yamwong <wittawat@web.de>
6 
7    This file is part of the SANE package.
8 
9    This program is free software; you can redistribute it and/or
10    modify it under the terms of the GNU General Public License as
11    published by the Free Software Foundation; either version 2 of the
12    License, or (at your option) any later version.
13 
14    This program is distributed in the hope that it will be useful, but
15    WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17    General Public License for more details.
18 
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <https://www.gnu.org/licenses/>.
21 
22    As a special exception, the authors of SANE give permission for
23    additional uses of the libraries contained in this release of SANE.
24 
25    The exception is that, if you link a SANE library with other files
26    to produce an executable, this does not by itself cause the
27    resulting executable to be covered by the GNU General Public
28    License.  Your use of that executable is in no way restricted on
29    account of linking the SANE library code into it.
30 
31    This exception does not, however, invalidate any other reasons why
32    the executable file might be covered by the GNU General Public
33    License.
34 
35    If you submit changes to SANE to the maintainers to be included in
36    a subsequent release, you agree by submitting the changes that
37    those changes may be distributed with this exception intact.
38 
39    If you write modifications of your own for SANE, it is your choice
40    whether to permit this exception to apply to your modifications.
41    If you do not wish that, delete this exception notice.
42  */
43 #include "../include/sane/config.h"
44 
45 #include <errno.h>
46 #include <string.h>
47 #include <stdlib.h>
48 #ifdef USE_PTHREAD
49 # include <pthread.h>
50 #endif
51 #include <signal.h>		/* sigaction(POSIX) */
52 #include <unistd.h>		/* POSIX: write read close pipe */
53 #ifdef HAVE_FCNTL_H
54 # include <fcntl.h>
55 #endif
56 
57 #include "pixma_rename.h"
58 #include "pixma.h"
59 
60 # define DEBUG_NOT_STATIC
61 # include "../include/sane/sane.h"
62 # include "../include/sane/sanei.h"
63 # include "../include/sane/saneopts.h"
64 # include "../include/sane/sanei_thread.h"
65 # include "../include/sane/sanei_backend.h"
66 # include "../include/sane/sanei_config.h"
67 # include "../include/sane/sanei_jpeg.h"
68 # include "../include/sane/sanei_usb.h"
69 
70 #ifdef NDEBUG
71 # define PDBG(x)
72 #else
73 #  define PDBG(x) IF_DBG(x)
74 #endif /* NDEBUG */
75 
76 #ifdef __GNUC__
77 # define UNUSED(v) (void) v
78 #else
79 # define UNUSED(v)
80 #endif
81 
82 #define DECL_CTX pixma_sane_t *ss = check_handle(h)
83 #define OPT_IN_CTX ss->opt
84 #define SOD(opt)  OPT_IN_CTX[opt].sod
85 #define OVAL(opt) OPT_IN_CTX[opt].val
86 #define AUTO_GAMMA 2.2
87 
88 /* pixma_sane_options.h generated by
89  * scripts/pixma_gen_options.py h < pixma.c > pixma_sane_options.h
90  */
91 #include "pixma_sane_options.h"
92 
93 #define BUTTON_GROUP_SIZE ( opt_adf_orientation - opt_button_1 + 1 )
94 #define BUTTON_GROUP_INDEX(x) ( x - opt_button_1 )
95 
96 typedef struct pixma_sane_t
97 {
98   struct pixma_sane_t *next;
99   pixma_t *s;
100   pixma_scan_param_t sp;
101   SANE_Bool cancel;
102 
103   /* valid states: idle, !idle && scanning, !idle && !scanning */
104   SANE_Bool idle;
105   SANE_Bool scanning;
106   SANE_Status last_read_status;	/* valid if !idle && !scanning */
107 
108   option_descriptor_t opt[opt_last];
109   char button_option_is_cached[BUTTON_GROUP_SIZE];
110   SANE_Range xrange, yrange;
111   SANE_Word dpi_list[9];	/* up to 9600 dpi */
112   SANE_String_Const mode_list[6];
113   pixma_scan_mode_t mode_map[6];
114   uint8_t gamma_table[4096];
115   SANE_String_Const source_list[4];
116   pixma_paper_source_t source_map[4];
117   SANE_String_Const calibrate_list[PIXMA_CALIBRATE_NUM_OPTS + 1];
118   pixma_calibrate_option_t calibrate_map[PIXMA_CALIBRATE_NUM_OPTS + 1];
119 
120   unsigned byte_pos_in_line, output_line_size;
121   uint64_t image_bytes_read;
122   unsigned page_count;		/* valid for ADF */
123 
124   SANE_Pid reader_taskid;
125   int wpipe, rpipe;
126   SANE_Bool reader_stop;
127 
128   /* Valid for JPEG source */
129   djpeg_dest_ptr jdst;
130   struct jpeg_decompress_struct jpeg_cinfo;
131   struct jpeg_error_mgr jpeg_err;
132   SANE_Bool jpeg_header_seen;
133 } pixma_sane_t;
134 
135 typedef struct
136 {
137   struct jpeg_source_mgr jpeg;
138 
139   pixma_sane_t *s;
140   JOCTET *buffer;
141 
142   SANE_Byte *linebuffer;
143   SANE_Int linebuffer_size;
144   SANE_Int linebuffer_index;
145 } pixma_jpeg_src_mgr;
146 
147 
148 static const char vendor_str[] = "CANON";
149 static const char type_str[] = "multi-function peripheral";
150 
151 static pixma_sane_t *first_scanner = NULL;
152 static const SANE_Device **dev_list = NULL;
153 static const char* conf_devices[MAX_CONF_DEVICES];
154 
mark_all_button_options_cached(struct pixma_sane_t * ss)155 static void mark_all_button_options_cached ( struct pixma_sane_t * ss )
156 {
157   int i;
158   for (i = 0; i < (opt__group_5 - opt_button_1); i++ )
159       ss -> button_option_is_cached[i] = 1;
160 }
161 
config_attach_pixma(SANEI_Config __sane_unused__ * config,const char * devname,void __sane_unused__ * data)162 static SANE_Status config_attach_pixma(SANEI_Config __sane_unused__ * config,
163 				       const char *devname,
164 				       void __sane_unused__ *data)
165 {
166   int i;
167   for (i=0; i < (MAX_CONF_DEVICES -1); i++)
168     {
169       if(conf_devices[i] == NULL)
170         {
171           conf_devices[i] = strdup(devname);
172           return SANE_STATUS_GOOD;
173         }
174     }
175   return SANE_STATUS_INVAL;
176 }
177 
178 static SANE_Status
map_error(int error)179 map_error (int error)
180 {
181   if (error >= 0)
182     return SANE_STATUS_GOOD;
183 
184   switch (error)
185     {
186     case PIXMA_ENOMEM:
187       return SANE_STATUS_NO_MEM;
188     case PIXMA_ECANCELED:
189       return SANE_STATUS_CANCELLED;
190     case PIXMA_EBUSY:
191       return SANE_STATUS_DEVICE_BUSY;
192     case PIXMA_EINVAL:
193       return SANE_STATUS_INVAL;
194     case PIXMA_EACCES:
195       return SANE_STATUS_ACCESS_DENIED;
196     case PIXMA_EPAPER_JAMMED:
197       return SANE_STATUS_JAMMED;
198     case PIXMA_ENO_PAPER:
199       return SANE_STATUS_NO_DOCS;
200     case PIXMA_ECOVER_OPEN:
201       return SANE_STATUS_COVER_OPEN;
202     case PIXMA_ENOTSUP:
203       return SANE_STATUS_UNSUPPORTED;
204     case PIXMA_EPROTO:
205     case PIXMA_ENODEV:
206     case PIXMA_EIO:
207     case PIXMA_ETIMEDOUT:
208       return SANE_STATUS_IO_ERROR;
209     }
210   PDBG (pixma_dbg (1, "BUG: unmapped error %d\n", error));
211   return SANE_STATUS_IO_ERROR;
212 }
213 
214 static int
getenv_atoi(const char * name,int def)215 getenv_atoi (const char *name, int def)
216 {
217   const char *str = getenv (name);
218   return (str) ? atoi (str) : def;
219 }
220 
221 #define CONST_CAST(t,x) (t)(x)
222 
223 static void
free_block(const void * ptr)224 free_block (const void * ptr)
225 {
226   free (CONST_CAST (void *, ptr));
227 }
228 
229 static void
cleanup_device_list(void)230 cleanup_device_list (void)
231 {
232   if (dev_list)
233     {
234       int i;
235       for (i = 0; dev_list[i]; i++)
236         {
237           free_block ((const void *) dev_list[i]->name);
238           free_block ((const void *) dev_list[i]->model);
239           free_block ((const void *) dev_list[i]);
240         }
241     }
242   free (dev_list);
243   dev_list = NULL;
244 }
245 
246 static void
find_scanners(SANE_Bool local_only)247 find_scanners (SANE_Bool local_only)
248 {
249   unsigned i, nscanners;
250 
251   cleanup_device_list ();
252   nscanners = pixma_find_scanners (conf_devices, local_only);
253   PDBG (pixma_dbg (3, "pixma_find_scanners() found %u devices\n", nscanners));
254   dev_list =
255     (const SANE_Device **) calloc (nscanners + 1, sizeof (*dev_list));
256   if (!dev_list)
257     return;
258   for (i = 0; i != nscanners; i++)
259     {
260       SANE_Device *sdev = (SANE_Device *) calloc (1, sizeof (*sdev));
261       char *name, *model;
262       if (!sdev)
263         goto nomem;
264       name = strdup (pixma_get_device_id (i));
265       model = strdup (pixma_get_device_model (i));
266       if (!name || !model)
267         {
268           free (name);
269           free (model);
270           free (sdev);
271           goto nomem;
272         }
273       sdev->name = name;
274       sdev->model = model;
275       sdev->vendor = vendor_str;
276       sdev->type = type_str;
277       dev_list[i] = sdev;
278     }
279   /* dev_list is already NULL terminated by calloc(). */
280   return;
281 
282 nomem:
283   PDBG (pixma_dbg (1, "WARNING:not enough memory for device list\n"));
284   return;
285 }
286 
287 static pixma_sane_t *
check_handle(SANE_Handle h)288 check_handle (SANE_Handle h)
289 {
290   pixma_sane_t *p;
291 
292   for (p = first_scanner; p && (SANE_Handle) p != h; p = p->next)
293     {
294     }
295   return p;
296 }
297 
298 static void
update_button_state(pixma_sane_t * ss,SANE_Int * info)299 update_button_state (pixma_sane_t * ss, SANE_Int * info)
300 {
301   SANE_Int b1 = OVAL (opt_button_1).w;
302   SANE_Int b2 = OVAL (opt_button_2).w;
303   uint32_t ev = pixma_wait_event (ss->s, 300);
304   switch (ev & ~PIXMA_EV_ACTION_MASK)
305     {
306     case PIXMA_EV_BUTTON1:
307       b1 = 1;
308       break;
309     case PIXMA_EV_BUTTON2:
310       b2 = 1;
311       break;
312     }
313 
314   if (b1 != OVAL (opt_button_1).w || b2 != OVAL (opt_button_2).w)
315     {
316     *info |= SANE_INFO_RELOAD_OPTIONS;
317     OVAL (opt_button_1).w = b1;
318     OVAL (opt_button_2).w = b2;
319     OVAL (opt_original).w = GET_EV_ORIGINAL(ev);
320     OVAL (opt_target).w = GET_EV_TARGET(ev);
321     OVAL (opt_scan_resolution).w = GET_EV_DPI(ev);
322     OVAL (opt_document_type).w = GET_EV_DOC(ev);
323     OVAL (opt_adf_status).w = GET_EV_STAT(ev);
324     OVAL (opt_adf_orientation).w = GET_EV_ORIENT(ev);
325     }
326   mark_all_button_options_cached(ss);
327 }
328 
329 static SANE_Bool
enable_option(pixma_sane_t * ss,SANE_Int o,SANE_Bool enable)330 enable_option (pixma_sane_t * ss, SANE_Int o, SANE_Bool enable)
331 {
332   SANE_Word save = SOD (o).cap;
333   if (enable)
334     SOD (o).cap &= ~SANE_CAP_INACTIVE;
335   else
336     SOD (o).cap |= SANE_CAP_INACTIVE;
337   return (save != SOD (o).cap);
338 }
339 
340 static void
clamp_value(pixma_sane_t * ss,SANE_Int n,void * v,SANE_Int * info)341 clamp_value (pixma_sane_t * ss, SANE_Int n, void *v, SANE_Int * info)
342 {
343   SANE_Option_Descriptor *sod = &SOD (n);
344   SANE_Word *va = (SANE_Word *) v;
345   const SANE_Range *range = sod->constraint.range;
346   int i, nmemb;
347 
348   nmemb = sod->size / sizeof (SANE_Word);
349   for (i = 0; i < nmemb; i++)
350     {
351       SANE_Word value = va[i];
352       if (value < range->min)
353         {
354           value = range->min;
355         }
356       else if (value > range->max)
357         {
358           value = range->max;
359         }
360       if (range->quant != 0)
361         {
362           value = (value - range->min + range->quant / 2) /
363             range->quant * range->quant;
364         }
365       if (value != va[i])
366         {
367           va[i] = value;
368           *info |= SANE_INFO_INEXACT;
369         }
370     }
371 }
372 
373 /* create dynamic mode_list
374  * ss:      scanner device
375  * tpu = 0: flatbed or ADF mode
376  *          1 bit lineart, 8 bit grayscale and 24 bit color scans
377  * tpu = 1: TPU mode
378  *          16 bit grayscale and 48 bit color scans */
379 static void
create_mode_list(pixma_sane_t * ss)380 create_mode_list (pixma_sane_t * ss)
381 {
382   SANE_Bool tpu;
383   const pixma_config_t *cfg;
384   int i;
385 
386   cfg = pixma_get_config (ss->s);
387   tpu = (ss->source_map[OVAL (opt_source).w] == PIXMA_SOURCE_TPU);
388 
389   /* setup available mode */
390   i = 0;
391   ss->mode_list[i] = SANE_VALUE_SCAN_MODE_COLOR;
392   ss->mode_map[i] = PIXMA_SCAN_MODE_COLOR;
393   i++;
394   if (cfg->cap & PIXMA_CAP_GRAY)
395     {
396       ss->mode_list[i] = SANE_VALUE_SCAN_MODE_GRAY;
397       ss->mode_map[i] = PIXMA_SCAN_MODE_GRAY;
398       i++;
399     }
400   if (tpu && (cfg->cap & PIXMA_CAP_NEGATIVE))
401     {
402       ss->mode_list[i] = SANE_I18N ("Negative color");
403       ss->mode_map[i] = PIXMA_SCAN_MODE_NEGATIVE_COLOR;
404       i++;
405       if (cfg->cap & PIXMA_CAP_GRAY)
406         {
407           ss->mode_list[i] = SANE_I18N ("Negative gray");
408           ss->mode_map[i] = PIXMA_SCAN_MODE_NEGATIVE_GRAY;
409           i++;
410         }
411     }
412   if (tpu && (cfg->cap & PIXMA_CAP_TPUIR) == PIXMA_CAP_TPUIR)
413     {
414       ss->mode_list[i] = SANE_I18N ("Infrared");
415       ss->mode_map[i] = PIXMA_SCAN_MODE_TPUIR;
416       i++;
417     }
418   if (!tpu && (cfg->cap & PIXMA_CAP_48BIT))
419     {
420       ss->mode_list[i] = SANE_I18N ("48 bits color");
421       ss->mode_map[i] = PIXMA_SCAN_MODE_COLOR_48;
422       i++;
423       if (cfg->cap & PIXMA_CAP_GRAY)
424         {
425           ss->mode_list[i] = SANE_I18N ("16 bits gray");
426           ss->mode_map[i] = PIXMA_SCAN_MODE_GRAY_16;
427           i++;
428         }
429     }
430   if (!tpu && (cfg->cap & PIXMA_CAP_LINEART))
431     {
432       ss->mode_list[i] = SANE_VALUE_SCAN_MODE_LINEART;
433       ss->mode_map[i] = PIXMA_SCAN_MODE_LINEART;
434       i++;
435     }
436   /* terminate mode_list and mode_map */
437   ss->mode_list[i] = 0;
438   ss->mode_map[i] = 0;
439 }
440 
441 /* create dynamic dpi_list
442  * ss: scanner device */
443 static void
create_dpi_list(pixma_sane_t * ss)444 create_dpi_list (pixma_sane_t * ss)
445 {
446   const pixma_config_t *cfg;
447   int i, j;
448   int min;
449   unsigned min_dpi;
450   unsigned max_dpi;
451 
452   cfg = pixma_get_config (ss->s);
453 
454   /* get min/max dpi */
455   max_dpi = cfg->xdpi;
456   min_dpi = 75;
457   if (ss->source_map[OVAL (opt_source).w] == PIXMA_SOURCE_TPU
458       && ss->mode_map[OVAL (opt_mode).w] == PIXMA_SCAN_MODE_TPUIR)
459   { /* IR mode */
460     /*PDBG (pixma_dbg (4, "*create_dpi_list***** TPUIR mode\n"));*/
461     min_dpi = (cfg->tpuir_min_dpi) ? cfg->tpuir_min_dpi : 75;
462     max_dpi = (cfg->tpuir_max_dpi) ? cfg->tpuir_max_dpi : cfg->xdpi;
463   }
464   else if (ss->source_map[OVAL (opt_source).w] == PIXMA_SOURCE_TPU
465             || ss->source_map[OVAL (opt_source).w] == PIXMA_SOURCE_ADF
466             || ss->source_map[OVAL (opt_source).w] == PIXMA_SOURCE_ADFDUP)
467   { /* ADF / TPU mode */
468     /*PDBG (pixma_dbg (4, "*create_dpi_list***** ADF/TPU mode\n"));*/
469     min_dpi = (cfg->adftpu_min_dpi) ? cfg->adftpu_min_dpi : 75;
470     max_dpi = (cfg->adftpu_max_dpi) ? cfg->adftpu_max_dpi : cfg->xdpi;
471   }
472   else if (ss->source_map[OVAL (opt_source).w] == PIXMA_SOURCE_FLATBED
473             && (ss->mode_map[OVAL (opt_mode).w] == PIXMA_SCAN_MODE_COLOR_48
474                 || ss->mode_map[OVAL (opt_mode).w] == PIXMA_SCAN_MODE_GRAY_16))
475   { /* 48 bits flatbed */
476     /*PDBG (pixma_dbg (4, "*create_dpi_list***** 48 bits flatbed mode\n"));*/
477     min_dpi = (cfg->min_xdpi_16) ? cfg->min_xdpi_16 : 75;
478   }
479 
480   /* set j for min. dpi
481    *  75 dpi: j = 0
482    * 150 dpi: j = 1 \
483    * 300 dpi: j = 2 |--> from cfg->adftpu_min_dpi or cfg->tpuir_min_dpi
484    * 600 dpi: j = 3 /
485    * */
486   j = -1;
487   min = min_dpi / 75;
488   do
489   {
490     j++;
491     min >>= 1;
492   }
493   while (min > 0);
494 
495   /* create dpi_list
496    * use j for min. dpi */
497   i = 0;
498   do
499     {
500       i++; j++;
501       ss->dpi_list[i] = 75 * (1 << (j - 1));    /* 75 x 2^(j-1) */
502     }
503   while ((unsigned) ss->dpi_list[i] < max_dpi);
504   ss->dpi_list[0] = i;
505   /*PDBG (pixma_dbg (4, "*create_dpi_list***** min_dpi = %d, max_dpi = %d\n", min_dpi, max_dpi));*/
506 }
507 
508 
509 static void
create_calibrate_list(pixma_sane_t * ss)510 create_calibrate_list (pixma_sane_t * ss)
511 {
512   int i = 0;
513   ss->calibrate_list[i] = SANE_I18N ("Once");
514   ss->calibrate_map[i] = PIXMA_CALIBRATE_ONCE;
515   i++;
516   ss->calibrate_list[i] = SANE_I18N ("Always");
517   ss->calibrate_map[i] = PIXMA_CALIBRATE_ALWAYS;
518   i++;
519   ss->calibrate_list[i] = SANE_I18N ("Never");
520   ss->calibrate_map[i] = PIXMA_CALIBRATE_NEVER;
521   i++;
522 }
523 
524 static void
select_value_from_list(pixma_sane_t * ss,SANE_Int n,void * v,SANE_Int * info)525 select_value_from_list (pixma_sane_t * ss, SANE_Int n, void *v,
526 			SANE_Int * info)
527 {
528   SANE_Option_Descriptor *sod = &SOD (n);
529   SANE_Word *va = (SANE_Word *) v;
530   const SANE_Word *list = sod->constraint.word_list;
531   int i, j, nmemb;
532 
533   nmemb = sod->size / sizeof (SANE_Word);
534   for (i = 0; i < nmemb; i++)
535     {
536       SANE_Word value = va[i];
537       SANE_Word mindelta = abs (value - list[1]);
538       SANE_Word nearest = list[1];
539       for (j = 2; j <= list[0]; j++)
540         {
541           SANE_Word delta = abs (value - list[j]);
542           if (delta < mindelta)
543             {
544               mindelta = delta;
545               nearest = list[j];
546             }
547           if (mindelta == 0)
548             break;
549         }
550       if (va[i] != nearest)
551         {
552           va[i] = nearest;
553           *info |= SANE_INFO_INEXACT;
554         }
555     }
556 }
557 
558 static SANE_Status
control_scalar_option(pixma_sane_t * ss,SANE_Int n,SANE_Action a,void * v,SANE_Int * info)559 control_scalar_option (pixma_sane_t * ss, SANE_Int n, SANE_Action a, void *v,
560 		       SANE_Int * info)
561 {
562   option_descriptor_t *opt = &(OPT_IN_CTX[n]);
563   SANE_Word val;
564 
565   /* PDBG (pixma_dbg (4, "*control_scalar_option***** n = %u, a = %u\n", n, a)); */
566 
567   switch (a)
568     {
569     case SANE_ACTION_GET_VALUE:
570       switch (opt->sod.type)
571         {
572         case SANE_TYPE_BOOL:
573         case SANE_TYPE_INT:
574         case SANE_TYPE_FIXED:
575           *(SANE_Word *) v = opt->val.w;
576           break;
577         default:
578           return SANE_STATUS_UNSUPPORTED;
579         }
580       return SANE_STATUS_GOOD;
581 
582     case SANE_ACTION_SET_VALUE:
583       switch (opt->sod.type)
584         {
585         case SANE_TYPE_BOOL:
586           val = *(SANE_Word *) v;
587           if (val != SANE_TRUE && val != SANE_FALSE)
588             return SANE_STATUS_INVAL;
589           opt->val.w = val;
590           break;
591         case SANE_TYPE_INT:
592         case SANE_TYPE_FIXED:
593           if (opt->sod.constraint_type == SANE_CONSTRAINT_RANGE)
594             clamp_value (ss, n, v, info);
595           else if (opt->sod.constraint_type == SANE_CONSTRAINT_WORD_LIST)
596             select_value_from_list (ss, n, v, info);
597           opt->val.w = *(SANE_Word *) v;
598           break;
599         default:
600           return SANE_STATUS_UNSUPPORTED;
601         }
602       *info |= opt->info;
603       return SANE_STATUS_GOOD;
604 
605     case SANE_ACTION_SET_AUTO:
606       switch (opt->sod.type)
607         {
608         case SANE_TYPE_BOOL:
609         case SANE_TYPE_INT:
610         case SANE_TYPE_FIXED:
611           opt->val.w = opt->def.w;
612           break;
613         default:
614           return SANE_STATUS_UNSUPPORTED;
615         }
616       *info |= opt->info;
617       return SANE_STATUS_GOOD;
618     }
619   return SANE_STATUS_UNSUPPORTED;
620 }
621 
622 static SANE_Status
control_string_option(pixma_sane_t * ss,SANE_Int n,SANE_Action a,void * v,SANE_Int * info)623 control_string_option (pixma_sane_t * ss, SANE_Int n, SANE_Action a, void *v,
624 		       SANE_Int * info)
625 {
626   option_descriptor_t *opt = &(OPT_IN_CTX[n]);
627   const SANE_String_Const *slist = opt->sod.constraint.string_list;
628   SANE_String str = (SANE_String) v;
629 
630   /* PDBG (pixma_dbg (4, "*control_string_option***** n = %u, a = %u\n", n, a)); */
631 
632   if (opt->sod.constraint_type == SANE_CONSTRAINT_NONE)
633     {
634       switch (a)
635         {
636         case SANE_ACTION_GET_VALUE:
637           strcpy (str, opt->val.s);
638           break;
639         case SANE_ACTION_SET_AUTO:
640           str = opt->def.s;
641           /* fall through */
642         case SANE_ACTION_SET_VALUE:
643           strncpy (opt->val.s, str, opt->sod.size - 1);
644           *info |= opt->info;
645           break;
646         }
647       return SANE_STATUS_GOOD;
648     }
649   else
650     {
651       int i;
652 
653       switch (a)
654         {
655         case SANE_ACTION_GET_VALUE:
656           strcpy (str, slist[opt->val.w]);
657           break;
658         case SANE_ACTION_SET_AUTO:
659           str = opt->def.ptr;
660           /* fall through */
661         case SANE_ACTION_SET_VALUE:
662           i = 0;
663           while (slist[i] && strcasecmp (str, slist[i]) != 0)
664             i++;
665           if (!slist[i])
666             return SANE_STATUS_INVAL;
667           if (strcmp (slist[i], str) != 0)
668             {
669               strcpy (str, slist[i]);
670               *info |= SANE_INFO_INEXACT;
671             }
672           opt->val.w = i;
673           *info |= opt->info;
674           break;
675         }
676       return SANE_STATUS_GOOD;
677     }
678 }
679 
680 static SANE_Status
control_option(pixma_sane_t * ss,SANE_Int n,SANE_Action a,void * v,SANE_Int * info)681 control_option (pixma_sane_t * ss, SANE_Int n,
682 		SANE_Action a, void *v, SANE_Int * info)
683 {
684   SANE_Option_Descriptor *sod = &SOD (n);
685   int result, i;
686   const pixma_config_t *cfg;
687   SANE_Int dummy;
688 
689   /* info may be null, better to set a dummy here then test everywhere */
690   if (info == NULL)
691     info = &dummy;
692 
693   cfg = pixma_get_config (ss->s);
694 
695   /* PDBG (pixma_dbg (4, "*control_option***** n = %u, a = %u\n", n, a)); */
696 
697   /* first deal with options that require special treatment */
698   result = SANE_STATUS_UNSUPPORTED;
699   switch (n)
700     {
701       case opt_gamma_table:
702         {
703           int table_size = sod->size / sizeof (SANE_Word);
704           int byte_cnt = table_size == 1024 ? 2 : 1;
705 
706           switch (a)
707             {
708             case SANE_ACTION_SET_VALUE:
709               PDBG (pixma_dbg (4, "*control_option***** opt_gamma_table: SANE_ACTION_SET_VALUE with %d values ***** \n", table_size));
710               clamp_value (ss, n, v, info);
711               if (byte_cnt == 1)
712                 {
713                   for (i = 0; i < table_size; i++)
714                     ss->gamma_table[i] = *((SANE_Int *) v + i);
715                 }
716               else
717                 {
718                   for (i = 0; i < table_size; i++)
719                     {
720                       ss->gamma_table[i * 2] = *((SANE_Int *) v + i);
721                       ss->gamma_table[i * 2 + 1] = *((uint8_t *)((SANE_Int *) v + i) + 1);
722                     }
723                 }
724               /* PDBG (pixma_hexdump (4, (uint8_t *)v, table_size * 4)); */
725               /* PDBG (pixma_hexdump (4, ss->gamma_table, table_size * byte_cnt)); */
726               break;
727             case SANE_ACTION_GET_VALUE:
728               PDBG (pixma_dbg (4, "*control_option***** opt_gamma_table: SANE_ACTION_GET_VALUE ***** \n"));
729               if (byte_cnt == 1)
730                 {
731                   for (i = 0; i < table_size; i++)
732                     *((SANE_Int *) v + i) = ss->gamma_table[i];
733                 }
734               else
735                 {
736                   for (i = 0; i < table_size; i++)
737                     {
738                       *((SANE_Int *) v + i) = ss->gamma_table[i * 2];
739                       *((uint8_t *)((SANE_Int *) v + i) + 1) = ss->gamma_table[i * 2 + 1];
740                     }
741                 }
742               break;
743             case SANE_ACTION_SET_AUTO:
744               PDBG (pixma_dbg (4, "*control_option***** opt_gamma_table: SANE_ACTION_SET_AUTO with gamma=%f ***** \n",
745                                SANE_UNFIX (OVAL (opt_gamma).w)));
746               pixma_fill_gamma_table (SANE_UNFIX (OVAL (opt_gamma).w),
747                                       ss->gamma_table, table_size);
748               /* PDBG (pixma_hexdump (4, ss->gamma_table, table_size * byte_cnt)); */
749               break;
750             default:
751               return SANE_STATUS_UNSUPPORTED;
752             }
753           return SANE_STATUS_GOOD;
754         }
755 
756       case opt_button_update:
757         if (a == SANE_ACTION_SET_VALUE)
758           {
759             update_button_state (ss, info);
760             return SANE_STATUS_GOOD;
761           }
762         else
763           {
764             return SANE_STATUS_INVAL;
765           }
766         break;
767       case opt_button_1:
768       case opt_button_2:
769       case opt_original:
770       case opt_target:
771       case opt_scan_resolution:
772       case opt_document_type:
773       case opt_adf_status:
774       case opt_adf_orientation:
775         /* poll scanner if option is not cached */
776         if (! ss->button_option_is_cached[ BUTTON_GROUP_INDEX(n) ] )
777           update_button_state (ss, info);
778         /* mark this option as read */
779         ss->button_option_is_cached[  BUTTON_GROUP_INDEX(n) ] = 0;
780     }
781 
782   /* now deal with getting and setting of options */
783   switch (SOD (n).type)
784     {
785     case SANE_TYPE_BOOL:
786     case SANE_TYPE_INT:
787     case SANE_TYPE_FIXED:
788       result = control_scalar_option (ss, n, a, v, info);
789       break;
790     case SANE_TYPE_STRING:
791       result = control_string_option (ss, n, a, v, info);
792       break;
793     case SANE_TYPE_BUTTON:
794     case SANE_TYPE_GROUP:
795       PDBG (pixma_dbg (1, "BUG:control_option():Unhandled option\n"));
796       result = SANE_STATUS_INVAL;
797       break;
798     }
799   if (result != SANE_STATUS_GOOD)
800     return result;
801 
802   /* deal with dependencies between options */
803   switch (n)
804     {
805     case opt_custom_gamma:
806       if (a == SANE_ACTION_SET_VALUE || a == SANE_ACTION_SET_AUTO)
807         {
808           if (enable_option (ss, opt_gamma_table, OVAL (opt_custom_gamma).b))
809             *info |= SANE_INFO_RELOAD_OPTIONS;
810           if (OVAL (opt_custom_gamma).b)
811             sane_control_option (ss, opt_gamma_table, SANE_ACTION_SET_AUTO,
812                                  NULL, NULL);
813 
814         }
815       break;
816     case opt_gamma:
817       if (a == SANE_ACTION_SET_VALUE || a == SANE_ACTION_SET_AUTO)
818         {
819           int table_size = SOD (opt_gamma_table).size / sizeof(SANE_Word);
820           PDBG (pixma_dbg (4, "*control_option***** gamma = %f *\n",
821                            SANE_UNFIX (OVAL (opt_gamma).w)));
822           PDBG (pixma_dbg (4, "*control_option***** table size = %d *\n",
823                            (int)(SOD (opt_gamma_table).size / sizeof (SANE_Word))));
824           pixma_fill_gamma_table (SANE_UNFIX (OVAL (opt_gamma).w),
825                                   ss->gamma_table, table_size);
826           /* PDBG (pixma_hexdump (4, ss->gamma_table,
827                                table_size == 1024 ? 2048 : table_size)); */
828         }
829       break;
830     case opt_mode:
831       if (cfg->cap & (PIXMA_CAP_48BIT|PIXMA_CAP_LINEART|PIXMA_CAP_TPUIR)
832           && (a == SANE_ACTION_SET_VALUE || a == SANE_ACTION_SET_AUTO))
833         { /* new mode selected: Color, Gray, ... */
834           /* PDBG (pixma_dbg (4, "*control_option***** mode = %u *\n",
835                            ss->mode_map[OVAL (opt_mode).w])); */
836           /* recreate dynamic lists */
837           create_dpi_list (ss);
838           if (ss->mode_map[OVAL (opt_mode).w] == PIXMA_SCAN_MODE_LINEART)
839             { /* lineart */
840               enable_option (ss, opt_threshold, SANE_TRUE);
841               enable_option (ss, opt_threshold_curve, SANE_TRUE);
842             }
843           else
844             { /* all other modes */
845               enable_option (ss, opt_threshold, SANE_FALSE);
846               enable_option (ss, opt_threshold_curve, SANE_FALSE);
847             }
848           *info |= SANE_INFO_RELOAD_OPTIONS;
849         }
850       break;
851     case opt_source:
852       if ((cfg->cap & (PIXMA_CAP_ADF|PIXMA_CAP_ADFDUP|PIXMA_CAP_TPU))
853           && (a == SANE_ACTION_SET_VALUE || a == SANE_ACTION_SET_AUTO))
854         {
855           /* new source selected: flatbed, ADF, TPU, ... */
856           pixma_scan_mode_t curr_mode = ss->mode_map[OVAL (opt_mode).w];
857           SANE_Word curr_res = OVAL (opt_resolution).w;
858 
859           /* recreate dynamic lists */
860           create_mode_list (ss);
861           create_dpi_list (ss);
862 
863           /*
864            * Check to see if the mode and res are still valid.
865            * Replace with default mode or closest res if not.
866            *
867            */
868           for (SANE_Int mode_idx = 0;; mode_idx++)
869             {
870               if (!ss->mode_list[mode_idx])
871                 {
872                   OVAL (opt_mode).w = 0;
873                   break;
874                 }
875               if (curr_mode == ss->mode_map[mode_idx])
876                 {
877                   OVAL (opt_mode).w = mode_idx;
878                   break;
879                 }
880             }
881 
882           for (SANE_Int res_idx = 1;; res_idx++)
883             {
884               if (res_idx > ss->dpi_list[0])
885                 {
886                   OVAL (opt_resolution).w = ss->dpi_list[1];
887                   break;
888                 }
889               if (ss->dpi_list[res_idx] >= curr_res)
890                 {
891                   OVAL (opt_resolution).w = ss->dpi_list[res_idx];
892                   break;
893                 }
894             }
895 
896           if (ss->mode_map[OVAL (opt_mode).w] == PIXMA_SCAN_MODE_LINEART)
897             { /* lineart */
898               enable_option (ss, opt_threshold, SANE_TRUE);
899               enable_option (ss, opt_threshold_curve, SANE_TRUE);
900             }
901           else
902             { /* all other modes */
903               enable_option (ss, opt_threshold, SANE_FALSE);
904               enable_option (ss, opt_threshold_curve, SANE_FALSE);
905             }
906           if (cfg->cap & (PIXMA_CAP_ADF_WAIT))
907             { /* adf-wait */
908               enable_option (ss, opt_adf_wait, SANE_TRUE);
909             }
910           else
911             { /* disable adf-wait */
912               enable_option (ss, opt_adf_wait, SANE_FALSE);
913             }
914           *info |= SANE_INFO_RELOAD_OPTIONS;
915         }
916       break;
917     }
918 
919   return result;
920 }
921 
922 #ifndef NDEBUG
923 static void
print_scan_param(int level,const pixma_scan_param_t * sp)924 print_scan_param (int level, const pixma_scan_param_t * sp)
925 {
926   pixma_dbg (level, "Scan parameters\n");
927   pixma_dbg (level, "  line_size=%"PRIu64" image_size=%"PRIu64" channels=%u depth=%u\n",
928 	     sp->line_size, sp->image_size, sp->channels, sp->depth);
929   pixma_dbg (level, "  dpi=%ux%u offset=(%u,%u) dimension=%ux%u\n",
930 	     sp->xdpi, sp->ydpi, sp->x, sp->y, sp->w, sp->h);
931   pixma_dbg (level, "  gamma=%f gamma_table=%p source=%d\n", sp->gamma,
932              (void *) sp->gamma_table, sp->source);
933   pixma_dbg (level, "  adf-wait=%d\n", sp->adf_wait);
934 }
935 #endif
936 
937 static int
calc_scan_param(pixma_sane_t * ss,pixma_scan_param_t * sp)938 calc_scan_param (pixma_sane_t * ss, pixma_scan_param_t * sp)
939 {
940   int x1, y1, x2, y2;
941   int error;
942 
943   memset (sp, 0, sizeof (*sp));
944 
945   sp->channels = (OVAL (opt_mode).w == 0) ? 3 : 1;
946   sp->depth = (OVAL (opt_mode).w == 2) ? 1 : 8;
947   sp->xdpi = sp->ydpi = OVAL (opt_resolution).w;
948 
949 #define PIXEL(x,dpi) (int)((SANE_UNFIX(x) / 25.4 * (dpi)) + 0.5)
950   x1 = PIXEL (OVAL (opt_tl_x).w, sp->xdpi);
951   x2 = PIXEL (OVAL (opt_br_x).w, sp->xdpi);
952   if (x2 < x1)
953     {
954       int temp = x1;
955       x1 = x2;
956       x2 = temp;
957     }
958   y1 = PIXEL (OVAL (opt_tl_y).w, sp->ydpi);
959   y2 = PIXEL (OVAL (opt_br_y).w, sp->ydpi);
960   if (y2 < y1)
961     {
962       int temp = y1;
963       y1 = y2;
964       y2 = temp;
965     }
966 #undef PIXEL
967   sp->x = x1;
968   sp->y = y1;
969   sp->w = x2 - x1;
970   sp->h = y2 - y1;
971   if (sp->w == 0)
972     sp->w = 1;
973   if (sp->h == 0)
974     sp->h = 1;
975   sp->tpu_offset_added = 0;
976 
977   sp->gamma = SANE_UNFIX (OVAL (opt_gamma).w);
978   sp->gamma_table = ss->gamma_table;
979   sp->source = ss->source_map[OVAL (opt_source).w];
980   sp->mode = ss->mode_map[OVAL (opt_mode).w];
981   sp->adf_pageid = ss->page_count;
982   sp->threshold = 2.55 * OVAL (opt_threshold).w;
983   sp->threshold_curve = OVAL (opt_threshold_curve).w;
984   sp->adf_wait = OVAL (opt_adf_wait).w;
985   sp->calibrate = ss->calibrate_map[OVAL (opt_calibrate).w];
986 
987   error = pixma_check_scan_param (ss->s, sp);
988   if (error < 0)
989     {
990       PDBG (pixma_dbg (1, "BUG:calc_scan_param() failed %d\n", error));
991       PDBG (print_scan_param (1, sp));
992     }
993   return error;
994 }
995 
996 static void
init_option_descriptors(pixma_sane_t * ss)997 init_option_descriptors (pixma_sane_t * ss)
998 {
999   const pixma_config_t *cfg;
1000   int i;
1001 
1002   cfg = pixma_get_config (ss->s);
1003 
1004   /* PDBG (pixma_dbg (4, "*init_option_descriptors*****\n")); */
1005 
1006   /* setup range for the scan area. */
1007   ss->xrange.min = SANE_FIX (0);
1008   ss->xrange.max = SANE_FIX (cfg->width / 75.0 * 25.4);
1009   ss->xrange.quant = SANE_FIX (0);
1010 
1011   ss->yrange.min = SANE_FIX (0);
1012   ss->yrange.max = SANE_FIX (cfg->height / 75.0 * 25.4);
1013   ss->yrange.quant = SANE_FIX (0);
1014 
1015   /* mode_list and source_list were already NULL-terminated,
1016    * because the whole pixma_sane_t was cleared during allocation. */
1017 
1018   /* setup available mode. */
1019   create_mode_list (ss);
1020 
1021   /* setup dpi up to the value supported by the scanner. */
1022   create_dpi_list (ss);
1023 
1024   /* setup paper source */
1025   i = 0;
1026   ss->source_list[i] = SANE_I18N ("Flatbed");
1027   ss->source_map[i] = PIXMA_SOURCE_FLATBED;
1028   i++;
1029   if (cfg->cap & PIXMA_CAP_ADF)
1030     {
1031       ss->source_list[i] = SANE_I18N ("Automatic Document Feeder");
1032       ss->source_map[i] = PIXMA_SOURCE_ADF;
1033       i++;
1034     }
1035   if ((cfg->cap & PIXMA_CAP_ADFDUP) == PIXMA_CAP_ADFDUP)
1036     {
1037       ss->source_list[i] = SANE_I18N ("ADF Duplex");
1038       ss->source_map[i] = PIXMA_SOURCE_ADFDUP;
1039       i++;
1040     }
1041   if (cfg->cap & PIXMA_CAP_TPU)
1042     {
1043       ss->source_list[i] = SANE_I18N ("Transparency Unit");
1044       ss->source_map[i] = PIXMA_SOURCE_TPU;
1045       i++;
1046     }
1047 
1048   create_calibrate_list (ss);
1049 
1050   build_option_descriptors (ss);
1051 
1052   /* Enable options that are available only in some scanners. */
1053   if (cfg->cap & PIXMA_CAP_GAMMA_TABLE)
1054     {
1055       SANE_Option_Descriptor *sod = &SOD (opt_gamma_table);
1056 
1057       /* some scanners have a large gamma table with 4096 entries */
1058       if (cfg->cap & PIXMA_CAP_GT_4096)
1059         {
1060           static const SANE_Range constraint_gamma_table_4096 = { 0,0xff,0 };
1061           sod->desc = SANE_I18N("Gamma-correction table with 4096 entries. In color mode this option equally affects the red, green, and blue channels simultaneously (i.e., it is an intensity gamma table).");
1062           sod->size = 4096 * sizeof(SANE_Word);
1063           sod->constraint.range = &constraint_gamma_table_4096;
1064         }
1065 
1066       /* PDBG (pixma_dbg (4, "*%s***** PIXMA_CAP_GAMMA_TABLE ***** \n",
1067                        __func__)); */
1068       /* PDBG (pixma_dbg (4, "%s: gamma_table_contraint.max = %d\n",
1069                        __func__,  sod->constraint.range->max)); */
1070       /* PDBG (pixma_dbg (4, "%s: gamma_table_size = %d\n",
1071                        __func__,  sod->size / sizeof(SANE_Word))); */
1072 
1073       /* activate option gamma */
1074       enable_option (ss, opt_gamma, SANE_TRUE);
1075       sane_control_option (ss, opt_gamma, SANE_ACTION_SET_AUTO,
1076                            NULL, NULL);
1077       /* activate option custom gamma table */
1078       enable_option (ss, opt_custom_gamma, SANE_TRUE);
1079       sane_control_option (ss, opt_custom_gamma, SANE_ACTION_SET_AUTO,
1080                            NULL, NULL);
1081     }
1082   enable_option (ss, opt_button_controlled,
1083 		 ((cfg->cap & PIXMA_CAP_EVENTS) != 0));
1084 }
1085 
1086 /* Writing to reader_ss outside reader_process() is a BUG! */
1087 static pixma_sane_t *reader_ss = NULL;
1088 
1089 static void
reader_signal_handler(int sig)1090 reader_signal_handler (int sig)
1091 {
1092   if (reader_ss)
1093     {
1094       reader_ss->reader_stop = SANE_TRUE;
1095       /* reader process is ended by SIGTERM, so no cancel in this case */
1096       if (sig != SIGTERM)
1097         pixma_cancel (reader_ss->s);
1098     }
1099 }
1100 
1101 static int
write_all(pixma_sane_t * ss,void * buf_,size_t size)1102 write_all (pixma_sane_t * ss, void *buf_, size_t size)
1103 {
1104   uint8_t *buf = (uint8_t *) buf_;
1105   int count;
1106 
1107   while (size != 0 && !ss->reader_stop)
1108     {
1109       count = write (ss->wpipe, buf, size);
1110       if (count == -1 && errno != EINTR)
1111 	break;
1112       if (count == -1 && errno == EINTR)
1113 	continue;
1114       buf += count;
1115       size -= count;
1116     }
1117   return buf - (uint8_t *) buf_;
1118 }
1119 
1120 /* NOTE: reader_loop() runs either in a separate thread or process. */
1121 static SANE_Status
reader_loop(pixma_sane_t * ss)1122 reader_loop (pixma_sane_t * ss)
1123 {
1124   void *buf;
1125   unsigned bufsize;
1126   int count = 0;
1127 
1128   PDBG (pixma_dbg (3, "Reader task started\n"));
1129   /*bufsize = ss->sp.line_size + 1;*/	/* XXX: "odd" bufsize for testing pixma_read_image() */
1130   bufsize = ss->sp.line_size;   /* bufsize EVEN needed by Xsane for 48 bits depth */
1131   buf = malloc (bufsize);
1132   if (!buf)
1133     {
1134       count = PIXMA_ENOMEM;
1135       goto done;
1136     }
1137 
1138   count = pixma_activate_connection (ss->s);
1139   if (count < 0)
1140     goto done;
1141 
1142   pixma_enable_background (ss->s, 1);
1143   if (OVAL (opt_button_controlled).b && ss->page_count == 0)
1144     {
1145       int start = 0;
1146 #ifndef NDEBUG
1147       pixma_dbg (1, "==== Button-controlled scan mode is enabled.\n");
1148       pixma_dbg (1, "==== To proceed, press 'SCAN' or 'COLOR' button. "
1149 		 "To cancel, press 'GRAY' or 'END' button.\n");
1150 #endif
1151       while (pixma_wait_event (ss->s, 10) != 0)
1152         {
1153         }
1154       while (!start)
1155         {
1156           uint32_t events;
1157           if (ss->reader_stop)
1158             {
1159               count = PIXMA_ECANCELED;
1160               goto done;
1161             }
1162           events = pixma_wait_event (ss->s, 1000);
1163           switch (events & ~PIXMA_EV_ACTION_MASK)
1164             {
1165             case PIXMA_EV_BUTTON1:
1166               start = 1;
1167               break;
1168             case PIXMA_EV_BUTTON2:
1169               count = PIXMA_ECANCELED;
1170               goto done;
1171             }
1172         }
1173     }
1174   count = pixma_scan (ss->s, &ss->sp);
1175   if (count >= 0)
1176     {
1177       while ((count = pixma_read_image (ss->s, buf, bufsize)) > 0)
1178         {
1179           if (write_all (ss, buf, count) != count)
1180             pixma_cancel (ss->s);
1181         }
1182     }
1183 
1184 done:
1185   pixma_enable_background (ss->s, 0);
1186   pixma_deactivate_connection (ss->s);
1187   free (buf);
1188   close (ss->wpipe);
1189   ss->wpipe = -1;
1190   if (count >= 0)
1191     {
1192       PDBG (pixma_dbg (3, "Reader task terminated\n"));
1193     }
1194   else
1195     {
1196       PDBG (pixma_dbg
1197 	    (2, "Reader task terminated: %s\n", pixma_strerror (count)));
1198     }
1199   return map_error (count);
1200 }
1201 
1202 static int
reader_process(void * arg)1203 reader_process (void *arg)
1204 {
1205   pixma_sane_t *ss = (pixma_sane_t *) arg;
1206   struct SIGACTION sa;
1207 
1208   reader_ss = ss;
1209   memset (&sa, 0, sizeof (sa));
1210   sigemptyset (&sa.sa_mask);
1211   sa.sa_handler = reader_signal_handler;
1212   /* FIXME: which signal else? */
1213   sigaction (SIGHUP, &sa, NULL);
1214   sigaction (SIGINT, &sa, NULL);
1215   sigaction (SIGPIPE, &sa, NULL);
1216   sigaction (SIGTERM, &sa, NULL);
1217   close (ss->rpipe);
1218   ss->rpipe = -1;
1219   return reader_loop (ss);
1220 }
1221 
1222 static int
reader_thread(void * arg)1223 reader_thread (void *arg)
1224 {
1225   pixma_sane_t *ss = (pixma_sane_t *) arg;
1226 #ifdef USE_PTHREAD
1227   /* Block SIGPIPE. We will handle this in reader_loop() by checking
1228      ss->reader_stop and the return value from write(). */
1229   sigset_t sigs;
1230   sigemptyset (&sigs);
1231   sigaddset (&sigs, SIGPIPE);
1232   pthread_sigmask (SIG_BLOCK, &sigs, NULL);
1233 #endif /* USE_PTHREAD */
1234   return reader_loop (ss);
1235 }
1236 
1237 static SANE_Pid
terminate_reader_task(pixma_sane_t * ss,int * exit_code)1238 terminate_reader_task (pixma_sane_t * ss, int *exit_code)
1239 {
1240   SANE_Pid result, pid;
1241   int status = 0;
1242 
1243   pid = ss->reader_taskid;
1244   if (!sanei_thread_is_valid (pid))
1245     return pid;
1246   if (sanei_thread_is_forked ())
1247     {
1248       sanei_thread_kill (pid);
1249     }
1250   else
1251     {
1252       ss->reader_stop = SANE_TRUE;
1253 /*      pixma_cancel (ss->s);   What is this for ? Makes end-of-scan buggy => removing */
1254     }
1255   result = sanei_thread_waitpid (pid, &status);
1256   sanei_thread_invalidate (ss->reader_taskid);
1257 
1258   if (ss->sp.source != PIXMA_SOURCE_ADF && ss->sp.source != PIXMA_SOURCE_ADFDUP)
1259     ss->idle = SANE_TRUE;
1260 
1261   if (result == pid)
1262     {
1263       if (exit_code)
1264 	      *exit_code = status;
1265       return pid;
1266     }
1267   else
1268     {
1269       PDBG (pixma_dbg (1, "WARNING:waitpid() failed %s\n", strerror (errno)));
1270       sanei_thread_invalidate (pid);
1271       return pid;
1272     }
1273 }
1274 
1275 static int
start_reader_task(pixma_sane_t * ss)1276 start_reader_task (pixma_sane_t * ss)
1277 {
1278   int fds[2];
1279   SANE_Pid pid;
1280   int is_forked;
1281 
1282   if (ss->rpipe != -1 || ss->wpipe != -1)
1283     {
1284       PDBG (pixma_dbg
1285 	    (1, "BUG:rpipe = %d, wpipe = %d\n", ss->rpipe, ss->wpipe));
1286       close (ss->rpipe);
1287       close (ss->wpipe);
1288       ss->rpipe = -1;
1289       ss->wpipe = -1;
1290     }
1291   if (sanei_thread_is_valid (ss->reader_taskid))
1292     {
1293       PDBG (pixma_dbg
1294 	    (1, "BUG:reader_taskid(%ld) != -1\n", (long) ss->reader_taskid));
1295       terminate_reader_task (ss, NULL);
1296     }
1297   if (pipe (fds) == -1)
1298     {
1299       PDBG (pixma_dbg (1, "ERROR:start_reader_task():pipe() failed %s\n",
1300 		       strerror (errno)));
1301       return PIXMA_ENOMEM;
1302     }
1303   ss->rpipe = fds[0];
1304   ss->wpipe = fds[1];
1305   ss->reader_stop = SANE_FALSE;
1306 
1307   is_forked = sanei_thread_is_forked ();
1308   if (is_forked)
1309     {
1310       pid = sanei_thread_begin (reader_process, ss);
1311       if (sanei_thread_is_valid (pid))
1312         {
1313           close (ss->wpipe);
1314           ss->wpipe = -1;
1315         }
1316     }
1317   else
1318     {
1319       pid = sanei_thread_begin (reader_thread, ss);
1320     }
1321   if (!sanei_thread_is_valid (pid))
1322     {
1323       close (ss->wpipe);
1324       close (ss->rpipe);
1325       ss->wpipe = -1;
1326       ss->rpipe = -1;
1327       PDBG (pixma_dbg (1, "ERROR:unable to start reader task\n"));
1328       return PIXMA_ENOMEM;
1329     }
1330   PDBG (pixma_dbg (3, "Reader task id=%ld (%s)\n", (long) pid,
1331 		   (is_forked) ? "forked" : "threaded"));
1332   ss->reader_taskid = pid;
1333   return 0;
1334 }
1335 
1336 /* libJPEG API callbacks */
1337 static void
jpeg_init_source(j_decompress_ptr __sane_unused__ cinfo)1338 jpeg_init_source(j_decompress_ptr __sane_unused__ cinfo)
1339 {
1340   /* No-op */
1341 }
1342 
1343 static void
jpeg_term_source(j_decompress_ptr __sane_unused__ cinfo)1344 jpeg_term_source(j_decompress_ptr __sane_unused__ cinfo)
1345 {
1346   /* No-op */
1347 }
1348 
1349 static boolean
jpeg_fill_input_buffer(j_decompress_ptr cinfo)1350 jpeg_fill_input_buffer(j_decompress_ptr cinfo)
1351 {
1352   pixma_jpeg_src_mgr *mgr = (pixma_jpeg_src_mgr *)cinfo->src;
1353   int size;
1354   int retry;
1355 
1356   for (retry = 0; retry < 30; retry ++ )
1357     {
1358       size = read (mgr->s->rpipe, mgr->buffer, 1024);
1359       if (size == 0)
1360         {
1361           return FALSE;
1362         }
1363       else if (size < 0)
1364         {
1365           sleep (1);
1366         }
1367       else
1368         {
1369           mgr->jpeg.next_input_byte = mgr->buffer;
1370           mgr->jpeg.bytes_in_buffer = size;
1371           return TRUE;
1372         }
1373     }
1374 
1375   return FALSE;
1376 }
1377 
1378 static void
jpeg_skip_input_data(j_decompress_ptr cinfo,long num_bytes)1379 jpeg_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
1380 {
1381   pixma_jpeg_src_mgr *mgr = (pixma_jpeg_src_mgr *)cinfo->src;
1382 
1383   if (num_bytes > 0)
1384     {
1385       /* Read and throw away extra */
1386       while (num_bytes > (long)mgr->jpeg.bytes_in_buffer)
1387         {
1388            num_bytes -= (long)mgr->jpeg.bytes_in_buffer;
1389            jpeg_fill_input_buffer(cinfo);
1390         }
1391 
1392       /* Update jpeg info structure with leftover */
1393       mgr->jpeg.next_input_byte += (size_t) num_bytes;
1394       mgr->jpeg.bytes_in_buffer -= (size_t) num_bytes;
1395     }
1396 }
1397 
1398 /* Pixma JPEG reader helpers */
1399 static SANE_Status
pixma_jpeg_start(pixma_sane_t * s)1400 pixma_jpeg_start(pixma_sane_t *s)
1401 {
1402   pixma_jpeg_src_mgr *mgr;
1403 
1404   s->jpeg_cinfo.err = jpeg_std_error(&s->jpeg_err);
1405 
1406   jpeg_create_decompress(&s->jpeg_cinfo);
1407 
1408   s->jpeg_cinfo.src = (struct jpeg_source_mgr *)(*s->jpeg_cinfo.mem->alloc_small)((j_common_ptr)&s->jpeg_cinfo,
1409                               JPOOL_PERMANENT, sizeof(pixma_jpeg_src_mgr));
1410 
1411   memset(s->jpeg_cinfo.src, 0, sizeof(pixma_jpeg_src_mgr));
1412 
1413   mgr = (pixma_jpeg_src_mgr *)s->jpeg_cinfo.src;
1414   mgr->s = s;
1415 
1416   mgr->buffer = (JOCTET *)(*s->jpeg_cinfo.mem->alloc_small)((j_common_ptr)&s->jpeg_cinfo,
1417                                                   JPOOL_PERMANENT,
1418                                                   1024 * sizeof(JOCTET));
1419 
1420   mgr->jpeg.init_source = jpeg_init_source;
1421   mgr->jpeg.fill_input_buffer = jpeg_fill_input_buffer;
1422   mgr->jpeg.skip_input_data = jpeg_skip_input_data;
1423   mgr->jpeg.resync_to_restart = jpeg_resync_to_restart;
1424   mgr->jpeg.term_source = jpeg_term_source;
1425   mgr->jpeg.bytes_in_buffer = 0;
1426   mgr->jpeg.next_input_byte = NULL;
1427 
1428   s->jpeg_header_seen = 0;
1429 
1430   return SANE_STATUS_GOOD;
1431 }
1432 
1433 static SANE_Status
pixma_jpeg_read_header(pixma_sane_t * s)1434 pixma_jpeg_read_header(pixma_sane_t *s)
1435 {
1436   pixma_jpeg_src_mgr *src = (pixma_jpeg_src_mgr *)s->jpeg_cinfo.src;
1437 
1438   if (jpeg_read_header(&s->jpeg_cinfo, TRUE))
1439     {
1440       s->jdst = sanei_jpeg_jinit_write_ppm(&s->jpeg_cinfo);
1441 
1442       if (jpeg_start_decompress(&s->jpeg_cinfo))
1443         {
1444           int size;
1445 
1446           DBG(3, "%s: w: %d, h: %d, components: %d\n",
1447                   __func__,
1448                   s->jpeg_cinfo.output_width, s->jpeg_cinfo.output_height,
1449                   s->jpeg_cinfo.output_components);
1450 
1451           size = s->jpeg_cinfo.output_width * s->jpeg_cinfo.output_components * 1;
1452 
1453           src->linebuffer = (*s->jpeg_cinfo.mem->alloc_large)((j_common_ptr)&s->jpeg_cinfo,
1454                   JPOOL_PERMANENT, size);
1455 
1456           src->linebuffer_size = 0;
1457           src->linebuffer_index = 0;
1458 
1459           s->jpeg_header_seen = 1;
1460 
1461           return SANE_STATUS_GOOD;
1462         }
1463       else
1464         {
1465           DBG(0, "%s: decompression failed\n", __func__);
1466           return SANE_STATUS_IO_ERROR;
1467         }
1468     }
1469   else
1470     {
1471       DBG(0, "%s: cannot read JPEG header\n", __func__);
1472       return SANE_STATUS_IO_ERROR;
1473     }
1474 }
1475 
1476 static void
pixma_jpeg_finish(pixma_sane_t * ss)1477 pixma_jpeg_finish(pixma_sane_t *ss)
1478 {
1479   jpeg_destroy_decompress(&ss->jpeg_cinfo);
1480 }
1481 
1482 static void
pixma_jpeg_read(pixma_sane_t * ss,SANE_Byte * data,SANE_Int max_length,SANE_Int * length)1483 pixma_jpeg_read(pixma_sane_t *ss, SANE_Byte *data,
1484            SANE_Int max_length, SANE_Int *length)
1485 {
1486   struct jpeg_decompress_struct *cinfo = &ss->jpeg_cinfo;
1487   pixma_jpeg_src_mgr *src = (pixma_jpeg_src_mgr *)cinfo->src;
1488 
1489   int l;
1490 
1491   *length = 0;
1492 
1493   /* copy from line buffer if available */
1494   if (src->linebuffer_size && src->linebuffer_index < src->linebuffer_size)
1495     {
1496       *length = src->linebuffer_size - src->linebuffer_index;
1497 
1498       if (*length > max_length)
1499         *length = max_length;
1500 
1501       memcpy(data, src->linebuffer + src->linebuffer_index, *length);
1502              src->linebuffer_index += *length;
1503 
1504       return;
1505     }
1506 
1507   if (cinfo->output_scanline >= cinfo->output_height)
1508     {
1509       *length = 0;
1510       return;
1511     }
1512 
1513   /* scanlines of decompressed data will be in ss->jdst->buffer
1514    * only one line at time is supported
1515    */
1516 
1517   l = jpeg_read_scanlines(cinfo, ss->jdst->buffer, 1);
1518   if (l == 0)
1519     return;
1520 
1521   /* from ss->jdst->buffer to linebuffer
1522    * linebuffer holds width * bytesperpixel
1523    */
1524 
1525   (*ss->jdst->put_pixel_rows)(cinfo, ss->jdst, 1, (char *)src->linebuffer);
1526 
1527   *length = ss->sp.w * ss->sp.channels;
1528   /* Convert RGB into grayscale */
1529   if (ss->sp.channels == 1)
1530     {
1531       unsigned int i;
1532       unsigned char *d = (unsigned char *)src->linebuffer;
1533       unsigned char *s = (unsigned char *)src->linebuffer;
1534       for (i = 0; i < ss->sp.w; i++)
1535         {
1536           /* Using BT.709 luma formula, fixed-point */
1537           int sum = ( s[0]*2126 + s[1]*7152 + s[2]*722 );
1538           *d = sum / 10000;
1539           d ++;
1540           s += 3;
1541         }
1542     }
1543 
1544   /* Maybe pack into lineary binary image */
1545   if (ss->sp.depth == 1)
1546     {
1547       *length /= 8;
1548       unsigned int i;
1549       unsigned char *d = (unsigned char *)src->linebuffer;
1550       unsigned char *s = (unsigned char *)src->linebuffer;
1551       unsigned char b = 0;
1552       for (i = 1; i < ss->sp.w + 1; i++)
1553         {
1554           if (*(s++) > 127)
1555             b = (b << 1) | 0;
1556          else
1557             b = (b << 1) | 1;
1558           if ((i % 8) == 0)
1559             *(d++) = b;
1560         }
1561     }
1562 
1563   src->linebuffer_size = *length;
1564   src->linebuffer_index = 0;
1565 
1566   if (*length > max_length)
1567     *length = max_length;
1568 
1569   memcpy(data, src->linebuffer + src->linebuffer_index, *length);
1570         src->linebuffer_index += *length;
1571 }
1572 
1573 
1574 
1575 static SANE_Status
read_image(pixma_sane_t * ss,void * buf,unsigned size,int * readlen)1576 read_image (pixma_sane_t * ss, void *buf, unsigned size, int *readlen)
1577 {
1578   int count, status;
1579 
1580   if (readlen)
1581     *readlen = 0;
1582   if (ss->image_bytes_read >= ss->sp.image_size)
1583     return SANE_STATUS_EOF;
1584 
1585   do
1586     {
1587       if (ss->cancel)
1588         /* ss->rpipe has already been closed by sane_cancel(). */
1589         return SANE_STATUS_CANCELLED;
1590       if (ss->sp.mode_jpeg && !ss->jpeg_header_seen)
1591         {
1592           status = pixma_jpeg_read_header(ss);
1593           if (status != SANE_STATUS_GOOD)
1594             {
1595               close (ss->rpipe);
1596               pixma_jpeg_finish(ss);
1597               ss->rpipe = -1;
1598               if (sanei_thread_is_valid (terminate_reader_task (ss, &status))
1599                 && status != SANE_STATUS_GOOD)
1600                 {
1601                   return status;
1602                 }
1603               else
1604                 {
1605                   /* either terminate_reader_task failed or
1606                      rpipe was closed but we expect more data */
1607                   return SANE_STATUS_IO_ERROR;
1608                 }
1609             }
1610         }
1611 
1612       if (ss->sp.mode_jpeg)
1613         {
1614           count = -1;
1615           pixma_jpeg_read(ss, buf, size, &count);
1616         }
1617       else
1618         count = read (ss->rpipe, buf, size);
1619     }
1620   while (count == -1 && errno == EINTR);
1621 
1622   if (count == -1)
1623     {
1624       if (errno == EAGAIN)
1625         return SANE_STATUS_GOOD;
1626       if (!ss->cancel)
1627         {
1628           PDBG (pixma_dbg (1, "WARNING:read_image():read() failed %s\n",
1629                strerror (errno)));
1630         }
1631       close (ss->rpipe);
1632       ss->rpipe = -1;
1633       terminate_reader_task (ss, NULL);
1634       if (ss->sp.mode_jpeg)
1635         pixma_jpeg_finish(ss);
1636       return SANE_STATUS_IO_ERROR;
1637     }
1638 
1639   /* here count >= 0 */
1640   ss->image_bytes_read += count;
1641   if (ss->image_bytes_read > ss->sp.image_size)
1642     {
1643       PDBG (pixma_dbg (1, "BUG:ss->image_bytes_read > ss->sp.image_size\n"));
1644     }
1645   if (ss->image_bytes_read >= ss->sp.image_size)
1646     {
1647       close (ss->rpipe);
1648       ss->rpipe = -1;
1649       terminate_reader_task (ss, NULL);
1650       if (ss->sp.mode_jpeg)
1651         pixma_jpeg_finish(ss);
1652     }
1653   else if (count == 0)
1654     {
1655       PDBG (pixma_dbg (3, "read_image():reader task closed the pipe:%"
1656 		       PRIu64" bytes received, %"PRIu64" bytes expected\n",
1657 		       ss->image_bytes_read, ss->sp.image_size));
1658       close (ss->rpipe);
1659       if (ss->sp.mode_jpeg)
1660         pixma_jpeg_finish(ss);
1661       ss->rpipe = -1;
1662       if (sanei_thread_is_valid (terminate_reader_task (ss, &status))
1663       	  && status != SANE_STATUS_GOOD)
1664         {
1665           return status;
1666         }
1667       else
1668         {
1669           /* either terminate_reader_task failed or
1670              rpipe was closed but we expect more data */
1671           return SANE_STATUS_IO_ERROR;
1672         }
1673     }
1674   if (readlen)
1675     *readlen = count;
1676   return SANE_STATUS_GOOD;
1677 }
1678 
1679 
1680 /*******************************************************************
1681  ** SANE API
1682  *******************************************************************/
1683 SANE_Status
sane_init(SANE_Int * version_code,SANE_Auth_Callback authorize)1684 sane_init (SANE_Int * version_code, SANE_Auth_Callback authorize)
1685 {
1686   int status, myversion, i;
1687   SANEI_Config config;
1688 
1689   UNUSED (authorize);
1690 
1691   if (!version_code)
1692     return SANE_STATUS_INVAL;
1693   myversion = 100 * PIXMA_VERSION_MAJOR + PIXMA_VERSION_MINOR;
1694   *version_code = SANE_VERSION_CODE (SANE_CURRENT_MAJOR, SANE_CURRENT_MINOR, myversion);
1695   DBG_INIT ();
1696   sanei_thread_init ();
1697   pixma_set_debug_level (DBG_LEVEL);
1698 
1699   PDBG(pixma_dbg(2, "pixma is compiled %s pthread support.\n",
1700                    (sanei_thread_is_forked () ? "without" : "with")));
1701 
1702   for (i = 0; i < MAX_CONF_DEVICES; i++)
1703     conf_devices[i] = NULL;
1704 
1705   config.count = 0;
1706   config.descriptors = NULL;
1707   config.values = NULL;
1708 
1709   if (sanei_configure_attach(PIXMA_CONFIG_FILE, &config,
1710                              config_attach_pixma, NULL) != SANE_STATUS_GOOD)
1711     PDBG(pixma_dbg(2, "Could not read pixma configuration file: %s\n",
1712                    PIXMA_CONFIG_FILE));
1713 
1714   status = pixma_init ();
1715   if (status < 0)
1716     {
1717       PDBG (pixma_dbg (2, "pixma_init() failed %s\n", pixma_strerror (status)));
1718     }
1719   return map_error (status);
1720 }
1721 
1722 void
sane_exit(void)1723 sane_exit (void)
1724 {
1725   while (first_scanner)
1726     sane_close (first_scanner);
1727   cleanup_device_list ();
1728   pixma_cleanup ();
1729   sanei_usb_exit ();
1730 }
1731 
1732 SANE_Status
sane_get_devices(const SANE_Device *** device_list,SANE_Bool local_only)1733 sane_get_devices (const SANE_Device *** device_list, SANE_Bool local_only)
1734 {
1735   if (!device_list)
1736     return SANE_STATUS_INVAL;
1737   find_scanners (local_only);
1738   *device_list = dev_list;
1739   return (dev_list) ? SANE_STATUS_GOOD : SANE_STATUS_NO_MEM;
1740 }
1741 
1742 SANE_Status
sane_open(SANE_String_Const name,SANE_Handle * h)1743 sane_open (SANE_String_Const name, SANE_Handle * h)
1744 {
1745   unsigned i, j, nscanners;
1746   int error = 0;
1747   pixma_sane_t *ss = NULL;
1748   const pixma_config_t *cfg;
1749 
1750   if (!name || !h)
1751     return SANE_STATUS_INVAL;
1752 
1753   *h = NULL;
1754   nscanners = pixma_find_scanners (conf_devices, SANE_FALSE);
1755   if (nscanners == 0)
1756     return SANE_STATUS_INVAL;
1757 
1758   /* also get device id if we replay a xml file
1759    * otherwise name contains the xml filename
1760    * and further replay will fail  */
1761   if (name[0] == '\0' || strstr (name, ".xml"))
1762     name = pixma_get_device_id (0);
1763 
1764   /* Have we already opened the scanner? */
1765   for (ss = first_scanner; ss; ss = ss->next)
1766     {
1767       if (strcmp (pixma_get_string (ss->s, PIXMA_STRING_ID), name) == 0)
1768         {
1769           /* We have already opened it! */
1770           return SANE_STATUS_DEVICE_BUSY;
1771         }
1772     }
1773 
1774   i = 0;
1775   while (strcmp (pixma_get_device_id (i), name) != 0)
1776     {
1777       if (++i >= nscanners)
1778 	      return SANE_STATUS_INVAL;
1779     }
1780   cfg = pixma_get_device_config (i);
1781   if ((cfg->cap & PIXMA_CAP_EXPERIMENT) != 0)
1782     {
1783 #ifndef NDEBUG
1784       pixma_dbg (1, "WARNING:"
1785 		 "Experimental backend CAN DAMAGE your hardware!\n");
1786       if (getenv_atoi ("PIXMA_EXPERIMENT", 0) == 0)
1787         {
1788           pixma_dbg (1, "Experimental SANE backend for %s is disabled "
1789                "by default.\n", pixma_get_device_model (i));
1790           pixma_dbg (1, "To enable it, set the environment variable "
1791                "PIXMA_EXPERIMENT to non-zero.\n");
1792           return SANE_STATUS_UNSUPPORTED;
1793         }
1794 #else
1795       return SANE_STATUS_UNSUPPORTED;
1796 #endif
1797     }
1798 
1799   ss = (pixma_sane_t *) calloc (1, sizeof (*ss));
1800   if (!ss)
1801     return SANE_STATUS_NO_MEM;
1802   ss->next = first_scanner;
1803   first_scanner = ss;
1804   sanei_thread_initialize (ss->reader_taskid);
1805   ss->wpipe = -1;
1806   ss->rpipe = -1;
1807   ss->idle = SANE_TRUE;
1808   ss->scanning = SANE_FALSE;
1809   ss->sp.frontend_cancel = SANE_FALSE;
1810   for (j=0; j < BUTTON_GROUP_SIZE; j++)
1811     ss->button_option_is_cached[j] = 0;
1812   error = pixma_open (i, &ss->s);
1813   if (error < 0)
1814     {
1815       sane_close (ss);
1816       return map_error (error);
1817     }
1818   pixma_enable_background (ss->s, 0);
1819   init_option_descriptors (ss);
1820   *h = ss;
1821   return SANE_STATUS_GOOD;
1822 }
1823 
1824 void
sane_close(SANE_Handle h)1825 sane_close (SANE_Handle h)
1826 {
1827   pixma_sane_t **p, *ss;
1828 
1829   for (p = &first_scanner; *p && *p != (pixma_sane_t *) h; p = &((*p)->next))
1830     {
1831     }
1832   if (!(*p))
1833     return;
1834   ss = *p;
1835   sane_cancel (ss);
1836   pixma_close (ss->s);
1837   *p = ss->next;
1838   free (ss);
1839 }
1840 
1841 const SANE_Option_Descriptor *
sane_get_option_descriptor(SANE_Handle h,SANE_Int n)1842 sane_get_option_descriptor (SANE_Handle h, SANE_Int n)
1843 {
1844   DECL_CTX;
1845 
1846   if (ss && 0 <= n && n < opt_last)
1847     return &SOD (n);
1848   return NULL;
1849 }
1850 
1851 SANE_Status
sane_control_option(SANE_Handle h,SANE_Int n,SANE_Action a,void * v,SANE_Int * i)1852 sane_control_option (SANE_Handle h, SANE_Int n,
1853 		     SANE_Action a, void *v, SANE_Int * i)
1854 {
1855   DECL_CTX;
1856   SANE_Int info = 0;
1857   int error;
1858   option_descriptor_t *opt;
1859 
1860   if (i)
1861     *i = 0;
1862   if (!ss)
1863     return SANE_STATUS_INVAL;
1864   if (n < 0 || n >= opt_last)
1865     return SANE_STATUS_UNSUPPORTED;
1866   if (!ss->idle && a != SANE_ACTION_GET_VALUE)
1867     {
1868       PDBG (pixma_dbg (3, "Warning: !idle && !SANE_ACTION_GET_VALUE\n"));
1869       if (ss->sp.source != PIXMA_SOURCE_ADF && ss->sp.source != PIXMA_SOURCE_ADFDUP)
1870         return SANE_STATUS_INVAL;
1871     }
1872 
1873   opt = &(OPT_IN_CTX[n]);
1874   if (!SANE_OPTION_IS_ACTIVE (opt->sod.cap))
1875     return SANE_STATUS_INVAL;
1876   switch (a)
1877     {
1878     case SANE_ACTION_SET_VALUE:
1879       if ((opt->sod.type != SANE_TYPE_BUTTON && !v) ||
1880           !SANE_OPTION_IS_SETTABLE (opt->sod.cap))
1881         return SANE_STATUS_INVAL;	/* or _UNSUPPORTED? */
1882       break;
1883     case SANE_ACTION_SET_AUTO:
1884       if (!(opt->sod.cap & SANE_CAP_AUTOMATIC) ||
1885           !SANE_OPTION_IS_SETTABLE (opt->sod.cap))
1886         return SANE_STATUS_INVAL;	/* or _UNSUPPORTED? */
1887       break;
1888     case SANE_ACTION_GET_VALUE:
1889       if (!v || !(opt->sod.cap & SANE_CAP_SOFT_DETECT))
1890         return SANE_STATUS_INVAL;	/* or _UNSUPPORTED? */
1891       break;
1892     default:
1893       return SANE_STATUS_UNSUPPORTED;
1894     }
1895 
1896   error = control_option (ss, n, a, v, &info);
1897   if (error == SANE_STATUS_GOOD && i)
1898     *i = info;
1899   return error;
1900 }
1901 
1902 SANE_Status
sane_get_parameters(SANE_Handle h,SANE_Parameters * p)1903 sane_get_parameters (SANE_Handle h, SANE_Parameters * p)
1904 {
1905   DECL_CTX;
1906   pixma_scan_param_t temp, *sp;
1907 
1908   if (!ss || !p)
1909     return SANE_STATUS_INVAL;
1910 
1911   if (!ss->idle)
1912     {
1913       sp = &ss->sp;		/* sp is calculated in sane_start() */
1914     }
1915   else
1916     {
1917       calc_scan_param (ss, &temp);
1918       sp = &temp;
1919     }
1920   p->format = (sp->channels == 3) ? SANE_FRAME_RGB : SANE_FRAME_GRAY;
1921   p->last_frame = SANE_TRUE;
1922   p->lines = sp->h;
1923   p->depth = sp->depth;
1924   p->pixels_per_line = sp->w;
1925   /* p->bytes_per_line = sp->line_size; NOTE: It should work this way, but it doesn't. No SANE frontend can cope with this. */
1926   p->bytes_per_line = (sp->w * sp->channels * sp->depth) / 8;
1927   return SANE_STATUS_GOOD;
1928 }
1929 
1930 SANE_Status
sane_start(SANE_Handle h)1931 sane_start (SANE_Handle h)
1932 {
1933   DECL_CTX;
1934   int error = 0;
1935 
1936   if (!ss)
1937     return SANE_STATUS_INVAL;
1938   if (!ss->idle && ss->scanning)
1939     {
1940       PDBG (pixma_dbg (3, "Warning in Sane_start: !idle && scanning. idle=%d, ss->scanning=%d\n",
1941                        ss->idle, ss->scanning));
1942       if (ss->sp.source != PIXMA_SOURCE_ADF && ss->sp.source != PIXMA_SOURCE_ADFDUP)
1943         return SANE_STATUS_INVAL;
1944     }
1945 
1946   ss->cancel = SANE_FALSE;
1947   if (ss->idle ||
1948       ss->source_map[OVAL (opt_source).w] == PIXMA_SOURCE_FLATBED ||
1949       ss->source_map[OVAL (opt_source).w] == PIXMA_SOURCE_TPU)
1950     ss->page_count = 0;	/* start from idle state or scan from flatbed or TPU */
1951   else
1952     ss->page_count++;
1953   if (calc_scan_param (ss, &ss->sp) < 0)
1954     return SANE_STATUS_INVAL;
1955 
1956   /* Prepare the JPEG decompressor, if needed */
1957   if (ss->sp.mode_jpeg)
1958     {
1959       SANE_Status status;
1960       status = pixma_jpeg_start(ss);
1961       if (status != SANE_STATUS_GOOD)
1962         {
1963           PDBG (pixma_dbg(1, "%s: pixma_jpeg_start: %s\n", __func__, sane_strstatus(status)) );
1964           return status;
1965         }
1966     }
1967 
1968   ss->image_bytes_read = 0;
1969   /* TODO: Check paper here in sane_start(). A function like
1970      pixma_get_status() is needed. */
1971   error = start_reader_task (ss);
1972   if (error >= 0)
1973     {
1974       ss->output_line_size = (ss->sp.w * ss->sp.channels * ss->sp.depth) / 8;
1975       ss->byte_pos_in_line = 0;
1976       ss->last_read_status = SANE_STATUS_GOOD;
1977       ss->scanning = SANE_TRUE;
1978       ss->idle = SANE_FALSE;
1979       if (ss->sp.mode_jpeg && !ss->jpeg_header_seen)
1980         {
1981           SANE_Status status;
1982           status = pixma_jpeg_read_header(ss);
1983           if (status != SANE_STATUS_GOOD)
1984             {
1985               close (ss->rpipe);
1986               pixma_jpeg_finish(ss);
1987               ss->rpipe = -1;
1988               if (sanei_thread_is_valid (terminate_reader_task (ss, &error))
1989                 && error != SANE_STATUS_GOOD)
1990                 {
1991                   return error;
1992                 }
1993             }
1994         }
1995     }
1996   return map_error (error);
1997 }
1998 
1999 SANE_Status
sane_read(SANE_Handle h,SANE_Byte * buf,SANE_Int maxlen,SANE_Int * len)2000 sane_read (SANE_Handle h, SANE_Byte * buf, SANE_Int maxlen, SANE_Int * len)
2001 {
2002   DECL_CTX;
2003   int sum, n;
2004   /* Due to 32 pixels alignment, sizeof(temp) is to be greater than:
2005    * max(nchannels) * max (sp.line_size - output_line_size)
2006    * so currently: 3 * 32 = 96  for better end line cropping efficiency */
2007   SANE_Byte temp[100];
2008   SANE_Status status;
2009 
2010   if (len)
2011     *len = 0;
2012   if (!ss || !buf || !len)
2013     return SANE_STATUS_INVAL;
2014   if (ss->cancel)
2015     return SANE_STATUS_CANCELLED;
2016   if ((ss->idle)
2017       && (ss->sp.source == PIXMA_SOURCE_ADF || ss->sp.source == PIXMA_SOURCE_ADFDUP))
2018     return SANE_STATUS_INVAL;
2019   if (!ss->scanning)
2020     return ss->last_read_status;
2021 
2022   status = SANE_STATUS_GOOD;
2023   /* CCD scanners use software lineart
2024    * the scanner must scan 24 bit color or 8 bit grayscale for one bit lineart */
2025   if ((ss->sp.line_size - ((ss->sp.software_lineart == 1) ? (ss->output_line_size * 8) : ss->output_line_size)) == 0)
2026     {
2027       status = read_image (ss, buf, maxlen, &sum);
2028     }
2029   else
2030     {
2031       /* FIXME: Because there is no frontend that can cope with padding at
2032          the end of line, we've to remove it here in the backend! */
2033       PDBG (pixma_dbg (1, "*sane_read***** Warning: padding may cause incomplete scan results\n"));
2034       sum = 0;
2035       while (sum < maxlen)
2036         {
2037           if (ss->byte_pos_in_line < ss->output_line_size)
2038             {
2039               n = ss->output_line_size - ss->byte_pos_in_line;
2040               if ((maxlen - sum) < n)
2041                 n = maxlen - sum;
2042               status = read_image (ss, buf, n, &n);
2043               if (n == 0)
2044                 break;
2045               sum += n;
2046               buf += n;
2047               ss->byte_pos_in_line += n;
2048             }
2049           else
2050             {
2051               /* skip padding */
2052               n = ss->sp.line_size - ss->byte_pos_in_line;
2053               if (n > (int) sizeof (temp))
2054                 {
2055                   PDBG (pixma_dbg (3, "Inefficient skip buffer. Should be %d\n", n));
2056                   n = sizeof (temp);
2057                 }
2058               status = read_image (ss, temp, n, &n);
2059               if (n == 0)
2060                 break;
2061               ss->byte_pos_in_line += n;
2062               if (ss->byte_pos_in_line == ss->sp.line_size)
2063                 ss->byte_pos_in_line = 0;
2064              }
2065         }
2066     }
2067   if (ss->cancel)
2068     status = SANE_STATUS_CANCELLED;
2069   else if ((status == SANE_STATUS_GOOD || status == SANE_STATUS_EOF) &&
2070 	   sum > 0)
2071     {
2072       *len = sum;
2073       status = SANE_STATUS_GOOD;
2074     }
2075   ss->scanning = (status == SANE_STATUS_GOOD);
2076   ss->last_read_status = status;
2077   return status;
2078 }
2079 
2080 void
sane_cancel(SANE_Handle h)2081 sane_cancel (SANE_Handle h)
2082 {
2083   DECL_CTX;
2084 
2085   if (!ss)
2086     return;
2087   ss->cancel = SANE_TRUE;
2088   ss->sp.frontend_cancel = SANE_TRUE;
2089   if (ss->idle)
2090     return;
2091   close (ss->rpipe);
2092   if (ss->sp.mode_jpeg)
2093     pixma_jpeg_finish(ss);
2094   ss->rpipe = -1;
2095   terminate_reader_task (ss, NULL);
2096   ss->idle = SANE_TRUE;
2097 }
2098 
2099 SANE_Status
sane_set_io_mode(SANE_Handle h,SANE_Bool m)2100 sane_set_io_mode (SANE_Handle h, SANE_Bool m)
2101 {
2102   DECL_CTX;
2103 
2104   if (!ss || ss->idle || ss->rpipe == -1)
2105     return SANE_STATUS_INVAL;
2106 #ifdef HAVE_FCNTL_H
2107   PDBG (pixma_dbg (2, "Setting %sblocking mode\n", (m) ? "non-" : ""));
2108   if (fcntl (ss->rpipe, F_SETFL, (m) ? O_NONBLOCK : 0) == -1)
2109     {
2110       PDBG (pixma_dbg
2111 	    (1, "WARNING:fcntl(F_SETFL) failed %s\n", strerror (errno)));
2112       return SANE_STATUS_UNSUPPORTED;
2113     }
2114   return SANE_STATUS_GOOD;
2115 #else
2116   return (m) ? SANE_STATUS_UNSUPPORTED : SANE_STATUS_GOOD;
2117 #endif
2118 }
2119 
2120 SANE_Status
sane_get_select_fd(SANE_Handle h,SANE_Int * fd)2121 sane_get_select_fd (SANE_Handle h, SANE_Int * fd)
2122 {
2123   DECL_CTX;
2124 
2125   *fd = -1;
2126   if (!ss || !fd || ss->idle || ss->rpipe == -1)
2127     return SANE_STATUS_INVAL;
2128   *fd = ss->rpipe;
2129   return SANE_STATUS_GOOD;
2130 }
2131 
2132 /* CAUTION!
2133  * Remove generated files pixma_sane_options.[ch] after editing SANE option
2134  * descriptors below OR do a 'make clean' OR manually generate them as described
2135  * below.
2136  * However, make drops the circular dependency and the files won't be generated
2137  * again (see merge request sane-project/backends!491).
2138 
2139 BEGIN SANE_Option_Descriptor
2140 
2141 rem -------------------------------------------
2142 type group
2143   title Scan mode
2144 
2145 type int resolution
2146   unit dpi
2147   constraint @word_list = ss->dpi_list
2148   default 75
2149   title @SANE_TITLE_SCAN_RESOLUTION
2150   desc  @SANE_DESC_SCAN_RESOLUTION
2151   cap soft_select soft_detect automatic
2152   info reload_params
2153 
2154 type string mode[30]
2155   constraint @string_list = ss->mode_list
2156   default @s = SANE_VALUE_SCAN_MODE_COLOR
2157   title @SANE_TITLE_SCAN_MODE
2158   desc  @SANE_DESC_SCAN_MODE
2159   cap soft_select soft_detect automatic
2160   info reload_params
2161 
2162 type string source[30]
2163   constraint @string_list = ss->source_list
2164   title @SANE_TITLE_SCAN_SOURCE
2165   desc  Selects the scan source (such as a document-feeder). Set source before mode and resolution. Resets mode and resolution to auto values.
2166   default Flatbed
2167   cap soft_select soft_detect
2168 
2169 type bool button-controlled
2170   title Button-controlled scan
2171   desc When enabled, scan process will not start immediately. To proceed, press \"SCAN\" button (for MP150) or \"COLOR\" button (for other models). To cancel, press \"GRAY\" button.
2172   default SANE_FALSE
2173   cap soft_select soft_detect inactive
2174 
2175 rem -------------------------------------------
2176 type group
2177   title Gamma
2178 
2179 type bool custom-gamma
2180   default SANE_FALSE
2181   title @SANE_TITLE_CUSTOM_GAMMA
2182   desc  @SANE_DESC_CUSTOM_GAMMA
2183   cap soft_select soft_detect automatic inactive
2184 
2185 type int gamma-table[1024]
2186   constraint (0,0xffff,0)
2187   title @SANE_TITLE_GAMMA_VECTOR
2188   desc  Gamma-correction table with 1024 entries. In color mode this option equally affects the red, green, and blue channels simultaneously (i.e., it is an intensity gamma table).
2189   cap soft_select soft_detect automatic inactive
2190 
2191 type fixed gamma
2192   default AUTO_GAMMA
2193   constraint (0.3,5,0)
2194   title Gamma function exponent
2195   desc  Changes intensity of midtones
2196   cap soft_select soft_detect automatic inactive
2197 
2198 rem -------------------------------------------
2199 type group
2200   title Geometry
2201 
2202 type fixed tl-x
2203   unit mm
2204   default 0
2205   constraint @range = &ss->xrange
2206   title @SANE_TITLE_SCAN_TL_X
2207   desc  @SANE_DESC_SCAN_TL_X
2208   cap soft_select soft_detect automatic
2209   info reload_params
2210 
2211 type fixed tl-y
2212   unit mm
2213   default 0
2214   constraint @range = &ss->yrange
2215   title @SANE_TITLE_SCAN_TL_Y
2216   desc  @SANE_DESC_SCAN_TL_Y
2217   cap soft_select soft_detect automatic
2218   info reload_params
2219 
2220 type fixed br-x
2221   unit mm
2222   default _MAX
2223   constraint @range = &ss->xrange
2224   title @SANE_TITLE_SCAN_BR_X
2225   desc  @SANE_DESC_SCAN_BR_X
2226   cap soft_select soft_detect automatic
2227   info reload_params
2228 
2229 type fixed br-y
2230   unit mm
2231   default _MAX
2232   constraint @range = &ss->yrange
2233   title @SANE_TITLE_SCAN_BR_Y
2234   desc  @SANE_DESC_SCAN_BR_Y
2235   cap soft_select soft_detect automatic
2236   info reload_params
2237 
2238 rem -------------------------------------------
2239 type group
2240   title Buttons
2241 
2242 type button button-update
2243   title Update button state
2244   cap soft_select soft_detect advanced
2245 
2246 type int button-1
2247   default 0
2248   title Button 1
2249   cap soft_detect advanced
2250 
2251 type int button-2
2252   default 0
2253   title Button 2
2254   cap soft_detect advanced
2255 
2256 type int original
2257   default 0
2258   title Type of original to scan
2259   cap soft_detect advanced
2260 
2261 type int target
2262   default 0
2263   title Target operation type
2264   cap soft_detect advanced
2265 
2266 type int scan-resolution
2267   default 0
2268   title Scan resolution
2269   cap soft_detect advanced
2270 
2271 type int document-type
2272   default 0
2273   title Document type
2274   cap soft_detect advanced
2275 
2276 type int adf-status
2277   default 0
2278   title ADF status
2279   cap soft_detect advanced
2280 
2281 type int adf-orientation
2282   default 0
2283   title ADF orientation
2284   cap soft_detect advanced
2285 
2286 rem -------------------------------------------
2287 type group
2288   title Extras
2289 
2290 type int threshold
2291   unit PERCENT
2292   default 50
2293   constraint (0,100,1)
2294   title @SANE_TITLE_THRESHOLD
2295   desc  @SANE_DESC_THRESHOLD
2296   cap soft_select soft_detect automatic inactive
2297 
2298 type int threshold-curve
2299   constraint (0,127,1)
2300   title Threshold curve
2301   desc  Dynamic threshold curve, from light to dark, normally 50-65
2302   cap soft_select soft_detect automatic inactive
2303 
2304 type int adf-wait
2305   default 0
2306   constraint (0,3600,1)
2307   title ADF Waiting Time
2308   desc  When set, the scanner waits up to the specified time in seconds for a new document inserted into the automatic document feeder.
2309   cap soft_select soft_detect automatic inactive
2310 
2311 type string calibrate[30]
2312   constraint @string_list = ss->calibrate_list
2313   title Calibration
2314   desc When to perform scanner calibration. If you choose \"Once\" it will be performed a single time per driver init for single page scans, and for the first page for each ADF scan.
2315   default Once
2316   cap soft_select soft_detect automatic
2317 
2318 rem -------------------------------------------
2319 END SANE_Option_Descriptor
2320 */
2321 
2322 /* pixma_sane_options.c generated by
2323  * scripts/pixma_gen_options.py < pixma.c > pixma_sane_options.c
2324  *
2325  * pixma_sane_options.h generated by
2326  * scripts/pixma_gen_options.py h < pixma.c > pixma_sane_options.h
2327  */
2328 #include "pixma_sane_options.c"
2329