summaryrefslogtreecommitdiffstats
path: root/perl-install/standalone/scannerdrake
blob: fdfc92303f32df6f6b62304edb2dbbb394d4c30e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
#!/usr/bin/perl

# scannerdrake $Id$
# Yves Duret <yduret at mandriva.com>
# Till Kamppeter <till at mandriva.com>
# Copyright (C) 2001-2004 Mandriva
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

use lib qw(/usr/lib/libDrakX);
use strict;
use standalone;     #- warning, standalone must be loaded very first, for 'explanations'
use common;

use interactive;
use scanner;
use handle_configs;
use services;

my $companyname = "Mandriva";
my $distroname = "Mandriva Linux";
my $shortdistroname = "Mandriva Linux";
my $domainname = "mandriva.com";

foreach (@ARGV) {
    /^--update-usbtable$/ and do { scanner::updateScannerDBfromUsbtable(); exit() };
    /^--update-sane=(.*)$/ and do { scanner::updateScannerDBfromSane($1); exit() };
    /^--manual$/ and $::Manual=1;
    /^--dynamic=(.*)$/ and do { dynamic(); exit() };
}

$ugtk2::wm_icon = "scannerdrake";
my $in = 'interactive'->vnew('su');
if (!files_exist(qw(/usr/bin/scanimage
		    /etc/sane.d/dll.conf)) ||
    (!files_exist(qw(/usr/bin/xsane)) &&
     !files_exist(qw(/usr/bin/kooka)) &&
     !$in->do_pkgs->is_installed('scanner-gui'))) {
    if (!$in->ask_yesorno(N("Warning"), N("SANE packages need to be installed to use scanners.

Do you want to install the SANE packages?"))) {
	$in->ask_warn("Scannerdrake", 
		      N("Aborting Scannerdrake."));
	exit 0;
    }
    if (!$in->do_pkgs->install('sane-backends', 'scanner-gui')) {
	$in->ask_warn(N("Error"),
		      N("Could not install the packages needed to set up a scanner with Scannerdrake.") . " " .
		      N("Scannerdrake will not be started now."));
	exit 0;
    }
}
if ($::Manual) { manual(); quit() }
my $wait = $in->wait_message(N("Scannerdrake"),
			     N("Searching for configured scanners..."));
my @c = scanner::configured();
$wait = undef;
$wait = $in->wait_message(N("Scannerdrake"),
			     N("Searching for new scanners..."));
my @f = scanner::detect(@c);
$wait = undef;
my $changed = 0;
@f and $changed = auto();
if ($changed) {
    my $_wait =
	$in->wait_message(N("Scannerdrake"),
			  N("Re-generating list of configured scanners..."));
    @c = scanner::configured();
}
mainwindow(@c);
quit();

sub removeverticalbar {
    my ($s) = @_;
    $s =~ s/\|/ /g;
    my $searchmake = handle_configs::searchstr(first($s =~ /^\s*(\S+)\s+/));
    $s =~ s/($searchmake)\s*$searchmake/$1/;
    return $s; 
}

sub auto() {
    my $changed = 0;
    foreach (@f) {
	my $c = 0;
	if (member($_->{val}{DESCRIPTION}, keys %$scanner::scannerDB)) {
	    my $name = $_->{val}{DESCRIPTION};
	    $name =~ s/\s$//; # some HP entries have a trailing space, i will correct usbtable asap
	    if ($scanner::scannerDB->{$name}{flags}{unsupported}) {
		$in->ask_warn('Scannerdrake', N("The %s is not supported by this version of %s.", removeverticalbar($name), $distroname));
		next;
	    }
	    if ($in->ask_yesorno('Scannerdrake', N("%s found on %s, configure it automatically?", removeverticalbar($name), $_->{port}),1)) {
		$c = (tryConfScanner($name, $_->{port}, 
				     $_->{val}{vendor},
				     $_->{val}{id}) || 
		      manual($_->{port}, $_->{val}{vendor},
			     $_->{val}{id}, $name));
	    } else {
		$c = manual($_->{port}, $_->{val}{vendor},
			    $_->{val}{id}, $name);
	    }
	} else {
	    $in->ask_yesorno('Scannerdrake',
			     N("%s is not in the scanner database, configure it manually?", 
			       removeverticalbar($_->{val}{DESCRIPTION})),1)
		and $c =
		     manual($_->{port}, $_->{val}{vendor}, $_->{val}{id},
			    $_->{val}{DESCRIPTION});
	}
	$changed ||= $c;
    }
    return $changed;
}

sub manual {
    my ($port, $vendor, $product, $name) = @_;
    my $s = 
	$in->ask_from_treelist('Scannerdrake', 
			       N("Select a scanner model") .
			       if_($port || $name, N(" (")) .
			       if_($name, N("Detected model: %s",
					    removeverticalbar($name))) .
			       if_($port && $name, N(", ")) .
			       if_($port, N("Port: %s", $port)) .
			       if_($port || $name, N(")")),
			       '|', [' None', map { $_ . if_($scanner::scannerDB->{$_}{flags}{unsupported}, N(" (UNSUPPORTED)")) } keys %$scanner::scannerDB],
			       '') or return 0;
    return 0 if $s eq ' None';
    my $unsuppstr = quotemeta(N(" (UNSUPPORTED)"));
    $s =~ s/$unsuppstr$//;
    if ($scanner::scannerDB->{$s}{flags}{unsupported}) {
	$in->ask_warn('Scannerdrake', N("The %s is not supported under Linux.", removeverticalbar($s)));
	return 0;
    }
    return tryConfScanner($s, $port, $vendor, $product);
}

sub dynamic() {
    @f = scanner::detect();
    my $name;
    foreach (@f) { 
	if (member($_->{val}{DESCRIPTION}, keys %$scanner::scannerDB)) {
	    $name = $_->{val}{DESCRIPTION};
	    $name =~ s/\s$//; #some HP entry have a trailing space, i will correct usbtable asap
	    next if ($scanner::scannerDB->{$name}{flags}{unsupported});
	    if (my @modules = @{$scanner::scannerDB->{$name}{kernel}}) {
		modules::load(@modules);
		modules::append_to_modules_loaded_at_startup_for_all_kernels(@modules);
	    }
	    scanner::confScanner($name, $_->{port},
				 $_->{val}{vendor}, $_->{val}{id}, "");
	}
    }
}

sub installfirmware {
    my ($model, $backend) = @_;
    my $firmware;
    my $choice = N("Do not install firmware file");
    while (1) {
	# Tell user about firmware installation
	$in->ask_from('Scannerdrake',
		      N("It is possible that your %s needs its firmware to be uploaded everytime when it is turned on.", removeverticalbar($model)) . " " .
		      N("If this is the case, you can make this be done automatically.") . " " .
		      N("To do so, you need to supply the firmware file for your scanner so that it can be installed.") . " " .
		      N("You find the file on the CD or floppy coming with the scanner, on the manufacturer's home page, or on your Windows partition."),
		      [
		       { label => N("Install firmware file from"), 
			 val => \$choice,
			 list => [N("CD-ROM"),
				  N("Floppy Disk"), 
				  N("Other place"),
				  N("Do not install firmware file")], 
			 not_edit => 1, sort => 0 },
		       ],
		      ) or return "///";
	my $dir;
	if ($choice eq N("CD-ROM")) {
	    $dir = "/mnt/cdrom";
	} elsif ($choice eq N("Floppy Disk")) {
	    $dir = "/mnt/floppy";
	} elsif ($choice eq N("Other place")) {
	    $dir = "/mnt";
	} else {
	    return "";
	}
	# Let user select a firmware file from a floppy, hard disk, ...
        $firmware = $in->ask_file(N("Select firmware file"), "$dir");
	last if !$firmware || (-r $firmware);
	$in->ask_warn(N("Error"),
		      N("The firmware file %s does not exist or is unreadable!",
			$firmware));
	
    }
    # Install the firmware file in /usr/share/sane/firmware
    $firmware = scanner::installfirmware($firmware, $backend);
    return $firmware;
}

sub updatefirmware {
    my (@configured) = @_;
    my $firmware;
    my @scanners =
	map { 
	    $_->{val}{DESCRIPTION}
	} grep { 
	    $_->{val}{FIRMWARELINE}
	} @configured;
    my ($scannerchoice, $mediachoice);
    while (1) {
	# Tell user about firmware installation
	$in->ask_from('Scannerdrake',
		      ($#scanners > 0 ?
		       N("It is possible that your scanners need their firmware to be uploaded everytime when they are turned on.") :
		       N("It is possible that your %s needs its firmware to be uploaded everytime when it is turned on.", $scanners[0])) . " " .
		      N("If this is the case, you can make this be done automatically.") . " " .
		      ($#scanners > 0 ?
		       N("To do so, you need to supply the firmware files for your scanners so that it can be installed.") :
		       N("To do so, you need to supply the firmware file for your scanner so that it can be installed.")) . " " .
		       N("You find the file on the CD or floppy coming with the scanner, on the manufacturer's home page, or on your Windows partition.") . "\n" .
		      N("If you have already installed your scanner's firmware you can update the firmware here by supplying the new firmware file."),
		      [
		       { label => N("Install firmware for the"), 
			 val => \$scannerchoice,
			 list => \@scanners, 
			 not_edit => 1, sort => 1 },
		       { label => N("Install firmware file from"), 
			 val => \$mediachoice,
			 list => [N("CD-ROM"),
				  N("Floppy Disk"), 
				  N("Other place")], 
			 not_edit => 1, sort => 0 },
		       ],
		      ) or return 0;
	my $dir;
	if ($mediachoice eq N("CD-ROM")) {
	    $dir = "/mnt/cdrom";
	} elsif ($mediachoice eq N("Floppy Disk")) {
	    $dir = "/mnt/floppy";
	} elsif ($mediachoice eq N("Other place")) {
	    $dir = "/mnt";
	} else {
	    return 0;
	}
	# Let user select a firmware file from a floppy, hard disk, ...
        $firmware = $in->ask_file(N("Select firmware file for the %s",
				    $scannerchoice), "$dir");
	last if !$firmware || (-r $firmware);
	$in->ask_warn(N("Error"),
		      N("The firmware file %s does not exist or is unreadable!",
			$firmware));
	
    }

    return 0 if !$firmware;

    foreach (@configured) {
	next if $_->{val}{DESCRIPTION} ne $scannerchoice; 
	# Install the firmware file in /usr/share/sane/firmware
	my $backend = $_->{val}{BACKEND};
	$firmware = scanner::installfirmware($firmware, $backend);
	if (!$firmware) {
	    $in->ask_warn('Error',
			  N("Could not install the firmware file for the %s!",
			    $scannerchoice));
	    return 0;
	}
	# Enter the path to the firmware in the appropriate config file
	my $firmwareline =$_->{val}{FIRMWARELINE};
	$firmwareline =~ s/\$FIRMWARE/$firmware/sg;
	scanner::setfirmware($backend, $firmwareline);
	last;
    }

    # Success message
    $in->ask_warn('Scannerdrake',
		  N("The firmware file for your %s was successfully installed.",
		    $scannerchoice));
    
    return 1;
}

sub tryConfScanner {
    # take care if interactive output is needed (unsupported, parallel..)
    my ($model, $port, $vendor, $product) = @_;
    if ($scanner::scannerDB->{$model}{flags}{unsupported}) {
	$in->ask_warn('Scannerdrake', N("The %s is unsupported", 
					removeverticalbar($model)));
	return 0;
    }
    if ($scanner::scannerDB->{$model}{server} =~ /(printerdrake|hpoj|hpaio|hplip)/i) {
     	$in->ask_warn('Scannerdrake', N("The %s must be configured by printerdrake.\nYou can launch printerdrake from the %s Control Center in Hardware section.", removeverticalbar($model), $shortdistroname));
     	return 0;
    }
    if ($scanner::scannerDB->{$model}{ask} =~ /DEVICE/ || !$port) {
	$port ||= N("Auto-detect available ports");
	$in->ask_from('Scannerdrake',
		      N("Please select the device where your %s is attached", removeverticalbar($model)) . " " .
		      N("(Note: Parallel ports cannot be auto-detected)"),
		      [
		       { label => N("choose device"), 
			 val => \$port,
			 list => [N("Auto-detect available ports"),
				  '/dev/scanner', 
				  '/dev/usb/scanner0',
				  '/dev/usb/scanner1',
				  '/dev/usb/scanner2',
				  'libusb:001:001',
				  'libusb:001:002',
				  'libusb:001:003',
				  'libusb:001:004',
				  'libusb:001:005',
				  'libusb:001:006',
				  'libusb:001:007',
				  'libusb:001:008',
				  'libusb:001:009',
				  'libusb:001:010', 
				  '/dev/sg0',
				  '/dev/sg1',
				  '/dev/sg2',
				  '/dev/sg3',
				  '/dev/sg4',
				  '/dev/parport0',
				  '/dev/parport1',
				  '/dev/parport2',
				  '/dev/pt_drv',
				  '/dev/ttyS0',
				  '/dev/ttyS1',
				  '/dev/ttyS2'], 
			 not_edit => 0, sort => 0 },
		       ],
		      ) or return 0;
	if ($port eq N("Auto-detect available ports")) {
	    $wait = $in->wait_message(N("Scannerdrake"),
				      N("Searching for scanners..."));
	    my @d = scanner::detect();
	    undef $wait;
	    my @list = map {
		$_->{port} . " (" .
		    removeverticalbar($_->{val}{DESCRIPTION}) . ")";
	    } @d;
	    $port ||= $list[0];
	    $in->ask_from('Scannerdrake',
			  N("Please select the device where your %s is attached", removeverticalbar($model)),
			  [
			   { label => N("choose device"), 
			     val => \$port,
			     list => \@list,
			     not_edit => 1, sort => 0 },
			   ],
			  ) or return 0;
	    $port =~ s/^\s*([^\(\s]*)\s*\(.*$/$1/;
	    foreach (@d) {
		next if $_->{port} ne $port;
		$vendor = $_->{val}{vendor};
		$product = $_->{val}{id};
		last;
	    }
	}
    }
    ($vendor, $product) = scanner::get_usb_ids_for_port($port);
    my $firmware;
    my $server = $scanner::scannerDB->{$model}{server};
    if (grep { /FIRMWARELINE/ } @{$scanner::scannerDB->{$model}{lines}} ) {
	$firmware = installfirmware($model, $server);
	return 0 if $firmware eq "///";
    }
    if (defined($scanner::scannerDB->{$model}{kernel})) {
	my @modules = @{$scanner::scannerDB->{$model}{kernel}};
	my $wait = $in->wait_message(N("Scannerdrake"),
				     N("Setting up kernel modules..."));
	modules::load(@modules);
	modules::append_to_modules_loaded_at_startup_for_all_kernels(@modules);
    }
    scanner::confScanner($model, $port, $vendor, $product, $firmware);
    if ($scanner::scannerDB->{$model}{flags}{manual} == 2) {
	# MANUALREQUIRED in ScannerDB
	$in->ask_warn(N("Attention!"),
		      N("Your %s cannot be configured fully automatically.\n\nManual adjustments are required. Please edit the configuration file /etc/sane.d/%s.conf. ", removeverticalbar($model), $server) .
		      N("More info in the driver's manual page. Run the command \"man sane-%s\" to read it.", $server) .
		      "\n\n" .
		      N("After that you may scan documents using \"XSane\" or \"Kooka\" from Multimedia/Graphics in the applications menu."));
    } elsif ($scanner::scannerDB->{$model}{flags}{manual} == 1) {
	# MANUAL in ScannerDB
	$in->ask_warn(N("Attention!"),
		      N("Your %s has been configured, but it is possible that additional manual adjustments are needed to get it to work. ", removeverticalbar($model)) .
		      N("If it does not appear in the list of configured scanners in the main window of Scannerdrake or if it does not work correctly, ") .
		      N("edit the configuration file /etc/sane.d/%s.conf. ", $server) .
		      N("More info in the driver's manual page. Run the command \"man sane-%s\" to read it.", $server) .
		      "\n\n" .
		      N("After that you may scan documents using \"XSane\" or \"Kooka\" from Multimedia/Graphics in the applications menu."));
    } else {
	$in->ask_warn(N("Congratulations!"),
		      N("Your %s has been configured.\nYou may now scan documents using \"XSane\" or \"Kooka\" from Multimedia/Graphics in the applications menu.", removeverticalbar($model)));
    }
    return 1;
}

sub quit() {
    $in->exit(0);
}

sub mainwindow {
    my @configured = @_;
    # main loop
    my $maindone;
    while (!$maindone) {
	# Generate list of configured scanners
	my $msg = do {
	    if (@configured) {
		my @scannerlist = 
		    map {
			my $entry = $_->{val}{DESCRIPTION};
			if_($entry, "  -  $entry\n");
		    } @configured;
		if (@scannerlist) {
		    my $main_msg = 
			@scannerlist > 1 ?
			N_("The following scanners\n\n%s\nare available on your system.\n") :
			N_("The following scanner\n\n%s\nis available on your system.\n");
		    sprintf($main_msg, join('', @scannerlist));
		} else {
		    N("There are no scanners found which are available on your system.\n");
		}
	    } else {
		N("There are no scanners found which are available on your system.\n");
	    }
	};
	my $buttonclicked;
	#- Show dialog
	if ($in->ask_from_
	    (
	     { 
		 title => N("Scannerdrake"),
		 messages => $msg,
		 ok => "",
		 cancel => "",
	     },
	     [
	      { val => N("Search for new scanners"),
		type => 'button',
		clicked_may_quit => sub {
		    $buttonclicked = "autoadd";
		    1;
		} },
	      { val => N("Add a scanner manually"),
		type => 'button',
		clicked_may_quit => sub {
		    $buttonclicked = "manualadd";
		    1;
		} },
	      ( (grep { $_->{val}{FIRMWARELINE} } @configured) ?
		{ val => N("Install/Update firmware files"),
		  type => 'button',
		  clicked_may_quit => sub {
		      $buttonclicked = "firmware";
		      1;
		  } } : () ),
	      { val => N("Scanner sharing"),
		type => 'button',
		clicked_may_quit => sub {
		    $buttonclicked = "sharing";
		    1;
		} },
	      { val => N("Quit"),
		type => 'button',
		clicked_may_quit => sub {
		    $buttonclicked = "quit";
		    1;
		} },
	      ]
	     )
	    ) {
	    my $changed = 0;
	    if ($buttonclicked eq "autoadd") {
		# Do scanner auto-detection
		my $wait =
		    $in->wait_message(N("Scannerdrake"),
				      N("Searching for configured scanners..."));
		@configured = scanner::configured();
		$wait = 
		    $in->wait_message(N("Scannerdrake"),
				      N("Searching for new scanners..."));
		my @f = scanner::detect(@configured);
		$wait = undef;
		if (@f) { 
		    $changed = auto();
		}
	    } elsif ($buttonclicked eq "manualadd") {
		# Show dialogs to manually add a scanner
		$changed = manual();
	    } elsif ($buttonclicked eq "sharing") {
		# Show dialog to set up scanner sharing
		$changed = sharewindow(@configured);
	    } elsif ($buttonclicked eq "firmware") {
		# Show dialog to select the firmware file
		updatefirmware(@configured);
	    } elsif ($buttonclicked eq "quit") {
		# We have clicked "Quit"
		$maindone = 1;
	    }
	    if ($changed) {
		my $_wait =
		    $in->wait_message(N("Scannerdrake"),
				      N("Re-generating list of configured scanners..."));
		@configured = scanner::configured();
	    }
	} else {
	    # Cancel clicked
	    $maindone = 1;
	}
    }
}

sub makeexportmenues {
    my @exports = @_;
    my %menuexports = map {
	($_ eq '+' ? N("All remote machines") : $_) => $_;
    } map {
	# Remove comments and blank lines
	(/^\s*($|#)/ ? () : chomp_($_));
    } @exports;
    my %menuexports_inv = reverse %menuexports;
    return (\%menuexports, \%menuexports_inv);
}

sub makeimportmenues {
    my @imports = @_;
    my %menuimports = map {
	($_ eq 'localhost' ? N("This machine") : $_) => $_;
    } map {
	# Remove comments and blank lines
	if_(!/^\s*($|#)/, chomp_($_));
    } @imports;
    my %menuimports_inv = reverse %menuimports;
    return (\%menuimports, \%menuimports_inv);
}

sub sharewindow {
    my @_configured = @_;
    # Read list of hosts to where to export the local scanners
    my @exports = cat_("/etc/sane.d/saned.conf");
    my ($menuexports, $menuexports_inv) =
	makeexportmenues(@exports);
    # Read list of hosts from where to import scanners
    my @imports = cat_("/etc/sane.d/net.conf");
    my ($menuimports, $menuimports_inv) =
	makeimportmenues(@imports);
    # Is saned running?
    my $sanedrunning = services::starts_on_boot("saned");
    my $oldsanedrunning = $sanedrunning;
    # Is the "net" SANE backend active
    my $netbackendactive = grep { /^\s*net\s*$/ }
      cat_("/etc/sane.d/dll.conf");
    my $oldnetbackendactive = $netbackendactive;
    # Set this to 1 to tell the caller that the list of locally available
    # scanners has changed (Here if the SANE client configuration has
    # changed)
    my $changed = 0;
    my $importschanged = 0;
    # main loop
    my $maindone;
    while (!$maindone) {
	my $buttonclicked;
	#- Show dialog
	if ($in->ask_from_
	    (
	     { 
		 title => N("Scannerdrake"),
		 messages => N("Here you can choose whether the scanners connected to this machine should be accessible by remote machines and by which remote machines.") .
                     N("You can also decide here whether scanners on remote machines should be made available on this machine."),
	     },
	     [
	      { text => N("The scanners on this machine are available to other computers"), type => 'bool',
		val => \$sanedrunning },
	      { val => N("Scanner sharing to hosts: ") .
		    (keys %$menuexports > 0 ?
		     (keys %$menuexports > 2 ?
		      join(", ", (keys %$menuexports)[0,1]) . " ..." :
		      join(", ", keys %$menuexports)) :
		     N("No remote machines")), 
		type => 'button',
		clicked_may_quit => sub {
		    $buttonclicked = "exports";
		    1;
		},
		disabled => sub {
		    !$sanedrunning;
		} },
	      { text => N("Use scanners on remote computers"),
		type => 'bool',
		val => \$netbackendactive },
	      { val => N("Use the scanners on hosts: ") .
		    (keys %$menuimports > 0 ?
		     (keys %$menuimports > 2 ?
		      join(", ", (keys %$menuimports)[0,1]) . " ..." :
		      join(", ", keys %$menuimports)) :
		     N("No remote machines")), 
		type => 'button',
		clicked_may_quit => sub {
		    $buttonclicked = "imports";
		    1;
		},
		disabled => sub {
		    !$netbackendactive;
		} },
	      ]
	     )
	    ) {
	    if ($buttonclicked eq "exports") {
		# Show dialog to add hosts to share scanners to
		my $subdone = 0;
		my $choice;
		while (!$subdone) {
		    my @list = keys %$menuexports;
		    # Entry should be edited when double-clicked
		    $buttonclicked = "edit";
		    $in->ask_from_
			(
			 { title => N("Sharing of local scanners"),
			   messages => N("These are the machines on which the locally connected scanner(s) should be available:"),
			   ok => "",
			   cancel => "",
		         },
			 # List the hosts
			 [ { val => \$choice, format => \&translate,
			     sort => 0, separator => "####",
			     tree_expanded => 1,
			     quit_if_double_click => 1,
			     allow_empty_list => 1,
			     list => \@list },
			   { val => N("Add host"), 
			     type => 'button',
			     clicked_may_quit => sub {
				 $buttonclicked = "add";
				 1; 
			     } },
			   { val => N("Edit selected host"), 
			     type => 'button',
			     clicked_may_quit => sub {
				 $buttonclicked = "edit";
				 1; 
			     },
			     disabled => sub {
				 return ($#list < 0);
			     } },
			   { val => N("Remove selected host"), 
			     type => 'button',
			     clicked_may_quit => sub {
				 $buttonclicked = "remove";
				 1; 
			     },
			     disabled => sub {
				 return ($#list < 0);
			     } },
			   { val => N("Done"), 
			     type => 'button',
			     clicked_may_quit => sub {
				 $buttonclicked = "";
				 $subdone = 1;
				 1; 
			     } },
			   ]
			 );
		    if ($buttonclicked eq "add" ||
			$buttonclicked eq "edit") {
			my ($hostchoice, $ip);
			if ($buttonclicked eq "add") {
			    # Use first entry as default for a new entry
			    $hostchoice = 
				N("Name/IP address of host:");
			} else {
			    if ($menuexports->{$choice} eq '+') {
				# Entry is "All hosts"
				$hostchoice = $choice;
			    } else {
				# Entry is a name/an IP address
				$hostchoice = 
				    N("Name/IP address of host:");
				$ip = $choice;
			    }
			}
			my @menu = (N("All remote machines"),
			            N("Name/IP address of host:"));
			# Show the dialog
			my $address;
			my $oldaddress = 
			    ($buttonclicked eq "edit" ?
			     $menuexports->{$choice} : "");
			if ($in->ask_from_
			    (
			     { title => N("Sharing of local scanners"),
			       messages => N("Choose the host on which the local scanners should be made available:"),
			       callbacks => {
				   complete => sub {
				       if ($hostchoice eq $menu[0]) {
					   $address = "+";
				       } elsif ($hostchoice eq $menu[1]) {
					   $address = $ip;
				       }
				       # Do not allow an empty address
				       if ($address !~ /\S/) {
					   $in->ask_warn(N("Error"), 
							 N("You must enter a host name or an IP address.\n"));
					   return (1,0);
				       }
				       # Strip off leading and trailing
				       # spaces
				       $address =~ s/^\s*(.*?)\s*$/$1/;
				       # Check whether item is duplicate
				       if ($address ne $oldaddress &&
					   member("$address\n",
						   @exports)) {
					   $in->ask_warn(N("Error"), 
							 N("This host is already in the list, it cannot be added again.\n"));
					   return (1,1);
				       }
				       return 0;
				   },
			       },
			   },
			     # List the host types
			     [ { val => \$hostchoice, format => \&translate,
				 type => 'list',
				 sort => 0,
				 list => \@menu },
			       { val => \$ip, 
				 disabled => sub {
				     $hostchoice ne 
					 N("Name/IP address of host:");
			         } },
			       ],
			     )) {
			    # OK was clicked, insert new item into the list
			    if ($buttonclicked eq "add") {
				handle_configs::set_directive(\@exports,
							      $address);
			    } else {
				handle_configs::replace_directive(\@exports,
								  $oldaddress,
								  $address);
			    }
			    # Refresh list of hosts
			    ($menuexports, $menuexports_inv) =
				makeexportmenues(@exports);
			    # Position the list cursor on the new/modified
			    # item
			    $choice = $menuexports_inv->{$address};
			}
		    } elsif ($buttonclicked eq "remove") {
			my $address = $menuexports->{$choice};
			handle_configs::remove_directive(\@exports,
							 $address);
			# Refresh list of hosts
			($menuexports, $menuexports_inv) =
			    makeexportmenues(@exports);
		    }
		}
	    } elsif ($buttonclicked eq "imports") {
		# Show dialog to add hosts on which the scanners should be
		# used
		my $subdone = 0;
		my $choice;
		while (!$subdone) {
		    my @list = keys %$menuimports;
		    # Entry should be edited when double-clicked
		    $buttonclicked = "edit";
		    $in->ask_from_
			(
			 { title => N("Usage of remote scanners"),
			   messages => N("These are the machines from which the scanners should be used:"),
			   ok => "",
			   cancel => "",
		         },
			 # List the hosts
			 [ { val => \$choice, format => \&translate,
			     sort => 0, separator => "####",
			     tree_expanded => 1,
			     quit_if_double_click => 1,
			     allow_empty_list => 1,
			     list => \@list },
			   { val => N("Add host"), 
			     type => 'button',
			     clicked_may_quit => sub {
				 $buttonclicked = "add";
				 1; 
			     } },
			   { val => N("Edit selected host"), 
			     type => 'button',
			     clicked_may_quit => sub {
				 $buttonclicked = "edit";
				 1; 
			     },
			     disabled => sub {
				 return ($#list < 0);
			     } },
			   { val => N("Remove selected host"), 
			     type => 'button',
			     clicked_may_quit => sub {
				 $buttonclicked = "remove";
				 1; 
			     },
			     disabled => sub {
				 return ($#list < 0);
			     } },
			   { val => N("Done"), 
			     type => 'button',
			     clicked_may_quit => sub {
				 $buttonclicked = "";
				 $subdone = 1;
				 1; 
			     } },
			   ]
			 );
		    if ($buttonclicked eq "add" ||
			$buttonclicked eq "edit") {
			my ($hostchoice, $ip);
			if ($buttonclicked eq "add") {
			    # Use first entry as default for a new entry
			    $hostchoice = 
				N("Name/IP address of host:");
			} else {
			    if ($menuimports->{$choice} eq 'localhost') {
				# Entry is "This machine"
				$hostchoice = $choice;
			    } else {
				# Entry is a name/an IP address
				$hostchoice = 
				    N("Name/IP address of host:");
				$ip = $choice;
			    }
			}
			my @menu = (N("This machine"),
			            N("Name/IP address of host:"));
			# Show the dialog
			my $address;
			my $oldaddress = 
			    ($buttonclicked eq "edit" ?
			     $menuimports->{$choice} : "");
			if ($in->ask_from_
			    (
			     { title => N("Sharing of local scanners"),
			       messages => N("Choose the host on which the local scanners should be made available:"),
			       callbacks => {
				   complete => sub {
				       if ($hostchoice eq $menu[0]) {
					   $address = 'localhost';
				       } elsif ($hostchoice eq $menu[1]) {
					   $address = $ip;
				       }
				       # Do not allow an empty address
				       if ($address !~ /\S/) {
					   $in->ask_warn(N("Error"), 
							 N("You must enter a host name or an IP address.\n"));
					   return (1,0);
				       }
				       # Strip off leading and trailing
				       # spaces
				       $address =~ s/^\s*(.*?)\s*$/$1/;
				       # Check whether item is duplicate
				       if ($address ne $oldaddress &&
					   member("$address\n",
						   @imports)) {
					   $in->ask_warn(N("Error"), 
							 N("This host is already in the list, it cannot be added again.\n"));
					   return (1,1);
				       }
				       return 0;
				   },
			       },
			   },
			     # List the host types
			     [ { val => \$hostchoice, format => \&translate,
				 type => 'list',
				 sort => 0,
				 list => \@menu },
			       { val => \$ip, 
				 disabled => sub {
				     $hostchoice ne 
					 N("Name/IP address of host:");
			         } },
			       ],
			     )) {
			    # OK was clicked, insert new item into the list
			    if ($buttonclicked eq "add") {
				handle_configs::set_directive(\@imports,
							      $address);
			    } else {
				handle_configs::replace_directive(\@imports,
								  $oldaddress,
								  $address);
			    }
			    $importschanged = 1;
			    # Refresh list of hosts
			    ($menuimports, $menuimports_inv) =
				makeimportmenues(@imports);
			    # Position the list cursor on the new/modified
			    # item
			    $choice = $menuimports_inv->{$address};
			}
		    } elsif ($buttonclicked eq "remove") {
			my $address = $menuimports->{$choice};
			handle_configs::remove_directive(\@imports,
							 $address);
			# Refresh list of hosts
			($menuimports, $menuimports_inv) =
			    makeimportmenues(@imports);
			$importschanged = 1;
		    }
		}
	    } else {
		# We have clicked "OK"
		$maindone = 1;
		if ($importschanged) {
		    $changed = 1;
		}
		# Write /etc/sane.d/saned.conf
		output("/etc/sane.d/saned.conf", @exports);
		# Write /etc/sane.d/net.conf
		output("/etc/sane.d/net.conf", @imports);
		# Turn on/off saned
		if ($sanedrunning != $oldsanedrunning) {
		    if ($sanedrunning) {
			# Make sure saned and xinetd is installed and 
			# running
			if (!files_exist('/usr/sbin/xinetd',
					 '/usr/sbin/saned')) {
			    if (!$in->ask_yesorno(N("Warning"), N("saned needs to be installed to share the local scanner(s).

Do you want to install the saned package?"))) {
				$in->ask_warn("Scannerdrake", 
					      N("Your scanner(s) will not be available on the network."));
			    } elsif (!$in->do_pkgs->install('xinetd', 'saned')) {
				$in->ask_warn(N("Error"),
					      N("Could not install the packages needed to share your scanner(s).") . " " .
					      N("Your scanner(s) will not be available on the network."));
			    }
			}
			# Start saned and make sure that it gets started on
			# every boot
			services::start_service_on_boot("saned");
			services::start_service_on_boot("xinetd");
			services::restart("xinetd");
		    } else {
			# Stop saned and make sure that it does not get
			# started when booting
			services::do_not_start_service_on_boot("saned");
			services::restart("xinetd");
		    }
		}
		# Turn on/off "net" SANE backend
		if ($netbackendactive != $oldnetbackendactive) {
		    my @dllconf = cat_("/etc/sane.d/dll.conf");
		    if ($netbackendactive) {
			handle_configs::set_directive(\@dllconf, "net");
		    } else {
			handle_configs::comment_directive(\@dllconf, "net");
		    }
		    output("/etc/sane.d/dll.conf", @dllconf);
		    $changed = 1;
		}
	    }
	} else {
	    # Cancel clicked
	    $maindone = 1;
	}
    }
    return $changed;
}