1 /* sane - Scanner Access Now Easy.
2    Copyright (C) 2001-2002 Matthew C. Duggan and Simon Krix
3    This file is part of the SANE package.
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    As a special exception, the authors of SANE give permission for
19    additional uses of the libraries contained in this release of SANE.
20 
21    The exception is that, if you link a SANE library with other files
22    to produce an executable, this does not by itself cause the
23    resulting executable to be covered by the GNU General Public
24    License.  Your use of that executable is in no way restricted on
25    account of linking the SANE library code into it.
26 
27    This exception does not, however, invalidate any other reasons why
28    the executable file might be covered by the GNU General Public
29    License.
30 
31    If you submit changes to SANE to the maintainers to be included in
32    a subsequent release, you agree by submitting the changes that
33    those changes may be distributed with this exception intact.
34 
35    If you write modifications of your own for SANE, it is your choice
36    whether to permit this exception to apply to your modifications.
37    If you do not wish that, delete this exception notice.
38 
39    -----
40 
41    This file is part of the canon_pp backend, supporting Canon FBX30P
42    and NX40P scanners
43    */
44 
45 #ifdef  _AIX
46 #include  <lalloca.h>		/* MUST come first for AIX! */
47 #endif
48 
49 #define BACKEND_NAME canon_pp
50 
51 #define THREE_BITS 0xE0
52 #define TWO_BITS 0xC0
53 #define MM_PER_IN 25.4
54 
55 #ifndef NOSANE
56 #include "../include/sane/config.h"
57 #endif
58 
59 #include  <string.h>
60 #include  <math.h>
61 #include  <unistd.h>
62 #include  <sys/stat.h>
63 #include  <sys/types.h>
64 #include  <stdlib.h>
65 #include  <errno.h>
66 #include  <ieee1284.h>
67 
68 #include  "../include/sane/sane.h"
69 #include  "../include/sane/saneopts.h"
70 
71 #include "canon_pp-dev.h"
72 #include "canon_pp-io.h"
73 #include "canon_pp.h"
74 
75 /* #include  "../include/sane/sanei_pio.h" */
76 #include  "../include/sane/sanei_config.h"
77 #include  "../include/sane/sanei_backend.h"
78 /* #include  "../include/sane/sanei_debug.h" */
79 
80 
81 /* Prototypes */
82 static SANE_Status init_device(struct parport *pp);
83 
84 /* create a calibration file and give it initial values */
85 static int init_cal(char *file);
86 
87 static SANE_Status fix_weights_file(CANONP_Scanner *cs);
88 
89 static SANE_Status detect_mode(CANONP_Scanner *cs);
90 
91 /* Global Variables (ack!) */
92 
93 /* The first device in a linked list of devices */
94 static CANONP_Scanner *first_dev = NULL;
95 /* The default scanner to open */
96 static char *def_scanner = NULL;
97 /* The number of devices */
98 static int num_devices = 0;
99 /* ieee1284 parallel ports */
100 struct parport_list pl;
101 /* leftover from the last read */
102 static SANE_Byte *read_leftover = NULL;
103 /* leftover from the last read */
104 static SANE_Bool force_nibble = SANE_FALSE;
105 
106 /* Constants */
107 
108 /* Colour Modes */
109 static const SANE_String_Const cmodes[] = {
110 	SANE_VALUE_SCAN_MODE_GRAY,
111 	SANE_VALUE_SCAN_MODE_COLOR,
112 	NULL };
113 
114 /* bit depths */
115 static const SANE_String_Const depths[] = { "8", "12", NULL };
116 /* resolutions */
117 static const SANE_Int res300[] = {3, 75, 150, 300};
118 static const SANE_Int res600[] = {4, 75, 150, 300, 600};
119 
120 
121 /*************************************************************************
122  *
123  * sane_init()
124  *
125  * Initialises data for the list of scanners, stored in canon-p.conf.
126  *
127  * Scanners are not sent any commands until sane_open() is called.
128  *
129  *************************************************************************/
130 	SANE_Status
sane_init(SANE_Int * vc,SANE_Auth_Callback cb)131 sane_init (SANE_Int *vc, SANE_Auth_Callback cb)
132 {
133 	SANE_Status status = SANE_STATUS_GOOD;
134 	int i, tmp;
135 	int tmp_im = INITMODE_AUTO;
136 	FILE *fp;
137 	char line[81]; /* plus 1 for a null */
138 	char *tmp_wf, *tmp_port;
139 	CANONP_Scanner *s_tmp;
140 
141 
142 	DBG_INIT();
143 
144 #if defined PACKAGE && defined VERSION
145 	DBG(2, ">> sane_init (version %s null, authorize %s null): " PACKAGE " " VERSION "\n",
146 	    (vc) ? "!=" : "==", (cb) ? "!=" : "==");
147 #endif
148 
149 	if(vc)
150 		*vc = SANE_VERSION_CODE (SANE_CURRENT_MAJOR, V_MINOR, 0);
151 
152 	DBG(2,"sane_init: >> ieee1284_find_ports\n");
153 	/* Find lp ports */
154 	tmp = ieee1284_find_ports(&pl, 0);
155 	DBG(2,"sane_init: %d << ieee1284_find_ports\n", tmp);
156 
157 	if (tmp != E1284_OK)
158 	{
159 		DBG(1,"sane_init: Error trying to get port list\n");
160 		return SANE_STATUS_IO_ERROR;
161 	}
162 
163 
164 	if (pl.portc < 1)
165 	{
166 		DBG(1,"sane_init: Error, no parallel ports found.\n");
167 		return SANE_STATUS_IO_ERROR;
168 	}
169 
170 	DBG(10,"sane_init: %i parallel port(s) found.\n", pl.portc);
171 	/* Setup data structures for each port */
172 	for(i=0; i<pl.portc; i++)
173 	{
174 		DBG(10,"sane_init: port %s\n", pl.portv[i]->name);
175 		status = init_device(pl.portv[i]);
176 		/* Now's a good time to quit if we got an error */
177 		if (status != SANE_STATUS_GOOD) return status;
178 	}
179 
180 	/* This should never be true here */
181 	if (num_devices == 0)
182 		status = SANE_STATUS_IO_ERROR;
183 
184 	/* just to be extra sure, the line will always have an end: */
185 	line[sizeof(line)-1] = '\0';
186 
187 	/*
188 	 * Read information from config file: pixel weight location and default
189 	 * port.
190 	 */
191 	if((fp = sanei_config_open(CANONP_CONFIG_FILE)))
192 	{
193 		while(sanei_config_read(line, sizeof (line) - 1, fp))
194 		{
195 			DBG(100, "sane_init: >%s<\n", line);
196 			if(line[0] == '#')	/* ignore line comments */
197 				continue;
198 			if(!strlen(line))
199 				continue;	/* ignore empty lines */
200 
201 			if(strncmp(line,"calibrate ", 10) == 0)
202 			{
203 				/* warning: pointer trickyness ahead
204 				 * Do not free tmp_port! */
205 				DBG(40, "sane_init: calibrate line, %s\n",
206 						line);
207 				tmp_wf = strdup(line+10);
208 				tmp_port = strstr(tmp_wf, " ");
209 				if ((tmp_port == tmp_wf) || (tmp_port == NULL))
210 				{
211 					/* They have used an old style config
212 					 * file which does not specify scanner
213 					 * Assume first port */
214 					DBG(1, "sane_init: old config line:"
215 							"\"%s\".  Please add "
216 							"a port argument.\n",
217 							line);
218 
219 					/* first_dev should never be null here
220 					 * because we found at least one
221 					 * parallel port above */
222 					first_dev->weights_file = tmp_wf;
223 					DBG(100, "sane_init: Successfully "
224 							"parsed (old) cal, "
225 							"weight file is "
226 							"'%s'.\n", tmp_wf);
227 					continue;
228 
229 				}
230 
231 				/* Now find which scanner wants
232 				 * this calibration file */
233 				s_tmp = first_dev;
234 				DBG(100, "sane_init: Finding scanner on port "
235 						"'%s'\n", tmp_port+1);
236 				while (s_tmp != NULL)
237 				{
238 					if (!strcmp(s_tmp->params.port->name,
239 								tmp_port+1))
240 					{
241 						DBG(100, "sane_init: Found!\n");
242 						/* Now terminate the weight
243 						 * file string */
244 						*tmp_port = '\0';
245 						s_tmp->weights_file = tmp_wf;
246 						DBG(100, "sane_init: Parsed "
247 								"cal, for port"
248 								" '%s', weight"
249 								" file is '%s'"
250 								".\n",
251 								s_tmp->params.
252 								  port->name,
253 								tmp_wf);
254 						break;
255 					}
256 					s_tmp = s_tmp->next;
257 				}
258 				if (s_tmp == NULL)
259 				{
260 					/* we made it all the way through the
261 					 * list and didn't find the port */
262 					free(tmp_wf);
263 					DBG(10, "sane_init: calibrate line is "
264 							"for unknown port!\n");
265 				}
266 				continue;
267 			}
268 
269 
270 			if(strncmp(line,"ieee1284 ", 9) == 0)
271 			{
272 				DBG(100, "sane_init: Successfully parsed "
273 						"default scanner.\n");
274 				/* this will be our default scanner */
275 				def_scanner = strdup(line+9);
276 				continue;
277 			}
278 
279 			if(strncmp(line,"force_nibble", 12) == 0)
280 			{
281 				DBG(100, "sane_init: force_nibble "
282 						"requested.\n");
283 				force_nibble = SANE_TRUE;
284 				continue;
285 			}
286 
287 			if(strncmp(line,"init_mode ", 10) == 0)
288 			{
289 
290 				/* parse what sort of initialisation mode to
291 				 * use */
292 				if (strncmp(line+10, "FB620P", 6) == 0)
293 					tmp_im = INITMODE_20P;
294 				else if (strncmp(line+10, "FB630P", 6) == 0)
295 					tmp_im = INITMODE_30P;
296 				else if (strncmp(line+10, "AUTO", 4) == 0)
297 					tmp_im = INITMODE_AUTO;
298 
299 				/* now work out which port it blongs to */
300 
301 				tmp_port = strstr(line+10, " ");
302 
303 				if (tmp_port == NULL)
304 				{
305 					/* first_dev should never be null here
306 					 * because we found at least one
307 					 * parallel port above */
308 					first_dev->init_mode = tmp_im;
309 					DBG(100, "sane_init: Parsed init-1.\n");
310 					continue;
311 				}
312 
313 
314 				s_tmp = first_dev;
315 				while (s_tmp != NULL)
316 				{
317 					if (!strcmp(s_tmp->params.port->name,
318 								tmp_port+1))
319 					{
320 						s_tmp->init_mode = tmp_im;
321 						DBG(100, "sane_init: Parsed "
322 								"init.\n");
323 						break;
324 					}
325 					s_tmp = s_tmp->next;
326 				}
327 				if (s_tmp == NULL)
328 				{
329 					/* we made it all the way through the
330 					 * list and didn't find the port */
331 					DBG(10, "sane_init: init_mode line is "
332 							"for unknown port!\n");
333 				}
334 
335 				continue;
336 			}
337 			DBG(1, "sane_init: Unknown configuration command!");
338 
339 		}
340 		fclose (fp);
341 	}
342 
343 	/* There should now be a LL of ports starting at first_dev */
344 
345 	for (s_tmp = first_dev; s_tmp != NULL; s_tmp = s_tmp->next)
346 	{
347 		/* Assume there's no scanner present until proven otherwise */
348 		s_tmp->scanner_present = SANE_FALSE;
349 
350 		/* Try to detect if there's a scanner there, and if so,
351 		 * what sort of scanner it is */
352 		status = detect_mode(s_tmp);
353 
354 		if (status != SANE_STATUS_GOOD)
355 		{
356 			DBG(10,"sane_init: Error detecting port mode on %s!\n",
357 					s_tmp->params.port->name);
358 			s_tmp->scanner_present = SANE_FALSE;
359 			continue;
360 		}
361 
362 		/* detect_mode succeeded, so the port is open.  This beholdens
363 		 * us to call ieee1284_close in any of the remaining error
364 		 * cases in this loop. */
365 #if 0
366 		tmp = sanei_canon_pp_detect(s_tmp->params.port,
367 				s_tmp->init_mode);
368 
369 
370 		if (tmp && (s_tmp->ieee1284_mode != M1284_NIBBLE))
371 		{
372 			/* A failure, try again in nibble mode... */
373 			DBG(1, "sane_init: Failed on ECP mode, falling "
374 					"back to nibble mode\n");
375 
376 			s_tmp->ieee1284_mode = M1284_NIBBLE;
377 			sanei_canon_pp_set_ieee1284_mode(s_tmp->ieee1284_mode);
378 			tmp = sanei_canon_pp_detect(s_tmp->params.port,
379 					s_tmp->init_mode);
380 		}
381 		/* still no go? */
382 		if (tmp)
383 		{
384 			DBG(1,"sane_init: couldn't find a scanner on port "
385 					"%s\n", s_tmp->params.port->name);
386 
387 			ieee1284_close(s_tmp->params.port);
388 			continue;
389 		}
390 
391 #endif
392 		/* all signs point to yes, try it out */
393 		if (ieee1284_claim(s_tmp->params.port) != E1284_OK) {
394 			DBG(10, "sane_init: Couldn't claim port %s.\n",
395 				s_tmp->params.port->name);
396 
397 			ieee1284_close(s_tmp->params.port);
398 			continue;
399 		}
400 
401 		DBG(2, "sane_init: >> initialise\n");
402 		tmp = sanei_canon_pp_initialise(&(s_tmp->params),
403 				s_tmp->init_mode);
404 		DBG(2, "sane_init: << %d initialise\n", tmp);
405 		if (tmp) {
406 			DBG(10, "sane_init: Couldn't contact scanner on port "
407 				"%s. Probably no scanner there?\n",
408 				s_tmp->params.port->name);
409 			ieee1284_release(s_tmp->params.port);
410 			ieee1284_close(s_tmp->params.port);
411 			s_tmp->scanner_present = SANE_FALSE;
412 			continue;
413 		}
414 
415 		/* put it back to sleep until we're ready to
416 		 * open for business again - this will only work
417 		 * if we actually have a scanner there! */
418 		DBG(100, "sane_init: And back to sleep again\n");
419 		sanei_canon_pp_sleep_scanner(s_tmp->params.port);
420 
421 		/* leave the port open but not claimed - this is regardless
422 		 * of the return value of initialise */
423 		ieee1284_release(s_tmp->params.port);
424 
425 		/* Finally, we're sure there's a scanner there! Now we
426 		 * just have to load the weights file...*/
427 
428 		if (fix_weights_file(s_tmp) != SANE_STATUS_GOOD) {
429 			DBG(1, "sane_init: Eeek! fix_weights_file failed for "
430 				"scanner on port %s!\n",
431 				s_tmp->params.port->name);
432 			/* non-fatal.. scans will look ugly as sin unless
433 			 * they calibrate */
434 		}
435 
436 		/* Cocked, locked and ready to rock */
437 		s_tmp->hw.model = s_tmp->params.name;
438 		s_tmp->scanner_present = SANE_TRUE;
439 	}
440 
441 	DBG(2, "<< sane_init\n");
442 
443 	return status;
444 }
445 
446 
447 /*************************************************************************
448  *
449  * sane_get_devices()
450  *
451  * Gives a list of devices available.  In our case, that's the linked
452  * list produced by sane_init.
453  *
454  *************************************************************************/
455 	SANE_Status
sane_get_devices(const SANE_Device *** dl,SANE_Bool local)456 sane_get_devices (const SANE_Device ***dl, SANE_Bool local)
457 {
458 	static const SANE_Device **devlist;
459 	CANONP_Scanner *dev;
460 	int i;
461 
462 	DBG(2, ">> sane_get_devices (%p, %d)\n", (const void*)dl, local);
463 
464 	if (dl == NULL)
465 	{
466 		DBG(1, "sane_get_devices: ERROR: devlist pointer is NULL!");
467 		return SANE_STATUS_INVAL;
468 	}
469 
470 	if (devlist != NULL)
471 	{
472 		/* this has been called already */
473 		*dl = devlist;
474 		return SANE_STATUS_GOOD;
475 	}
476 	devlist = malloc((num_devices + 1) * sizeof(*devlist));
477 	if (devlist == NULL)
478 		return SANE_STATUS_NO_MEM;
479 
480 	i = 0;
481 	for (dev = first_dev; dev != NULL; dev = dev->next)
482 	{
483 		if (dev->scanner_present == SANE_TRUE)
484 		{
485 			devlist[i] = &(dev->hw);
486 			i++;
487 		}
488 	}
489 
490 	devlist[i] = NULL;
491 
492 	*dl = devlist;
493 
494 	DBG(2, "<< sane_get_devices\n");
495 	return SANE_STATUS_GOOD;
496 }
497 
498 
499 /*************************************************************************
500  *
501  * sane_open()
502  *
503  * Open the scanner described by name.  Ask libieee1284 to claim the port
504  * and call Simon's init code.  Also configure data structures.
505  *
506  *************************************************************************/
507 	SANE_Status
sane_open(SANE_String_Const name,SANE_Handle * h)508 sane_open (SANE_String_Const name, SANE_Handle *h)
509 {
510 	CANONP_Scanner *cs;
511 	SANE_Range *tmp_range;
512 	int tmp;
513 
514 	DBG(2, ">> sane_open (h=%p, name=\"%s\")\n", (void *)h, name);
515 
516 	if ((h == NULL) || (name == NULL))
517 	{
518 		DBG(2,"sane_open: Null pointer received!\n");
519 		return SANE_STATUS_INVAL;
520 	}
521 
522 	if (!strlen(name))
523 	{
524 		DBG(10,"sane_open: Empty name given, assuming first/"
525 				"default scanner\n");
526 		if (def_scanner == NULL)
527 			name = first_dev->params.port->name;
528 		else
529 			name = def_scanner;
530 
531 		/* we don't _have_ to fit this name, so _don't_ fail if it's
532 		 * not there */
533 
534 		cs = first_dev;
535 		while((cs != NULL) && strcmp(cs->params.port->name, name))
536 			cs = cs->next;
537 
538 		/* if we didn't find the port they want, or there's no scanner
539 		 * there, we just want to find _any_ scanner */
540 		if ((cs == NULL) || (cs->scanner_present != SANE_TRUE))
541 		{
542 			cs = first_dev;
543 			while((cs != NULL) &&
544 					(cs->scanner_present == SANE_FALSE))
545 				cs = cs->next;
546 		}
547 
548 	} else {
549 
550 		/* they're dead keen for this name, so _do_ fail if it's
551 		 * not there */
552 		cs = first_dev;
553 		while((cs != NULL) && strcmp(cs->params.port->name, name))
554 			cs = cs->next;
555 	}
556 
557 
558 	if (cs == NULL)
559 	{
560 		DBG(2,"sane_open: No scanner found or requested port "
561 				"doesn't exist (%s)\n", name);
562 		return SANE_STATUS_IO_ERROR;
563 	}
564 	if (cs->scanner_present == SANE_FALSE)
565 	{
566 		DBG(1,"sane_open: Request to open port with no scanner "
567 				"(%s)\n", name);
568 		return SANE_STATUS_IO_ERROR;
569 	}
570 	if (cs->opened == SANE_TRUE)
571 	{
572 		DBG(2,"sane_open; Oi!, That scanner's already open.\n");
573 		return SANE_STATUS_DEVICE_BUSY;
574 	}
575 
576 	/* If the scanner has already been opened once, we don't have to do
577 	 * this setup again */
578 	if (cs->setup == SANE_TRUE)
579 	{
580 		cs->opened = SANE_TRUE;
581 		*h = (SANE_Handle)cs;
582 		return SANE_STATUS_GOOD;
583 	}
584 
585 	tmp = ieee1284_claim(cs->params.port);
586 	if (tmp != E1284_OK) {
587 		DBG(1, "sane_open: Could not claim port!\n");
588 		return SANE_STATUS_IO_ERROR;
589 	}
590 
591 	/* I put the scanner to sleep before, better wake it back up */
592 
593 	DBG(2, "sane_open: >> initialise\n");
594 	tmp = sanei_canon_pp_initialise(&(cs->params), cs->init_mode);
595 	DBG(2, "sane_open: << %d initialise\n", tmp);
596 	if (tmp != 0) {
597 		DBG(1, "sane_open: initialise returned %d, something is "
598 				"wrong with the scanner!\n", tmp);
599 
600 		DBG(1, "sane_open: Can't contact scanner.  Try power "
601 				"cycling scanner, and unplug any "
602 				"printers\n");
603 		ieee1284_release(cs->params.port);
604 		return SANE_STATUS_IO_ERROR;
605 	}
606 
607 	if (cs->weights_file != NULL)
608 		DBG(2, "sane_open: >> load_weights(%s, %p)\n",
609 				cs->weights_file,
610 				(const void *)(&(cs->params)));
611 	else
612 		DBG(2, "sane_open: >> load_weights(NULL, %p)\n",
613 				(const void *)(&(cs->params)));
614 	tmp = sanei_canon_pp_load_weights(cs->weights_file, &(cs->params));
615 	DBG(2, "sane_open: << %d load_weights\n", tmp);
616 
617 	if (tmp != 0) {
618 		DBG(1, "sane_open: WARNING: Error on load_weights: "
619 				"returned %d.  This could be due to a corrupt "
620 				"calibration file.  Try recalibrating and if "
621 				"problems persist, please report the problem "
622 				"to the canon_pp maintainer\n", tmp);
623 		cs->cal_valid = SANE_FALSE;
624 	} else {
625 		cs->cal_valid = SANE_TRUE;
626 		DBG(10, "sane_open: loadweights successful, uploading gamma"
627 				" profile...\n");
628 		tmp = sanei_canon_pp_adjust_gamma(&(cs->params));
629 		if (tmp != 0)
630 			DBG(1, "sane_open: WARNING: adjust_gamma returned "
631 					"%d!\n", tmp);
632 
633 		DBG(10, "sane_open: after adjust_gamma Status = %i\n",
634 				sanei_canon_pp_check_status(cs->params.port));
635 	}
636 
637 
638 	/* Configure ranges etc */
639 
640 	/* Resolution - determined by magic number */
641 
642 	if (cs->params.scanheadwidth == 2552)
643 		cs->opt[OPT_RESOLUTION].constraint.word_list = res300;
644 	else
645 		cs->opt[OPT_RESOLUTION].constraint.word_list = res600;
646 
647 
648 	/* TL-X */
649 	if(!(tmp_range = malloc(sizeof(*tmp_range))))
650 		return SANE_STATUS_NO_MEM;
651 	(*tmp_range).min = 0;
652 	(*tmp_range).max = 215;
653 	cs->opt[OPT_TL_X].constraint.range = tmp_range;
654 
655 	/* TL-Y */
656 	if(!(tmp_range = malloc(sizeof(*tmp_range))))
657 		return SANE_STATUS_NO_MEM;
658 	(*tmp_range).min = 0;
659 	(*tmp_range).max = 296;
660 	cs->opt[OPT_TL_Y].constraint.range = tmp_range;
661 
662 	/* BR-X */
663 	if(!(tmp_range = malloc(sizeof(*tmp_range))))
664 		return SANE_STATUS_NO_MEM;
665 	(*tmp_range).min = 3;
666 	(*tmp_range).max = 216;
667 	cs->opt[OPT_BR_X].constraint.range = tmp_range;
668 
669 	/* BR-Y */
670 	if(!(tmp_range = malloc(sizeof(*tmp_range))))
671 		return SANE_STATUS_NO_MEM;
672 	(*tmp_range).min = 1;
673 	(*tmp_range).max = 297;
674 	cs->opt[OPT_BR_Y].constraint.range = tmp_range;
675 
676 
677 	cs->opened = SANE_TRUE;
678 	cs->setup = SANE_TRUE;
679 
680 	*h = (SANE_Handle)cs;
681 
682 	DBG(2, "<< sane_open\n");
683 
684 	return SANE_STATUS_GOOD;
685 }
686 
687 /*************************************************************************
688  *
689  * sane_get_option_descriptor()
690  *
691  * Return the structure for option number opt.
692  *
693  *************************************************************************/
694 	const SANE_Option_Descriptor *
sane_get_option_descriptor(SANE_Handle h,SANE_Int opt)695 sane_get_option_descriptor (SANE_Handle h, SANE_Int opt)
696 {
697 	CANONP_Scanner *cs = ((CANONP_Scanner *)h);
698 	/*DBG(2, ">> sane_get_option_descriptor (h=%p, opt=%d)\n", h, opt);*/
699 
700 	if (h == NULL) {
701 		DBG(10,"sane_get_option_descriptor: WARNING: h==NULL!\n");
702 		return NULL;
703 	}
704 
705 	if ((unsigned)opt >= NUM_OPTIONS) {
706 		DBG(10,"sane_get_option_descriptor: Note: opt >= "
707 				"NUM_OPTIONS!\n");
708 		return NULL;
709 	}
710 
711 	if (cs->opened == SANE_FALSE)
712 	{
713 		DBG(1,"sane_get_option_descriptor: That scanner (%p) ain't "
714 				"open yet\n", h);
715 		return NULL;
716 	}
717 
718 	/*DBG(2, "<< sane_get_option_descriptor\n");*/
719 
720 	return (cs->opt + opt);
721 }
722 
723 
724 /*************************************************************************
725  *
726  * sane_control_option()
727  *
728  * Set a value for one of the options provided.
729  *
730  *************************************************************************/
731 SANE_Status
sane_control_option(SANE_Handle h,SANE_Int opt,SANE_Action act,void * val,SANE_Word * info)732 sane_control_option (SANE_Handle h, SANE_Int opt, SANE_Action act,
733 		void *val, SANE_Word *info)
734 {
735 	CANONP_Scanner *cs = ((CANONP_Scanner *)h);
736 	int i = 0, tmp, maxresi;
737 
738 	DBG(2, ">> sane_control_option (h=%p, opt=%d, act=%d)\n",
739 			h,opt,act);
740 	/* Do some sanity checks on the parameters
741 	 * note that val can be null for buttons */
742 	if ((h == NULL) || ((val == NULL) && (opt != OPT_CAL)))
743 		/* || (info == NULL))  - Don't check this any more..
744 		 * frontends seem to like passing a null */
745 	{
746 		DBG(1,"sane_control_option: Frontend passed me a null! "
747 				"(h=%p,val=%p,info=%p)\n",(void*)h,
748 				val,(void*)info);
749 		return SANE_STATUS_INVAL;
750 	}
751 
752 	if (((unsigned)opt) >= NUM_OPTIONS)
753 	{
754 		DBG(1,"sane_control_option: I don't do option %d.\n", opt);
755 		return SANE_STATUS_INVAL;
756 	}
757 
758 	if (cs->opened == SANE_FALSE)
759 	{
760 		DBG(1,"sane_control_option: That scanner (%p) ain't "
761 				"open yet\n", h);
762 		return SANE_STATUS_INVAL;
763 	}
764 
765 	if (cs->scanning == SANE_TRUE)
766 	{
767 		DBG(1,"sane_control_option: That scanner (%p) is scanning!\n",
768 				h);
769 		return SANE_STATUS_DEVICE_BUSY;
770 	}
771 
772 	switch(act)
773 	{
774 		case SANE_ACTION_GET_VALUE:
775 			switch (opt)
776 			{
777 				case OPT_COLOUR_MODE:
778 					strcpy((char *)val,
779 							cmodes[cs->vals[opt]]);
780 					break;
781 				case OPT_DEPTH:
782 					strcpy((char *)val,
783 							depths[cs->vals[opt]]);
784 					break;
785 				case OPT_RESOLUTION:
786 					*((int *)val) = res600[cs->vals[opt]];
787 					break;
788 				default:
789 					*((int *)val) = cs->vals[opt];
790 					break;
791 			}
792 			break;
793 		case SANE_ACTION_SET_VALUE:
794 			/* val has been checked for NULL if opt != OPT_CAL */
795 			if (opt != OPT_CAL) i = *((int *)val);
796 			if (info != NULL) *info = 0;
797 			switch (opt) {
798 				case OPT_NUM_OPTIONS:
799 					/* you can't set that! */
800 					return SANE_STATUS_INVAL;
801 				case OPT_RESOLUTION:
802 					i = cs->vals[opt];
803 					cs->vals[opt] = 1;
804 					maxresi = cs->opt[OPT_RESOLUTION].
805 						constraint.word_list[0];
806 
807 					while ((cs->vals[opt] <= maxresi) &&
808 							(res600[cs->vals[opt]]
809 							 < *((int *)val)))
810 					{
811 						cs->vals[opt] += 1;
812 					}
813 
814 					if (res600[cs->vals[opt]] !=
815 							*((int *)val))
816 					{
817 						if (info != NULL) *info |=
818 							SANE_INFO_INEXACT;
819 					}
820 					break;
821 				case OPT_COLOUR_MODE:
822 					cs->vals[opt] = 0;
823 					while ((cmodes[cs->vals[opt]] != NULL)
824 							&& strcmp(cmodes[cs->vals[opt]],
825 								(char *)val))
826 					{
827 						cs->vals[opt] += 1;
828 					}
829 					if (info != NULL) *info |=
830 						SANE_INFO_RELOAD_PARAMS;
831 					break;
832 				case OPT_DEPTH:
833 					cs->vals[opt] = 0;
834 					while ((depths[cs->vals[opt]] != NULL)
835 							&& strcmp(depths[cs->vals[opt]],
836 								(char *)val))
837 					{
838 						cs->vals[opt] += 1;
839 					}
840 					if (info != NULL) *info |=
841 						SANE_INFO_RELOAD_PARAMS;
842 					break;
843 				case OPT_TL_X:
844 				case OPT_BR_X:
845 				case OPT_TL_Y:
846 				case OPT_BR_Y:
847 					if ((i<cs->opt[opt].constraint.range->min) || (i>cs->opt[opt].constraint.range->max))
848 						return SANE_STATUS_INVAL;
849 					cs->vals[opt] = i;
850 					break;
851 				case OPT_CAL:
852 					/* Call the calibration code */
853 					if ((cs->weights_file==NULL) ||
854 							cs->cal_readonly
855 					   )
856 						DBG(2, ">> calibrate(x, "
857 								"NULL)\n");
858 					else
859 						DBG(2, ">> calibrate(x,"
860 								"%s)\n",
861 								cs->weights_file);
862 
863 					if (cs->cal_readonly) tmp =
864 						sanei_canon_pp_calibrate(
865 								&(cs->params),
866 								NULL);
867 					else tmp = sanei_canon_pp_calibrate(
868 							&(cs->params),
869 							cs->weights_file);
870 
871 					DBG(2, "<< %d calibrate\n",
872 							tmp);
873 					if (tmp != 0) {
874 						DBG(1, "sane_control_option: "
875 								"WARNING: "
876 								"calibrate "
877 								"returned %d!",
878 								tmp);
879 						cs->cal_valid =
880 							SANE_FALSE;
881 						return SANE_STATUS_IO_ERROR;
882 					} else {
883 						cs->cal_valid =
884 							SANE_TRUE;
885 					}
886 
887 					break;
888 					/*case OPT_PREVIEW:
889 					  if (i) cs->vals[opt] = 1;
890 					  else cs->vals[opt] = 0;
891 					  break;*/
892 				default:
893 					/* Should never happen */
894 					return SANE_STATUS_INVAL;
895 			}
896 			break;
897 		case SANE_ACTION_SET_AUTO:
898 			DBG(2, "sane_control_option: attempt at "
899 					"automatic control! (unsupported)\n");
900 			/* Auto? are they mad? I'm not that smart! */
901 			/* fall through. */
902 		default:
903 			return SANE_STATUS_INVAL;
904 	}
905 
906 
907 	DBG(2, "<< sane_control_option\n");
908 	return SANE_STATUS_GOOD;
909 }
910 
911 
912 /*************************************************************************
913  *
914  * sane_get_parameters()
915  *
916  * Get information about the next packet. If a scan hasn't started, results
917  * only have to be best guesses.
918  *
919  *************************************************************************/
920 	SANE_Status
sane_get_parameters(SANE_Handle h,SANE_Parameters * params)921 sane_get_parameters (SANE_Handle h, SANE_Parameters *params)
922 {
923 	int res, max_width, max_height, max_res;
924         CANONP_Scanner *cs = ((CANONP_Scanner *)h);
925 	DBG(2, ">> sane_get_parameters (h=%p, params=%p)\n", (void*)h,
926 			(void*)params);
927 
928 	if (h == NULL) return SANE_STATUS_INVAL;
929 
930 	if (cs->opened == SANE_FALSE)
931 	{
932 		DBG(1,"sane_get_parameters: That scanner (%p) ain't "
933 				"open yet\n", h);
934 		return SANE_STATUS_INVAL;
935 	}
936 
937 	/* We use 600 res list here because the 300 res list is just a shorter
938 	 * version, so this will always work. */
939 	res = res600[cs->vals[OPT_RESOLUTION]];
940 
941 	/*
942 	 * These don't change whether we're scanning or not
943 	 * NOTE: Assumes options don't change after scanning commences, which
944          *       is part of the standard
945 	 */
946 
947 	/* Copy the options stored in the vals into the scaninfo */
948 	params->pixels_per_line =
949                 ((cs->vals[OPT_BR_X] - cs->vals[OPT_TL_X]) * res) / MM_PER_IN;
950 	params->lines = ((cs->vals[OPT_BR_Y] - cs->vals[OPT_TL_Y]) * res)
951                 / MM_PER_IN;
952 
953 	/* FIXME: Magic numbers ahead! */
954 
955 	max_res = cs->params.scanheadwidth == 2552 ? 300 : 600;
956 
957 	/* x values have to be divisible by 4 (round down) */
958 	params->pixels_per_line -= (params->pixels_per_line%4);
959 
960         /* Can't scan less than 64 */
961         if (params->pixels_per_line < 64) params->pixels_per_line = 64;
962 
963 	max_width = cs->params.scanheadwidth / (max_res / res);
964 
965 	max_height = (cs->params.scanheadwidth == 2552 ? 3508 : 7016) /
966                                         (max_res / res);
967 
968         if(params->pixels_per_line > max_width)
969                 params->pixels_per_line = max_width;
970         if(params->lines > max_height) params->lines = max_height;
971 
972 
973 	params->depth = cs->vals[OPT_DEPTH] ? 16 : 8;
974 
975 	switch (cs->vals[OPT_COLOUR_MODE])
976 	{
977 		case 0:
978 			params->format = SANE_FRAME_GRAY;
979 			break;
980 		case 1:
981 			params->format = SANE_FRAME_RGB;
982 			break;
983 		default:
984 			/* shouldn't happen */
985 			break;
986 	}
987 
988 
989 	if (!(params->pixels_per_line)) {
990 		params->last_frame = SANE_TRUE;
991 		params->lines = 0;
992 	}
993 
994 	/* Always the "last frame" */
995 	params->last_frame = SANE_TRUE;
996 
997 	params->bytes_per_line = params->pixels_per_line * (params->depth/8) *
998 		(cs->vals[OPT_COLOUR_MODE] ? 3 : 1);
999 
1000 	DBG(10, "get_params: bytes_per_line=%d, pixels_per_line=%d, lines=%d\n"
1001                 "max_res=%d, res=%d, max_height=%d, br_y=%d, tl_y=%d, "
1002 		"mm_per_in=%f\n",
1003                 params->bytes_per_line, params->pixels_per_line, params->lines,
1004                 max_res, res, max_height, cs->vals[OPT_BR_Y],
1005 		cs->vals[OPT_TL_Y], MM_PER_IN);
1006 
1007 	DBG(2, "<< sane_get_parameters\n");
1008 	return SANE_STATUS_GOOD;
1009 }
1010 
1011 
1012 /*************************************************************************
1013  *
1014  * sane_start()
1015  *
1016  * Starts scanning an image.
1017  *
1018  *************************************************************************/
1019 	SANE_Status
sane_start(SANE_Handle h)1020 sane_start (SANE_Handle h)
1021 {
1022 	unsigned int i, res, max_width, max_height, max_res, tmp;
1023 	CANONP_Scanner *cs = ((CANONP_Scanner *)h);
1024 	DBG(2, ">> sane_start (h=%p)\n", h);
1025 
1026 	if (h == NULL) return SANE_STATUS_INVAL;
1027 
1028 	if (cs->scanning) return SANE_STATUS_DEVICE_BUSY;
1029 	if (cs->opened == SANE_FALSE)
1030 	{
1031 		DBG(1,"sane_start: That scanner (%p) ain't "
1032 				"open yet\n", h);
1033 		return SANE_STATUS_INVAL;
1034 	}
1035 
1036 
1037 	/* We use 600 res list here because the 300 res list is just a shorter
1038 	 * version, so this will always work. */
1039 	res = res600[cs->vals[OPT_RESOLUTION]];
1040 
1041 	/* Copy the options stored in the vals into the scaninfo */
1042 	cs->scan.width = ((cs->vals[OPT_BR_X] - cs->vals[OPT_TL_X]) * res)
1043                 / MM_PER_IN;
1044 	cs->scan.height = ((cs->vals[OPT_BR_Y] - cs->vals[OPT_TL_Y]) * res)
1045                 / MM_PER_IN;
1046 
1047 	cs->scan.xoffset = (cs->vals[OPT_TL_X] * res) / MM_PER_IN;
1048 	cs->scan.yoffset = (cs->vals[OPT_TL_Y] * res) / MM_PER_IN;
1049 
1050         /*
1051          * These values have to pass the requirements of not exceeding
1052          * dimensions (simple clipping) and both width values have to be some
1053          * integer multiple of 4
1054          */
1055 
1056 	/* FIXME: Magic numbers ahead! */
1057 
1058 	max_res = cs->params.scanheadwidth == 2552 ? 300 : 600;
1059 
1060 	/* x values have to be divisible by 4 (round down) */
1061 	cs->scan.width -= (cs->scan.width%4);
1062 	cs->scan.xoffset -= (cs->scan.xoffset%4);
1063 
1064 	/* Can't scan less than 64 */
1065         if (cs->scan.width < 64) cs->scan.width = 64;
1066 
1067 	max_width = cs->params.scanheadwidth / (max_res / res);
1068 
1069 	max_height = (cs->params.scanheadwidth == 2552 ? 3508 : 7016) /
1070                                         (max_res / res);
1071 
1072         if (cs->scan.width > max_width) cs->scan.width = max_width;
1073 	if (cs->scan.width + cs->scan.xoffset > max_width) cs->scan.xoffset =
1074 		max_width - cs->scan.width;
1075         if (cs->scan.height > max_height) cs->scan.height = max_height;
1076 
1077 	/* We pass a value to init_scan which is the power of 2 that 75
1078 	 * is multiplied by for the resolution.  ie:
1079 	 * 75 -> 0
1080 	 * 150 -> 1
1081 	 * 300 -> 2
1082 	 * 600 -> 4
1083 	 *
1084 	 * This rather strange parameter is a result of the way the scanner
1085 	 * takes its resolution argument
1086 	 */
1087 
1088 	i = 0;
1089 	while (res > 75)
1090 	{
1091 		i++;
1092 		res = res >> 1;
1093 	}
1094 
1095 	/* FIXME? xres == yres for now. */
1096 	cs->scan.xresolution = i;
1097 	cs->scan.yresolution = i;
1098 
1099 	if (((cs->vals[OPT_BR_Y] - cs->vals[OPT_TL_Y]) <= 0) ||
1100 			((cs->vals[OPT_BR_X] - cs->vals[OPT_TL_X]) <= 0))
1101 	{
1102 		DBG(1,"sane_start: height = %d, Width = %d. "
1103 				"Can't scan void range!",
1104 				cs->scan.height, cs->scan.width);
1105 		return SANE_STATUS_INVAL;
1106 	}
1107 
1108 	cs->scan.mode = cs->vals[OPT_COLOUR_MODE];
1109 
1110 	DBG(10, ">> init_scan()\n");
1111 	tmp = sanei_canon_pp_init_scan(&(cs->params), &(cs->scan));
1112 	DBG(10, "<< %d init_scan\n", tmp);
1113 
1114 	if (tmp != 0) {
1115 		DBG(1,"sane_start: WARNING: init_scan returned %d!", tmp);
1116 		return SANE_STATUS_IO_ERROR;
1117 	}
1118 	cs->scanning = SANE_TRUE;
1119 	cs->cancelled = SANE_FALSE;
1120 	cs->sent_eof = SANE_FALSE;
1121 	cs->lines_scanned = 0;
1122 	cs->bytes_sent = 0;
1123 
1124 	DBG(2, "<< sane_start\n");
1125 
1126 	return SANE_STATUS_GOOD;
1127 }
1128 
1129 
1130 /*************************************************************************
1131  *
1132  * sane_read()
1133  *
1134  * Reads some information from the buffer.
1135  *
1136  *************************************************************************/
1137 	SANE_Status
sane_read(SANE_Handle h,SANE_Byte * buf,SANE_Int maxlen,SANE_Int * lenp)1138 sane_read (SANE_Handle h, SANE_Byte *buf, SANE_Int maxlen, SANE_Int *lenp)
1139 {
1140 	CANONP_Scanner *cs = ((CANONP_Scanner *)h);
1141 	image_segment *is;
1142 	unsigned int lines, bytes, bpl;
1143 	unsigned int i;
1144 	short *shortptr;
1145 	SANE_Byte *charptr;
1146 	int tmp;
1147 
1148 	static SANE_Byte *lbuf;
1149 	static unsigned int bytesleft;
1150 
1151 	DBG(2, ">> sane_read (h=%p, buf=%p, maxlen=%d)\n", h,
1152 			(const void *)buf, maxlen);
1153 
1154 	/* default to returning 0 - for errors */
1155 	*lenp = 0;
1156 
1157 	if ((h == NULL) || (buf == NULL) || (lenp == NULL))
1158 	{
1159 		DBG(1, "sane_read: This frontend's passing me dodgy gear! "
1160 				"(h=%p, buf=%p, lenp=%p)\n",
1161 				(void*)h, (void*)buf, (void*)lenp);
1162 		return SANE_STATUS_INVAL;
1163 	}
1164 
1165 	/* Now we have to see if we have some leftover from last time */
1166 
1167 	if (read_leftover != NULL)
1168 	{
1169 		/* feed some more data in until we've run out - don't care
1170 		 * whether or not we _think_ the scanner is scanning now,
1171 		 * because we may still have data left over to send */
1172 		DBG(200, "sane_read: didn't send it all last time\n");
1173 
1174 		/* Now feed it some data from lbuf */
1175 		if (bytesleft <= (unsigned int)maxlen)
1176 		{
1177 			/* enough buffer to send the lot */
1178 			memcpy(buf, read_leftover, bytesleft);
1179 			free(lbuf);
1180 			*lenp = bytesleft;
1181 			lbuf = NULL;
1182 			read_leftover = NULL;
1183 			bytesleft = 0;
1184                         cs->bytes_sent += bytesleft;
1185 			return SANE_STATUS_GOOD;
1186 
1187 		} else {
1188 			/* only enough to send maxlen */
1189 			memcpy(buf, read_leftover, maxlen);
1190 			read_leftover += maxlen;
1191 			bytesleft -= maxlen;
1192 			*lenp = maxlen;
1193                         cs->bytes_sent += maxlen;
1194 		        DBG(100, "sane_read: sent %d bytes, still have %d to "
1195                                 "go\n", maxlen, bytesleft);
1196 			return SANE_STATUS_GOOD;
1197 		}
1198 
1199 	}
1200 
1201 
1202 	/* Has the last scan ended (other than by cancelling)? */
1203 	if (((unsigned)cs->scan.height <= (unsigned)cs->lines_scanned)
1204 	    || (cs->sent_eof) || !(cs->scanning))
1205 	{
1206 		cs->sent_eof = SANE_TRUE;
1207 		cs->scanning = SANE_FALSE;
1208 		cs->cancelled = SANE_FALSE;
1209 		cs->lines_scanned = 0;
1210 		cs->bytes_sent = 0;
1211 		read_leftover = NULL;
1212 		return SANE_STATUS_EOF;
1213 	}
1214 
1215 	/* At this point we have to read more data from the scanner - or the
1216 	 * scan has been cancelled, which means we have to call read_segment
1217 	 * to leave the scanner consistent */
1218 
1219 	/* Decide how many lines we can fit into this buffer */
1220 	if (cs->vals[OPT_DEPTH] == 0)
1221 		bpl = cs->scan.width * (cs->vals[OPT_COLOUR_MODE] ? 3 : 1);
1222 	else
1223 		bpl = cs->scan.width * (cs->vals[OPT_COLOUR_MODE] ? 6 : 2);
1224 
1225         /* New way: scan a whole scanner buffer full, and return as much as
1226          * the frontend wants.  It's faster and more reliable since the
1227          * scanners crack the shits if we ask for too many small packets */
1228 	lines = (BUF_MAX * 4 / 5) / bpl;
1229 
1230 	if (lines > (cs->scan.height - cs->lines_scanned))
1231 		lines = cs->scan.height - cs->lines_scanned;
1232 
1233 	if (!lines)
1234 	{
1235 		/* can't fit a whole line into the buffer
1236                  * (should never happen!) */
1237 		lines = 1;
1238 	}
1239 
1240 	bytes = lines * bpl;
1241 
1242 	/* Allocate a local buffer to hold the data while we play */
1243 	if ((lbuf = malloc(bytes)) == NULL)
1244 	{
1245 		DBG(10, "sane_read: Not enough memory to hold a "
1246 				"local buffer.  You're doomed\n");
1247 		return SANE_STATUS_NO_MEM;
1248 	}
1249 
1250 
1251 	/* This call required a lot of debugging information.. */
1252 	DBG(10, "sane_read: Here's what we're sending read_segment:\n");
1253 	DBG(10, "scanner setup: shw=%d xres=%d yres=%d %d %d id=%s\n",
1254 			cs->params.scanheadwidth,
1255 			cs->params.natural_xresolution,
1256 			cs->params.natural_yresolution,
1257 			cs->params.max_xresolution,
1258 			cs->params.max_yresolution,
1259 			(cs->params.id_string)+8);
1260 	DBG(10, "scan_params->: width=%d, height=%d, xoffset=%d, "
1261 			"yoffset=%d\n\txresolution=%d, yresolution=%d, "
1262 			"mode=%d, (lines=%d)\n",
1263 			cs->scan.width, cs->scan.height,
1264 			cs->scan.xoffset, cs->scan.yoffset,
1265 			cs->scan.xresolution, cs->scan.yresolution,
1266 			cs->scan.mode, lines);
1267 
1268 	DBG(2, ">> read_segment(x, x, x, %d, %d, %d)\n",
1269 			lines, cs->cal_valid,
1270 			cs->scan.height - cs->lines_scanned);
1271 	tmp = sanei_canon_pp_read_segment(&is, &(cs->params), &(cs->scan),
1272 			lines, cs->cal_valid,
1273 			cs->scan.height - cs->lines_scanned);
1274 	DBG(2, "<< %d read_segment\n", tmp);
1275 
1276 	if (tmp != 0) {
1277 		if (cs->cancelled)
1278 		{
1279 			DBG(10, "sane_read: cancelling.\n");
1280 			cs->sent_eof = SANE_TRUE;
1281 			cs->scanning = SANE_FALSE;
1282 			read_leftover = NULL;
1283 			sanei_canon_pp_abort_scan(&(cs->params));
1284 			return SANE_STATUS_CANCELLED;
1285 		}
1286 		DBG(1, "sane_read: WARNING: read_segment returned %d!\n", tmp);
1287 		return SANE_STATUS_IO_ERROR;
1288 	}
1289 
1290 	DBG(10, "sane_read: bpl=%d, lines=%d, bytes=%d\n", bpl, lines, bytes);
1291 
1292 	cs->lines_scanned += lines;
1293 
1294 	/* translate data out of buffer */
1295 	if (cs->vals[OPT_DEPTH] == 0)
1296 	{
1297 		/* 8bpp */
1298 		for(i = 0; i < bytes; i++)
1299 		{
1300 			charptr = lbuf + i;
1301 			if (cs->vals[OPT_COLOUR_MODE])
1302 			{
1303 				if (i % 3 == 0) charptr += 2;
1304 				if (i % 3 == 2) charptr -= 2;
1305 			}
1306 			*charptr = *((char *)(is->image_data) + (i*2));
1307 		}
1308 	}
1309 	else
1310 	{
1311 		/* 16bpp */
1312 		for(i = 0; i < (bytes/2); i++)
1313 		{
1314 			shortptr = ((short *)lbuf + i);
1315 			if (cs->vals[OPT_COLOUR_MODE])
1316 			{
1317 				if (i % 3 == 0) shortptr += 2;
1318 				if (i % 3 == 2) shortptr -= 2;
1319 			}
1320 			*shortptr = MAKE_SHORT(
1321 					*((char *)(is->image_data) + (i*2)),
1322 					*((char *)(is->image_data) + (i*2)+1)
1323 					);
1324 		}
1325 	}
1326 
1327 	/* Free data structures allocated in read_segment */
1328 	free(is->image_data);
1329 	free(is);
1330 
1331 	/* Now feed it some data from lbuf */
1332 	if (bytes <= (unsigned int)maxlen)
1333 	{
1334 		/* enough buffer to send the lot */
1335 		memcpy(buf, lbuf, bytes);
1336 		*lenp = bytes;
1337 		free(lbuf);
1338 		lbuf = NULL;
1339 		read_leftover = NULL;
1340 		bytesleft = 0;
1341                 cs->bytes_sent += bytes;
1342 
1343 	} else {
1344 		/* only enough to send maxlen */
1345 		memcpy(buf, lbuf, maxlen);
1346 		*lenp = maxlen;
1347 		read_leftover = lbuf + maxlen;
1348 		bytesleft = bytes - maxlen;
1349                 cs->bytes_sent += maxlen;
1350 		DBG(100, "sane_read: sent %d bytes, still have %d to go\n",
1351                         maxlen, bytesleft);
1352 	}
1353 
1354 	if ((unsigned)cs->lines_scanned >= cs->scan.height)
1355 	{
1356 		/* The scan is over! Don't need to call anything in the
1357 		 * hardware, it will sort itself out */
1358 		DBG(10, "sane_read: Scan is finished.\n");
1359 		cs->scanning = SANE_FALSE;
1360 		cs->lines_scanned = 0;
1361 		cs->bytes_sent = 0;
1362 	}
1363 
1364 	DBG(2, "<< sane_read\n");
1365 	return SANE_STATUS_GOOD;
1366 }
1367 
1368 
1369 /*************************************************************************
1370  *
1371  * sane_cancel()
1372  *
1373  * Cancels a scan in progress
1374  *
1375  *************************************************************************/
1376 	void
sane_cancel(SANE_Handle h)1377 sane_cancel (SANE_Handle h)
1378 {
1379 	/* Note: assume handle is valid apart from NULLs */
1380 	CANONP_Scanner *cs = ((CANONP_Scanner *)h);
1381 
1382 	DBG(2, ">> sane_cancel (h=%p)\n", h);
1383 	if (h == NULL) return;
1384 
1385 	read_leftover = NULL;
1386 
1387 	if (!(cs->scanning))
1388 	{
1389 		DBG(2, "<< sane_cancel (not scanning)\n");
1390 		return;
1391 	}
1392 
1393 	cs->cancelled = SANE_TRUE;
1394 	cs->params.abort_now = 1;
1395 
1396 	DBG(2, "<< sane_cancel\n");
1397 }
1398 
1399 
1400 /*************************************************************************
1401  *
1402  * sane_close()
1403  *
1404  * Closes a scanner handle.  Scanner is assumed to be free after this.
1405  *
1406  *************************************************************************/
1407 	void
sane_close(SANE_Handle h)1408 sane_close (SANE_Handle h)
1409 {
1410 	/* Note: assume handle is valid apart from NULLs */
1411 	CANONP_Scanner *cs = ((CANONP_Scanner *)h);
1412 	DBG(2, ">> sane_close (h=%p)\n", h);
1413 	if (h == NULL) return;
1414 
1415 	if (cs->opened == SANE_FALSE)
1416 	{
1417 		DBG(1,"sane_close: That scanner (%p) ain't "
1418 				"open yet\n", h);
1419 		return;
1420 	}
1421 
1422 	/* Put scanner back in transparent mode */
1423 	sanei_canon_pp_close_scanner(&(cs->params));
1424 
1425 	cs->opened = SANE_FALSE;
1426 
1427 	/* if it was scanning, it's not any more */
1428 	cs->scanning = SANE_FALSE;
1429 	cs->sent_eof = SANE_TRUE;
1430 
1431 	ieee1284_release(cs->params.port);
1432 
1433 	DBG(2, "<< sane_close\n");
1434 }
1435 
1436 
1437 /*************************************************************************
1438  *
1439  * sane_exit()
1440  *
1441  * Shut it down!
1442  *
1443  *************************************************************************/
1444 	void
sane_exit(void)1445 sane_exit (void)
1446 {
1447 	CANONP_Scanner *dev, *next;
1448 
1449 	DBG(2, ">> sane_exit\n");
1450 
1451 	for (dev = first_dev; dev != NULL; dev = next)
1452 	{
1453 		next = dev->next;
1454 
1455 		/* These were only created if the scanner has been init'd */
1456 
1457 		/* Should normally nullify pointers after freeing, but in
1458 		 * this case we're about to free the whole structure so
1459 		 * there's not a lot of point. */
1460 
1461 		/* Constraints (mostly) allocated when the scanner is opened */
1462 		if(dev->opt[OPT_TL_X].constraint.range)
1463 			free((void *)(dev->opt[OPT_TL_X].constraint.range));
1464 		if(dev->opt[OPT_TL_Y].constraint.range)
1465 			free((void *)(dev->opt[OPT_TL_Y].constraint.range));
1466 		if(dev->opt[OPT_BR_X].constraint.range)
1467 			free((void *)(dev->opt[OPT_BR_X].constraint.range));
1468 		if(dev->opt[OPT_BR_Y].constraint.range)
1469 			free((void *)(dev->opt[OPT_BR_Y].constraint.range));
1470 
1471 		/* Weights file now on a per-scanner basis */
1472 		if (dev->weights_file != NULL)
1473 			free(dev->weights_file);
1474 
1475 		if (dev->scanner_present)
1476 		{
1477 			if (dev->opened == SANE_TRUE)
1478 			{
1479 				/* naughty boys, should have closed first */
1480 				ieee1284_release(dev->params.port);
1481 			}
1482 			ieee1284_close(dev->params.port);
1483 		}
1484 
1485 		free (dev);
1486 	}
1487 
1488 	first_dev = NULL;
1489 	def_scanner = NULL;
1490 	read_leftover = NULL;
1491 	num_devices = 0;
1492 
1493 	/* FIXEDME: this created a segfault in DLL code. */
1494 	/* Bug was fixed in libieee1284 0.1.5 */
1495 	ieee1284_free_ports(&pl);
1496 
1497 	DBG(2, "<< sane_exit\n");
1498 }
1499 
1500 
1501 /*************************************************************************
1502  *
1503  * init_device()
1504  *
1505  * (Not part of the SANE API)
1506  *
1507  * Initialises a CANONP_Scanner data structure for a new device.
1508  * NOTE: The device is not ready to scan until initialise() has been
1509  * called in scan library!
1510  *
1511  *************************************************************************/
init_device(struct parport * pp)1512 static SANE_Status init_device(struct parport *pp)
1513 {
1514 	int i;
1515 	static const char *hw_vendor = "CANON";
1516 	static const char *hw_type = "flatbed scanner";
1517 	static const char *opt_names[] = {
1518 		SANE_NAME_NUM_OPTIONS,
1519 		SANE_NAME_SCAN_RESOLUTION,
1520 		SANE_NAME_SCAN_MODE,
1521 		SANE_NAME_BIT_DEPTH,
1522 		SANE_NAME_SCAN_TL_X,
1523 		SANE_NAME_SCAN_TL_Y,
1524 		SANE_NAME_SCAN_BR_X,
1525 		SANE_NAME_SCAN_BR_Y,
1526 		SANE_NAME_QUALITY_CAL
1527 #if 0
1528 		SANE_NAME_GAMMA_R,
1529 		SANE_NAME_GAMMA_G,
1530 		SANE_NAME_GAMMA_B
1531 #endif
1532 	};
1533 	static const char *opt_titles[] = {
1534 		SANE_TITLE_NUM_OPTIONS,
1535 		SANE_TITLE_SCAN_RESOLUTION,
1536 		SANE_TITLE_SCAN_MODE,
1537 		SANE_TITLE_BIT_DEPTH,
1538 		SANE_TITLE_SCAN_TL_X,
1539 		SANE_TITLE_SCAN_TL_Y,
1540 		SANE_TITLE_SCAN_BR_X,
1541 		SANE_TITLE_SCAN_BR_Y,
1542 		SANE_TITLE_QUALITY_CAL
1543 #if 0
1544 		SANE_TITLE_GAMMA_R,
1545 		SANE_TITLE_GAMMA_G,
1546 		SANE_TITLE_GAMMA_B
1547 #endif
1548 	};
1549 	static const char *opt_descs[] = {
1550 		SANE_DESC_NUM_OPTIONS,
1551 		SANE_DESC_SCAN_RESOLUTION,
1552 		SANE_DESC_SCAN_MODE,
1553 		SANE_DESC_BIT_DEPTH,
1554 		SANE_DESC_SCAN_TL_X,
1555 		SANE_DESC_SCAN_TL_Y,
1556 		SANE_DESC_SCAN_BR_X,
1557 		SANE_DESC_SCAN_BR_Y,
1558 		SANE_DESC_QUALITY_CAL
1559 #if 0
1560 		SANE_DESC_GAMMA_R,
1561 		SANE_DESC_GAMMA_G,
1562 		SANE_DESC_GAMMA_B
1563 #endif
1564 	};
1565 
1566 	CANONP_Scanner *cs = NULL;
1567 
1568 	DBG(2, ">> init_device\n");
1569 
1570 	cs = malloc(sizeof(*cs));
1571 	if (cs == NULL)
1572 	{
1573 		return SANE_STATUS_NO_MEM;
1574 	}
1575 	memset(cs, 0, sizeof(*cs));
1576 
1577 #if 0
1578 	if ((cs->params.port = malloc(sizeof(*(cs->params.port)))) == NULL)
1579 		return SANE_STATUS_NO_MEM;
1580 
1581 	memcpy(cs->params.port, pp, sizeof(*pp));
1582 #endif
1583 
1584 	cs->params.port = pp;
1585 
1586 	/* ensure these are null to start off with, otherwise they might be
1587 	 * erroneously free'd.  Note that we set everything to 0 above
1588 	 * but that's not *always* the same thing */
1589 	cs->params.blackweight = NULL;
1590 	cs->params.redweight = NULL;
1591 	cs->params.greenweight = NULL;
1592 	cs->params.blueweight = NULL;
1593 
1594 	/* Set some sensible defaults */
1595 	cs->hw.name = cs->params.port->name;
1596 	cs->hw.vendor = hw_vendor;
1597 	cs->hw.type = hw_type;
1598 	cs->opened = SANE_FALSE;
1599 	cs->scanning = SANE_FALSE;
1600 	cs->cancelled = SANE_FALSE;
1601 	cs->sent_eof = SANE_TRUE;
1602 	cs->lines_scanned = 0;
1603 	cs->bytes_sent = 0;
1604 	cs->init_mode = INITMODE_AUTO;
1605 
1606 	DBG(10, "init_device: [configuring options]\n");
1607 
1608 	/* take a punt at each option, then we change it later */
1609 	for (i = 0; i < NUM_OPTIONS; i++)
1610 	{
1611 		cs->opt[i].name = opt_names[i];
1612 		cs->opt[i].title = opt_titles[i];
1613 		cs->opt[i].desc = opt_descs[i];
1614 		cs->opt[i].cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
1615 		cs->opt[i].type = SANE_TYPE_INT;
1616 		cs->opt[i].size = sizeof(SANE_Int);
1617 	}
1618 
1619 	DBG(100, "init_device: configuring opt: num_options\n");
1620 	/* The number of options option */
1621 
1622 	cs->opt[OPT_NUM_OPTIONS].unit = SANE_UNIT_NONE;
1623 	cs->opt[OPT_NUM_OPTIONS].cap = SANE_CAP_SOFT_DETECT;
1624 	cs->vals[OPT_NUM_OPTIONS] = NUM_OPTIONS;
1625 
1626 	DBG(100, "init_device: configuring opt: resolution\n");
1627 
1628 	/* The resolution of scanning (X res == Y res for now)*/
1629 	cs->opt[OPT_RESOLUTION].unit = SANE_UNIT_DPI;
1630 	cs->opt[OPT_RESOLUTION].constraint_type = SANE_CONSTRAINT_WORD_LIST;
1631 	/* should never point at first element (wordlist size) */
1632 	cs->vals[OPT_RESOLUTION] = 1;
1633 
1634 	DBG(100, "init_device: configuring opt: colour mode\n");
1635 
1636 	/* The colour mode (0=grey 1=rgb) */
1637 	cs->opt[OPT_COLOUR_MODE].type = SANE_TYPE_STRING;
1638 	cs->opt[OPT_COLOUR_MODE].size = 20;
1639 	cs->opt[OPT_COLOUR_MODE].constraint_type = SANE_CONSTRAINT_STRING_LIST;
1640 	/* Set this one here because it doesn't change by scanner (yet) */
1641 	cs->opt[OPT_COLOUR_MODE].constraint.string_list = cmodes;
1642 
1643 	DBG(100, "init_device: configuring opt: bit depth\n");
1644 
1645 	/* The bit depth */
1646 	cs->opt[OPT_DEPTH].type = SANE_TYPE_STRING;
1647 	cs->opt[OPT_DEPTH].size = 20;
1648 	cs->opt[OPT_DEPTH].cap |= SANE_CAP_EMULATED;
1649 	cs->opt[OPT_DEPTH].constraint_type = SANE_CONSTRAINT_STRING_LIST;
1650 	cs->opt[OPT_DEPTH].constraint.string_list = depths;
1651 
1652 	DBG(100, "init_device: configuring opt: tl-x\n");
1653 
1654 	/* The top-left-x */
1655 	cs->opt[OPT_TL_X].unit = SANE_UNIT_MM;
1656 	cs->opt[OPT_TL_X].constraint_type = SANE_CONSTRAINT_RANGE;
1657 
1658 	DBG(100, "init_device: configuring opt: tl-y\n");
1659 
1660 	/* The top-left-y */
1661 	cs->opt[OPT_TL_Y].unit = SANE_UNIT_MM;
1662 	cs->opt[OPT_TL_Y].constraint_type = SANE_CONSTRAINT_RANGE;
1663 
1664 	DBG(100, "init_device: configuring opt: br-x\n");
1665 
1666 	/* The bottom-right-x */
1667 	cs->opt[OPT_BR_X].unit = SANE_UNIT_MM;
1668 	cs->opt[OPT_BR_X].constraint_type = SANE_CONSTRAINT_RANGE;
1669 	/* default scan width */
1670 	cs->vals[OPT_BR_X] = 100;
1671 
1672 	DBG(100, "init_device: configuring opt: br-y\n");
1673 
1674 	/* The bottom-right-y */
1675 	cs->opt[OPT_BR_Y].unit = SANE_UNIT_MM;
1676 	cs->opt[OPT_BR_Y].constraint_type = SANE_CONSTRAINT_RANGE;
1677 	cs->vals[OPT_BR_Y] = 100;
1678 
1679 	DBG(100, "init_device: configuring opt: calibrate\n");
1680 
1681 	/* The calibration button */
1682 	cs->opt[OPT_CAL].type = SANE_TYPE_BUTTON;
1683 	cs->opt[OPT_CAL].constraint_type = SANE_CONSTRAINT_NONE;
1684 	if (cs->cal_readonly)
1685 		cs->opt[OPT_CAL].cap |= SANE_CAP_INACTIVE;
1686 
1687 #if 0
1688 	/* the gamma values (once we do them) */
1689 	cs->opt[OPT_GAMMA_R].caps |= SANE_CAP_ADVANCED;
1690 	cs->opt[OPT_GAMMA_G].caps |= SANE_CAP_ADVANCED;
1691 	cs->opt[OPT_GAMMA_B].caps |= SANE_CAP_ADVANCED;
1692 #endif
1693 
1694 	/*
1695 	 * NOTE: Ranges and lists are actually set when scanner is opened,
1696 	 * because that's when we find out what sort of scanner it is
1697 	 */
1698 
1699 	DBG(100, "init_device: done opts\n");
1700 
1701 	/* add it to the head of the tree */
1702 	cs->next = first_dev;
1703 	first_dev = cs;
1704 
1705 	num_devices++;
1706 
1707 	DBG(2, "<< init_device\n");
1708 
1709 	return SANE_STATUS_GOOD;
1710 }
1711 
1712 
1713 /*************************************************************************
1714  *
1715  * These two are optional ones... maybe if I get really keen?
1716  *
1717  *************************************************************************/
1718 	SANE_Status
sane_set_io_mode(SANE_Handle h,SANE_Bool non_blocking)1719 sane_set_io_mode (SANE_Handle h, SANE_Bool non_blocking)
1720 {
1721 	DBG(2, ">> sane_set_io_mode (%p, %d) (not really supported)\n",
1722 			h, non_blocking);
1723 
1724 	if (non_blocking == SANE_FALSE)
1725 		return SANE_STATUS_GOOD;
1726 
1727 	DBG(2, "<< sane_set_io_mode\n");
1728 	return SANE_STATUS_UNSUPPORTED;
1729 }
1730 
1731 	SANE_Status
sane_get_select_fd(SANE_Handle h,SANE_Int * fdp)1732 sane_get_select_fd (SANE_Handle h, SANE_Int *fdp)
1733 {
1734 	DBG(2, ">> sane_get_select_fd (%p, %p) (not supported)\n", h,
1735 			(const void *)fdp);
1736 	DBG(2, "<< sane_get_select_fd\n");
1737 	return SANE_STATUS_UNSUPPORTED;
1738 }
1739 
1740 
1741 /*************************************************************************
1742  *
1743  * init_cal(): Try to create a calibration file
1744  * has to be changed.
1745  *
1746  ************************************************************************/
init_cal(char * file)1747 static int init_cal(char *file)
1748 {
1749 	char *tmp, *path;
1750 	int f, i;
1751 
1752 	if ((f = open(file, O_CREAT | O_WRONLY, 0600)) < 0)
1753 	{
1754 		if (errno == ENOENT)
1755 		{
1756 			/* we need to try and make ~/.sane perhaps -
1757 			 * find the last / in the file path, and try
1758 			 * to create it */
1759 			if ((tmp = strrchr(file, '/')) == NULL)
1760 				return -1;
1761 			path = strdup(file);
1762 			*(path + (tmp-file)) = '\0';
1763 			i = mkdir(path, 0777);
1764 			free(path);
1765 			if (i) return -1;
1766 			/* Path has been created, now try this again.. */
1767 			if ((f = open(file, O_CREAT | O_WRONLY, 0600)) < 0)
1768 				return -1;
1769 		}
1770 		else
1771 		{
1772 			/* Error is something like access denied - too
1773 			 * hard to fix, so i give up... */
1774 			return -1;
1775 		}
1776 	}
1777 	/* should probably set defaults here.. */
1778 	close(f);
1779 	return 0;
1780 }
1781 
1782 /*************************************************************************
1783  *
1784  * fix_weights_file(): Ensures that the weights_file setting for a given
1785  * scanner is valid
1786  *
1787  ************************************************************************/
fix_weights_file(CANONP_Scanner * cs)1788 static SANE_Status fix_weights_file(CANONP_Scanner *cs)
1789 {
1790 	char *tmp, *myhome, buf[PATH_MAX];
1791 	int i;
1792 	struct stat *f_stat;
1793 
1794 
1795 	if (cs == NULL)
1796 	{
1797 		DBG(0, "fix_weights_file: FATAL: NULL passed by my code, "
1798 				"please report this!\n");
1799 		return SANE_STATUS_INVAL;
1800 	}
1801 
1802 	/* Assume this is false and then correct it */
1803 	cs->cal_readonly = SANE_FALSE;
1804 
1805 	if (cs->weights_file == NULL)
1806 	{
1807 		/* Will be of form canon_pp-calibration-parport0 or -0x378 */
1808 		sprintf(buf, "~/.sane/canon_pp-calibration-%s",
1809 				cs->params.port->name);
1810 		cs->weights_file = strdup(buf);
1811 	}
1812 
1813 	/* Get the user's home dir if they used ~ */
1814 	if (cs->weights_file[0] == '~')
1815 	{
1816 		if ((tmp = malloc(PATH_MAX)) == NULL)
1817 			return SANE_STATUS_NO_MEM;
1818 		if ((myhome = getenv("HOME")) == NULL)
1819 		{
1820 			DBG(0,"fix_weights_file: FATAL: ~ used, but $HOME not"
1821 					" set!\n");
1822 			free(tmp);
1823 			tmp = NULL;
1824 			return SANE_STATUS_INVAL;
1825 		}
1826 		strncpy(tmp, myhome, PATH_MAX);
1827 		strncpy(tmp+strlen(tmp), (cs->weights_file)+1,
1828 				PATH_MAX-strlen(tmp));
1829 
1830 		free(cs->weights_file);
1831 		cs->weights_file = tmp;
1832 	}
1833 
1834 	if ((f_stat = malloc(sizeof(*f_stat))) == NULL)
1835 		return SANE_STATUS_NO_MEM;
1836 
1837 	if(stat(cs->weights_file, f_stat))
1838 	{
1839 		/* this non-intuitive if basically is if we got some error that
1840 		 * wasn't no-such-file, or we can't create the file.. */
1841 		if ((errno != ENOENT) || init_cal(cs->weights_file))
1842 		{
1843 			/* Some nasty error returned. Give up. */
1844 			DBG(2,"fix_weights_file: error stating cal file"
1845 					" (%s)\n", strerror(errno));
1846 			DBG(2,"fix_weights_file: Changes to cal data won't"
1847 					" be saved!\n");
1848 			free(cs->weights_file);
1849 			cs->weights_file = NULL;
1850 		}
1851 	}
1852 	else
1853 	{
1854 
1855 		/* No error returned.. Check read/writability */
1856 		i = open(cs->weights_file, O_RDWR | O_APPEND);
1857 		if (i <= 0)
1858 		{
1859 			DBG(10,"fix_weighs_file: Note: Changes to cal data "
1860 					"won't be saved!\n");
1861 			i = open(cs->weights_file, O_RDONLY);
1862 			if (i <= 0)
1863 			{
1864 				/*
1865 				 * Open failed (do i care why?)
1866 				 */
1867 				DBG(2,"fix_weights_file: error opening cal "
1868 						"(%s)\n", strerror(errno));
1869 				free(cs->weights_file);
1870 				cs->weights_file = NULL;
1871 			}
1872 			else
1873 			{
1874 				DBG(2,"fix_weights_file: file is read-only, "
1875 						"changes won't be saved\n");
1876 				cs->cal_readonly = SANE_TRUE;
1877 				close(i);
1878 			}
1879 		}
1880 		else
1881 		{
1882 			/* good! */
1883 			DBG(10,"fix_weights_file: Calibration file is good "
1884 					"for opening!\n");
1885 			close(i);
1886 		}
1887 	}
1888 
1889 	/* cleanup */
1890 	free(f_stat);
1891 
1892 	return SANE_STATUS_GOOD;
1893 }
1894 
1895 /* detect_mode
1896  * PRE:
1897  *	cs->params.port is not open
1898  * POST:
1899  * 	cs->params.port is left opened iff SANE_STATUS_GOOD returned.
1900  */
1901 
detect_mode(CANONP_Scanner * cs)1902 SANE_Status detect_mode(CANONP_Scanner *cs)
1903 {
1904 
1905 	int capabilities, tmp;
1906 
1907 	/* Open then claim parallel port using libieee1284 */
1908 	DBG(10,"detect_mode: Opening port %s\n", (cs->params.port->name));
1909 
1910 	tmp = ieee1284_open(cs->params.port, 0, &capabilities);
1911 
1912 	if (tmp != E1284_OK)
1913 	{
1914 		switch (tmp)
1915 		{
1916 			case E1284_INVALIDPORT:
1917 				DBG(1, "detect_mode: Invalid port.\n");
1918 				break;
1919 			case E1284_SYS:
1920 				DBG(1, "detect_mode: System error: %s\n",
1921 						strerror(errno));
1922 				break;
1923 			case E1284_INIT:
1924 				DBG(1, "detect_mode: Initialisation error.\n");
1925 				break;
1926 			default:
1927 				DBG(1, "detect_mode: Unknown error.\n");
1928 				break;
1929 		}
1930 		return SANE_STATUS_IO_ERROR;
1931 	}
1932 
1933 	DBG(10,"detect_mode: Claiming port.\n");
1934 
1935 	if (ieee1284_claim(cs->params.port) != E1284_OK)
1936 	{
1937 		DBG(1,"detect_mode: Unable to claim port\n");
1938 		ieee1284_close(cs->params.port);
1939 		return SANE_STATUS_IO_ERROR;
1940 	}
1941 
1942 
1943 	/* Check that compatibility-mode (required) is supported */
1944 	if (!(capabilities & CAP1284_COMPAT))
1945 	{
1946 		DBG(0,"detect_mode: Compatibility mode (required) not "
1947 				"supported.\n");
1948 		ieee1284_release(cs->params.port);
1949 		ieee1284_close(cs->params.port);
1950 		return SANE_STATUS_IO_ERROR;
1951 	}
1952 
1953 	/* Check capabilities which will enchance speed */
1954 	if (capabilities & CAP1284_ECP)
1955 		DBG(2, "detect_mode: Port supports ECP-H.\n");
1956 	else if (capabilities & CAP1284_ECPSWE)
1957 		DBG(2, "detect_mode: Port supports ECP-S.\n");
1958 	if (capabilities & CAP1284_IRQ)
1959 		DBG(2, "detect_mode: Port supports interrupts.\n");
1960 	if (capabilities & CAP1284_DMA)
1961 		DBG(2, "detect_mode: Port supports DMA.\n");
1962 
1963 	/* Check whether ECP mode is possible */
1964 	if (capabilities & CAP1284_ECP)
1965 	{
1966 		cs->ieee1284_mode = M1284_ECP;
1967 		DBG(10, "detect_mode: Using ECP-H Mode\n");
1968 	}
1969 	else if (capabilities & CAP1284_ECPSWE)
1970 	{
1971 		cs->ieee1284_mode = M1284_ECPSWE;
1972 		DBG(10, "detect_mode: Using ECP-S Mode\n");
1973 	}
1974 	else if (capabilities & CAP1284_NIBBLE)
1975 	{
1976 		cs->ieee1284_mode = M1284_NIBBLE;
1977 		DBG(10, "detect_mode: Using nibble mode\n");
1978 	}
1979 	else
1980 	{
1981 		DBG(0, "detect_mode: No supported parport modes available!\n");
1982 		ieee1284_release(cs->params.port);
1983 		ieee1284_close(cs->params.port);
1984 		return SANE_STATUS_IO_ERROR;
1985 	}
1986 
1987 	/* Check to make sure ECP mode really is supported */
1988 	/* Have disabled the hardware ECP check because it's always supported
1989 	 * by libieee1284 now, and it's too prone to hitting a ppdev bug
1990 	 */
1991 
1992 	/* Disabled check entirely.. check now in initialise when we
1993 	 * actually do a read */
1994 #if 0
1995 	if ((cs->ieee1284_mode == M1284_ECP) ||
1996 			(cs->ieee1284_mode == M1284_ECPSWE))
1997 	{
1998 		DBG(1, "detect_mode: attempting a 0 byte read, if we hang "
1999 				"here, it's a ppdev bug!\n");
2000 		/*
2001 		 * 29/06/02
2002 		 * NOTE:
2003 		 * This causes an infinite loop in ppdev on 2.4.18.
2004 		 * Not checking on hardware ECP mode should work-around
2005 		 * effectively.
2006 		 *
2007 		 * I have sent email to twaugh about it, should be fixed in
2008 		 * 2.4.19 and above.
2009 		 */
2010 		if (ieee1284_ecp_read_data(cs->params.port, 0, NULL, 0) ==
2011 				E1284_NOTIMPL)
2012 		{
2013 			DBG(10, "detect_mode: Your version of libieee1284 "
2014 					"doesn't support ECP mode - defaulting"
2015 					" to nibble mode instead.\n");
2016 			cs->ieee1284_mode = M1284_NIBBLE;
2017 		}
2018 	}
2019 #endif
2020 
2021 	if (force_nibble == SANE_TRUE) {
2022 		DBG(10, "detect_mode: Nibble mode force in effect.\n");
2023 		cs->ieee1284_mode = M1284_NIBBLE;
2024 	}
2025 
2026 	ieee1284_release(cs->params.port);
2027 
2028 	sanei_canon_pp_set_ieee1284_mode(cs->ieee1284_mode);
2029 
2030 	return SANE_STATUS_GOOD;
2031 }
2032