summaryrefslogtreecommitdiffstats
path: root/perl-install/standalone/printerdrake
blob: 7bc4e1387d9906a6bf8be07df8350871b43dbf2d (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
#!/usr/bin/perl
#
# Copyright (C) 2003-2005 Mandriva
#
# Till Kamppeter <till at mandriva.com>
# Daouda Lo <daouda at mandriva.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License Version 2 as
# published by the Free Software Foundation.
#
# 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 strict;

# i18n: IMPORTANT: to get correct namespace (printerdrake instead of 
# libDrakX)
BEGIN { unshift @::textdomains, 'drakconf' }

use lib qw(/usr/lib/libDrakX);
use standalone;

use common;
use any;

use ugtk2 qw(:all);
use interactive;
use POSIX qw(mktime ceil);
use printer::printerdrake;
use printer::main;
#Only for Debugging 
#use Devel::Peek;
use Gtk2::Gdk::Keysyms;
use modules;
use c;

my %sysh = distrib();
my $distroname = $sysh{system};

my $domainname = "mandriva.com";

my $pixdir = '/usr/share/libDrakX/pixmaps/';

my $refreshinterval = 5;

local $_ = join '', @ARGV;

my $printer;

$ugtk2::wm_icon = "printerdrake";
my $in = 'interactive'->vnew('su', if_(!$::isEmbedded, 'printer-mdk'));

my $commandline = $_;

# Suppress some wait messages to avoid windows popping up if no new print 
# queue has to be set up
$commandline =~ /-onlyautoqueue/ and $::autoqueue = 1;

# Data structure for GTK2 main window
my $us = {};
$us->{VERSION} = '2006';

# Check whether Foomatic is installed and install it if necessary
#printer::printerdrake::install_foomatic($in);

my $w = $::autoqueue ||
    $in->wait_message(N("Printerdrake"),
		      N("Reading data of installed printers..."));

# Get what was installed before
eval { $printer = printer::main::getinfo('') };

undef $w;

exit 0 unless printer::printerdrake::first_time_dialog($printer, $in, undef);

# Were we in expert mode last time?
$printer->{expert} = printer::main::get_usermode();

# Choose the spooler by command line options
$::expert and $printer->{expert} = 1;
$commandline =~ /-cups/ and
    $printer->{SPOOLER} = 'cups' and printer::main::read_configured_queues($printer);
$commandline =~ /-rcups/ and
    $printer->{SPOOLER} = 'rcups' and printer::main::read_configured_queues($printer);
$commandline =~ /-lpr/ and 
    $printer->{SPOOLER} = 'lpd'  and printer::main::read_configured_queues($printer);
$commandline =~ /-lpd/ and 
    $printer->{SPOOLER} = 'lpd'  and printer::main::read_configured_queues($printer);
$commandline =~ /-lprng/ and 
    $printer->{SPOOLER} = 'lprng' and printer::main::read_configured_queues($printer);
$commandline =~ /-pdq/ and 
    $printer->{SPOOLER} = 'pdq'  and printer::main::read_configured_queues($printer);

if ($::isInstall) {
    # Interactive main window for installation
    printer::printerdrake::main($printer, $::o->{security}, $in, 1, undef);
    exit();
}

require security::level;
my $security = security::level::get();

# Do not let printerdrake ask for the spooler
$printer->{SPOOLER} ||= 'cups';

# Initialization
printer::printerdrake::init($printer, $security, $in, undef);

# Stop here when we are supposed to only automatically set up print queues
$commandline =~ /-onlyautoqueue/ and exit 0;

# GTK2 main window

my $stringsearch = '';

sub HelpSystem() { exec("drakhelp --id printerdrake") unless fork() }

$::noborderWhenEmbedded = 1;
$us->{wnd} = ugtk2->new(N("%s Printer Management Tool", $distroname) . " " . $us->{VERSION});
gtkset_size_request($us->{wnd}{rwindow}, 660, 460);

if (!$::isEmbedded) {
    $us->{wnd}{rwindow}->set_position('center');
}
$us->{wnd}{window}->signal_connect(delete_event => \&QuitGlobal);
my $ltree_model = Gtk2::ListStore->new("Glib::String", "Glib::String", "Glib::String", "Glib::String", "Glib::String", "Glib::String", "Glib::String");
my $rtree_model = Gtk2::ListStore->new("Glib::String", "Glib::String", "Glib::String", "Glib::String", "Glib::String", "Glib::String");
my ($localtree, $remotetree);
$localtree = CreateTree($ltree_model);
$remotetree = CreateTree($rtree_model);
# slightly verbatimed from control-center
my %options = (
	       'add' => [ N("/_Actions"), N("/_Add Printer") ],
	       'default' => [ N("/_Actions"), N("/Set as _Default") ],
	       'edit' => [ N("/_Actions"), N("/_Edit") ],
	       'delete' => [ N("/_Actions"), N("/_Delete") ],
	       'expert' => [ N("/_Options"), N("/_Expert mode") ]
	      );
my %buttorcheck;
my ($menu, $factory) = create_factory_menu($::isEmbedded ? $::Plug : $us->{wnd}{rwindow},
                                           ([ N("/_File"), undef, undef, undef, '<Branch>' ],
                                            [ N("/_File") . N("/_Refresh"), undef, sub { Refresh($stringsearch) }, undef, '<StockItem>', 'gtk-refresh' ],
                                            [ N("/_File") . N("/_Quit"), N("<control>Q"), \&QuitGlobal, undef, '<StockItem>', 'gtk-quit' ],
                                            [ N("/_Actions"), undef, undef, undef, '<Branch>' ],
                                            [ N("/_Actions") . N("/_Add Printer"), undef, \&AddPrinter, undef, '<StockItem>', 'gtk-add' ],
                                            [ join('', @{$options{default}}), undef, \&SetAsDefault, undef, '<StockItem>', 'gtk-default' ],
                                            [ join('', @{$options{edit}}), undef, \&Edit, undef, '<StockItem>', 'gtk-properties' ],
                                            [ join('', @{$options{delete}}), undef, \&Delete, undef, '<StockItem>', 'gtk-delete' ],
                                            [ N("/_Actions") . N("/_Configure CUPS"), undef, \&ConfigCUPS, undef, '<StockItem>', 'gtk-config' ],
                                            [ N("/_Options"), undef, undef, undef, '<Branch>' ],
                                            [ join('', @{$options{expert}}), undef, sub {
                                                  $printer->{expert} = $buttorcheck{expert}->get_active;
						  # Remember state of expert
						  # mode for next
						  # printerdrake session
						  printer::main::set_usermode($printer->{expert});
						  # Read printer database
						  # for the new user mode
						  %printer::main::thedb = 
						      ();
                                              }, undef, '<CheckItem>' ],
                                            [ N("/_Options") . N("/Configure _Auto Administration"), undef, \&ConfigAutoAdmin, undef, '<StockItem>', 'gtk-autoadmin' ],
                                            [ N("/_Help"), undef, undef, undef, '<Branch>' ],
					    if_(-x "/usr/sbin/drakhelp_inst",
						[ N("/_Help") . N("/_Help"), undef, sub { HelpSystem() }, undef, '<StockItem>', 'gtk-help' ],
					       ),
					    if_(!-e "/etc/sysconfig/oem",
						[ N("/_Help") . N("/_Report Bug"), undef, sub { system("$ENV{BROWSER} https://qa.$domainname &") }, undef, '<StockItem>', 'gtk-stop' ],
					       ),
                                            [ N("/_Help") . N("/_About..."), undef, \&About, undef, '<StockItem>', 'gtk-preferences' ]
					   )
					  );
%buttorcheck = map {  $_ => $factory->get_widget("<main>" . join '', map { s/_//; $_ } @{$options{$_}}) } ('add', 'default', 'edit', 'delete', 'expert');

if (defined $buttorcheck{expert}) {
    $buttorcheck{expert}->set_active($printer->{expert});
} else {
    print STDERR "BUG with LANGUAGE $ENV{LANGUAGE}\n";
}

my $toolb = Gtk2::Toolbar->new;
my $filter;
my $searchBox = gtkpack_(Gtk2::HBox->new(0,5),
                         1, Gtk2::Label->new(""),
                         0, Gtk2::Label->new(N("Search:")),
                         0, gtksignal_connect($filter = Gtk2::Entry->new,
				       key_press_event => sub { $_[1]->keyval == $Gtk2::Gdk::Keysyms{Return} and do { $stringsearch = $filter->get_text; Refresh($stringsearch) };}),
                         0, my $fbut = Gtk2::Button->new(N("Apply filter")),
                        );
gtkappend_page(my $nb = Gtk2::Notebook->new, gtkpack(create_scrolled_window($localtree)), gtkshow(Gtk2::Label->new(N("Configured on this machine"))));
gtkappend_page($nb, gtkpack(create_scrolled_window($remotetree)), gtkshow(Gtk2::Label->new(N("Configured on other machines"))));
$nb->set_show_border(0);

my @extra_widgets;
if ($::isEmbedded) {
	push @extra_widgets, 0, Gtk2::Banner->new("/usr/share/mcc/themes/default/printer-mcc-mdk.png",
		#-PO: do not translate, this is already translated in mcc
		translate("Printers"));
}	 

$us->{wnd}{window}->add(gtkpack_(Gtk2::VBox->new(0, 0),
				  0, $menu,
				  @extra_widgets,
				  0, $toolb,
				  0, $searchBox,
				  0, Gtk2::HSeparator->new,
				  1, $nb));
my @lcolsize = (1, 1, 1, 1, 1, 1, 1, -1);
my @rcolsize = (1, 1, 1, 1, 1, 1, -1);
each_index {
    my $col = Gtk2::TreeViewColumn->new_with_attributes($_, Gtk2::CellRendererText->new, 'text' => $::i);
    $col->set_sort_column_id($::i);
    $col->set_min_width($lcolsize[$::i]);
    $localtree->append_column($col);
} (N("Def."), N("Printer Name"), N("State"), N("Model"), N("Connection Type"), N("Description"), N("Location"));

each_index {
    my $col = Gtk2::TreeViewColumn->new_with_attributes($_, Gtk2::CellRendererText->new, 'text' => $::i);
    $col->set_sort_column_id($::i);
    $col->set_min_width($rcolsize[$::i]);
    $remotetree->append_column($col);
} (N("Def."), N("Printer Name"), N("State"), N("Server Name"), N("Description"), N("Location"));
my @toolbwg = map {
    $toolb->append_item($_->[0], $_->[1], $_->[2],  
                        Gtk2::Image->new_from_file($pixdir . $_->[2] . '.png'), $_->[3], $toolb);
#    $toolb->append_space;
} ([
     # FIXME: then "add printer" should be a simple verb as suggested in Human Guidelines!!!
     #-PO: "Add Printer" is a button text and the translation has to be AS SHORT AS POSSIBLE
     N("Add Printer"), N("Add a new printer to the system"), 'printer_add', \&AddPrinter ], 
    [
     #-PO: "Set as default" is a button text and the translation has to be AS SHORT AS POSSIBLE
     N("Set as default"), N("Set selected printer as the default printer"), 'printer_default', \&SetAsDefault ],
    [ 
     #-PO: "Edit" is a button text and the translation has to be AS SHORT AS POSSIBLE
     N("Edit"), N("Edit selected printer"), 'printer_conf', \&Edit ],
    [ 
     #-PO: "Delete" is a button text and the translation has to be AS SHORT AS POSSIBLE
     N("Delete"), N("Delete selected printer"), 'printer_del', \&Delete ],
    [ 
     #-PO: "Refresh" is a button text and the translation has to be AS SHORT AS POSSIBLE
     N("Refresh"), N("Refresh the list"), 'refresh', sub { Refresh($stringsearch) } ],
    [
     #-PO: "Configure CUPS" is a button text and the translation has to be AS SHORT AS POSSIBLE
     N("Configure CUPS"), N("Configure CUPS printing system"), 'cups_config', \&ConfigCUPS ]
  );
my ($tbadd, $tbdefault, $tbedit, $tbdel, $_tbref, $_tbconfig) = @toolbwg;
GrayDelEdit();
foreach ($tbadd, $buttorcheck{add}) { defined $_ and $_->set_sensitive($printer->{SPOOLER} ne "rcups") }
$localtree->parent->parent->set_sensitive($printer->{SPOOLER} ne "rcups");
$nb->set_current_page(1) if $printer->{SPOOLER} eq "rcups";

$fbut->signal_connect('clicked', sub { $stringsearch = $filter->get_text; Refresh($stringsearch) });
Refresh($stringsearch);
$nb->signal_connect('switch-page' => sub { NotebookSwitch() });
$us->{wnd}{rwindow}->show_all;
set_selection($printer->{DEFAULT});
gtkset_mousecursor_normal();

# Prevent subwindows to embed themselves in the mcc which has already the
# main window embedded
my $isEmbedded = $::isEmbedded;
local $::isEmbedded = 0;

# Auto refresh
my $refreshing = 0;
Glib::Timeout->add($refreshinterval * 1000, 
		   sub { Refresh($stringsearch); 1 });

$us->{wnd}->main;
ugtk2->exit;

sub GrayDelEdit() {
    foreach ($tbdefault, $tbedit, $tbdel, $buttorcheck{default}, $buttorcheck{edit}, $buttorcheck{delete}) { defined $_ and $_->set_sensitive(0) }
}

sub TreeUnselect {
    my $treev = shift;
    $treev->get_selection->unselect_all;
    GrayDelEdit();
}
sub NotebookSwitch() { 
    TreeUnselect($localtree);
    TreeUnselect($remotetree);
    #set_selection_on_first();
}

sub RefreshLocalPrintersFull {
    my ($strfilt, @allprinters) = @_;
    my @printers;
    defined $printer and @printers = keys %{$printer->{configured}};
    $ltree_model->clear;
    return if $printer->{SPOOLER} eq "rcups";
    my @LocalReal;
    foreach my $p (@printers) {
	# Apply string search to all fields, not only the printer name
	my $state = ($printer->{SPOOLER} !~ /cups/ ? N("Unknown") :
		     ((any { 
			 ($_->{queuename} eq $p) &&
			     ($_->{state} eq "enabled");  
		     } @allprinters) ? N("Enabled") : N("Disabled")));
	my $connect = printer::main::connectionstr($printer->{configured}{$p}{queuedata}{connect});
	my $model = $printer->{configured}{$p}{queuedata}{make} . ' ' .
	    $printer->{configured}{$p}{queuedata}{model};
	my $description = $printer->{configured}{$p}{queuedata}{desc};
	my $location = $printer->{configured}{$p}{queuedata}{loc};
	my $searchstr = "$p|$state|$model|$connect|$description|$location";
	push(@LocalReal, $p) if !$strfilt || ($searchstr =~ /\Q$strfilt/i);
    }
    foreach my $p (sort { lc($a) cmp lc($b) } @LocalReal) {
	my $state = ($printer->{SPOOLER} !~ /cups/ ? N("Unknown") :
		     ((any { 
			 ($_->{queuename} eq $p) &&
			     ($_->{state} eq "enabled");  
		     } @allprinters) ? N("Enabled") : N("Disabled")));
	my $connect = printer::main::connectionstr($printer->{configured}{$p}{queuedata}{connect});
	my $description = $printer->{configured}{$p}{queuedata}{desc};
	my $location = $printer->{configured}{$p}{queuedata}{loc};
	my $model = $printer->{configured}{$p}{queuedata}{make} . ' ' .
	    $printer->{configured}{$p}{queuedata}{model};
	my $default = ($p eq $printer->{DEFAULT} ? "X" : "");
	$ltree_model->append_set([ 0 => $default, 1 => $p, 2 => $state, 
				   3 => $model, 
				   4 => $connect, 5 => $description,
				   6 => $location ]);
    }
}

sub RefreshRemotePrintersFull {
    my ($strfilt, @printers) = @_;
    $rtree_model->clear;
    my @RemoteReal;
    LOOP: foreach my $p (@printers) {
	# No locally defined queues
	next LOOP if defined($printer->{configured}{$p->{queuename}});
	# Apply string search to all fields, not only the printer name
	my $queue = $p->{queuename};
	my $state = ($p->{state} eq "enabled" ?
		     N("Enabled") : N("Disabled"));
	my $server = $p->{ipp} || $printer->{remote_cups_server};
	my $description = $p->{description};
	my $location = $p->{location};
	my $searchstr = "$queue|$state|$server|$description|$location";
	# All remaining to which the search term applies
	push(@RemoteReal, $p) if !$strfilt || ($searchstr =~ /\Q$strfilt/i);
    }
    foreach my $p (sort { lc($a->{queuename}) cmp lc($b->{queuename}) } 
		   @RemoteReal) {
	my $queue = $p->{queuename};
	my $state = ($p->{state} eq "enabled" ?
		     N("Enabled") : N("Disabled"));
	my $server = $p->{ipp} || $printer->{remote_cups_server};
	my $description = $p->{description};
	my $location = $p->{location};
	my $default = ($queue eq $printer->{DEFAULT} ? "X" : "");
	$rtree_model->append_set([ 0 => $default, 1 => $queue, 
				   2 => $state, 3 => $server,
				   4 => $description,
				   5 => $location ]);
    }
}

sub Refresh {
    # Do not have ourselves recalled if we are already running
    return if $refreshing;
    $refreshing = 1;
    my ($strfilt) = @_;
    my $selection = get_selection();
    printer::services::wait_for_cups();
    my @printers;
    defined $printer and @printers = printer::cups::lpstat_lpv();
    RefreshLocalPrintersFull($strfilt, @printers); 
    RefreshRemotePrintersFull($strfilt, @printers);
    GrayDelEdit();
    set_selection($selection);
    $refreshing = 0;
}

sub AddPrinter() {
    deactivate_mainwindow();
    if (printer::printerdrake::add_printer($printer, $in, undef)) {
	Refresh($stringsearch);
	set_selection($printer->{QUEUE});
    } else {
	delete($printer->{QUEUE});
    }
    activate_mainwindow();
}

sub SetAsDefault() {
    deactivate_mainwindow();
    my $queue = get_selection();
    printer::printerdrake::default_printer($printer, $in, $queue);
    Refresh($stringsearch);
    activate_mainwindow();
}

sub Edit() {
    deactivate_mainwindow();
    my $queue = get_selection();
    printer::printerdrake::edit_printer($printer, $in, undef, $queue);
    Refresh($stringsearch);
    if ($printer->{QUEUE}) {
	set_selection($printer->{QUEUE});
#    } else {
#	set_selection_on_first();
    }
    activate_mainwindow();
}

sub Delete() {
    deactivate_mainwindow();
    my $queue = get_selection();
    if (printer::printerdrake::remove_printer($printer, $in, $queue)) {
	Refresh($stringsearch);
	set_selection_on_first();
    } else {
	delete($printer->{QUEUE});
    }
    activate_mainwindow();
}

sub ConfigCUPS() {
    deactivate_mainwindow();
    printer::printerdrake::config_cups($printer, $security, $in, undef);
    foreach ($tbadd, $buttorcheck{add}) { defined $_ and $_->set_sensitive($printer->{SPOOLER} ne "rcups") }
    $localtree->parent->parent->set_sensitive($printer->{SPOOLER} ne "rcups");
    $nb->set_current_page(1) if $printer->{SPOOLER} eq "rcups";
    Refresh($stringsearch);
    activate_mainwindow();
}

sub ConfigAutoAdmin() {
    deactivate_mainwindow();
    printer::printerdrake::config_auto_admin($printer, $in);
    Refresh($stringsearch);
    activate_mainwindow();
}

sub deactivate_mainwindow() {
    $us->{wnd}{rwindow}->set_sensitive(0);
    gtkset_mousecursor_wait();
}

sub activate_mainwindow() {
    $us->{wnd}{rwindow}->set_sensitive(1);
    gtkset_mousecursor_normal();
}

sub set_selection_on_first() {
    # On which page are we currently
    my $page = $nb->get_current_page;
    my ($tree, $model);
    if ($page <= 0) {
	# Locally defined printer: first page
	$tree = $localtree;
	$model = $ltree_model;
    } elsif ($page == 1) {
	# Remotely defined printer: second page
	$tree = $remotetree;
	$model = $rtree_model;
    }
    my $iter = $model->get_iter_first;
    $tree->get_selection->select_iter($iter) if $iter;
}

sub set_selection {
    my ($queue) = @_;
    return if !$queue;
    my ($tree, $model, $page);
    if (defined($printer->{configured}{$queue})) {
	# Locally defined printer: first page
	$tree = $localtree;
	$model = $ltree_model;
	$page = 0;
    } else {
	# Remotely defined printer: second page
	$tree = $remotetree;
	$model = $rtree_model;
	$page = 1;
    }
    # Search entry on page
    my $iter = $model->get_iter_first;
    while ($iter) {
	my $q = $model->get($iter, 1);
	if ($q eq $queue) {
	    $tree->get_selection->select_iter($iter);
	    $nb->set_current_page($page);
	    return;
	}
	$iter = $model->iter_next($iter);
    }
    # Requested entry does not exist, go to the first entry on the current
    # page.
    set_selection_on_first();
}

sub get_selection() {
    my $queue;
    my $page = $nb->get_current_page;
    if ($page <= 0) {
	$queue = GetNameEntFromIter($localtree, $ltree_model, 1);
    } elsif ($page == 1) {
	$queue = GetNameEntFromIter($remotetree, $rtree_model, 1);
    }
    return $queue;
}

sub GetNameEntFromIter {
    my ($tree, $model, $rank) = @_;
    my (undef, $iter) = $tree->get_selection->get_selected;
    return undef if !defined($iter);
    my $name = $model->get($iter, $rank);
    $name;
}

sub CreateTree {
    my ($tree_model) = @_;
    my $tree = Gtk2::TreeView->new_with_model($tree_model);
    $tree->get_selection->set_mode('browse');
    $tree->set_headers_visible(1);
    $tree->set_rules_hint(1);
    $tree->get_selection->signal_connect('changed' => sub {
			       my (undef, $_event) = @_;
			       my (undef, $iter) = $tree->get_selection->get_selected;
			       return unless $iter;
                               foreach ($tbdefault, $tbedit, $tbdel, $buttorcheck{default}, $buttorcheck{edit}, $buttorcheck{delete}) { $_->set_sensitive(1) }
			       my $queue = $tree_model->get($iter, 1);
			       if (!defined($printer->{configured}{$queue})) {
				   foreach ($tbdel, $buttorcheck{delete}) { 
				       $_->set_sensitive(0);
				   }
			       }
			       if ($queue eq $printer->{DEFAULT}) {
				   foreach ($tbdefault, $buttorcheck{default}) { 
				       $_->set_sensitive(0);
				   }
			       }
			       });
    $tree->signal_connect(button_press_event => sub {
			       my (undef, $event) = @_;
			       my (undef, $iter) = $tree->get_selection->get_selected;
			       return unless $iter;
			       foreach ($tbdefault, $tbedit, $tbdel, $buttorcheck{default}, $buttorcheck{edit}, $buttorcheck{delete}) { $_->set_sensitive(1) }
			       my $queue = $tree_model->get($iter, 1);
			       if (!defined($printer->{configured}{$queue})) {
				   foreach ($tbdel, $buttorcheck{delete}) { 
				       $_->set_sensitive(0);
				   }
			       }
			       if ($queue eq $printer->{DEFAULT}) {
				   foreach ($tbdefault, $buttorcheck{default}) { 
				       $_->set_sensitive(0);
				   }
			       }
			       Edit() if $event->type eq '2button-press';
			      });
    $tree->signal_connect(key_press_event => sub {
			       my (undef, $event) = @_;
			       my (undef, $iter) = $tree->get_selection->get_selected;
			       return unless $iter;
			       Edit() if $event->keyval == $Gtk2::Gdk::Keysyms{Return};
			   });
    $tree;
}

sub NewDialog {
    my ($title, $o_no_button) = @_;
    my $dialog = gtkset_border_width(Gtk2::Dialog->new, 10);
    $dialog->set_transient_for($us->{wnd}{real_window});
    $dialog->set_position('center-on-parent');
    $dialog->set_title($title);
    $dialog->action_area->pack_start(gtkadd(Gtk2::HButtonBox->new,
                                            gtksignal_connect(Gtk2::Button->new(N("Close")), clicked => sub { $dialog->destroy })
                                            ),
                                     0,0,0) unless $o_no_button;
    gtkset_modal($dialog, 1);
}

sub About() {
    my $window_about = NewDialog(N("Printerdrake"));
    my $tree_model = Gtk2::TreeStore->new("Glib::String", "Glib::String", "Glib::String");
    my $list = Gtk2::TreeView->new_with_model($tree_model);
    $list->can_focus(0);
    each_index { $list->append_column(Gtk2::TreeViewColumn->new_with_attributes(undef, Gtk2::CellRendererText->new, 'text' => $::i)) } 0..2;
    $list->set_headers_visible(0);
    foreach my $row ([ '', '', '' ], [ N("Authors: "), 'Till Kamppeter', "<till\@$domainname>" ], [ '', '', '' ]) {
        $tree_model->append_set(undef, [ map_index { $::i => $_ } @$row ]);
    }
    $list->get_selection->set_mode('none');
    gtkpack_($window_about->vbox,
             -r "$pixdir/about-printerdrake.png" ?
             (0, Gtk2::Image->new_from_file("$pixdir/about-printerdrake.png")) :
               (1, gtkset_markup(Gtk2::Label->new, 
                                 qq(<span weight="bold" size="x-large">) .
                                   #-PO: here %s is the version number
                                   N("Printer Management %s", $us->{VERSION}) . "</span>"),
            ),
	     1, $list,
	    );
    $window_about->show_all;
}

sub QuitGlobal() {
    gtkset_mousecursor_normal();
    Gtk2->main_quit;
}
ref='#n1376'>1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
package ugtk2;

use diagnostics;
use strict;
use vars qw(@ISA %EXPORT_TAGS @EXPORT_OK @icon_paths $force_center $force_focus $force_position $grab $pop_it $border); #- leave it on one line, for automatic removal of the line at package creation
use lang;

$::o = { locale => lang::read() } if !$::isInstall;

@ISA = qw(Exporter);
%EXPORT_TAGS = (
    wrappers => [ qw(gtkadd gtkappend gtkappend_page gtkappenditems gtkcombo_setpopdown_strings gtkdestroy
                     gtkentry gtkflush gtkhide gtkmodify_font gtkmove gtkpack gtkpack2 gtkpack2_
                     gtkpack2__ gtkpack_ gtkpack__ gtkpowerpack gtkput gtkradio gtkresize gtkroot
                     gtkset_active gtkset_border_width gtkset_editable gtkset_justify gtkset_alignment gtkset_layout gtkset_line_wrap
                     gtkset_markup gtkset_modal gtkset_mousecursor gtkset_mousecursor_normal gtkset_mousecursor_wait gtkset_name
                     gtkset_property gtkset_relief gtkset_selectable gtkset_sensitive gtkset_shadow_type gtkset_size_request
                     gtkset_text gtkset_tip gtkset_visibility gtksetstyle gtkshow gtksignal_connect gtksize gtktext_append
                     gtktext_insert ) ],

    helpers => [ qw(add2notebook add_icon_path fill_tiled fill_tiled_coords get_text_coord gtkcolor gtkcreate_img
                    gtkcreate_pixbuf gtkfontinfo gtkset_background n_line_size set_back_pixbuf string_size
                    string_width string_height wrap_paragraph) ],

    create => [ qw(create_adjustment create_box_with_title create_dialog create_factory_menu create_factory_popup_menu
                   create_hbox create_hpaned create_menu create_notebook create_okcancel create_packtable
                   create_scrolled_window create_vbox create_vpaned _create_dialog ) ],

    ask => [ qw(ask_browse_tree_info ask_browse_tree_info_given_widgets ask_dir ask_from_entry ask_okcancel ask_warn
                ask_yesorno ) ],
    dialogs => [ qw(err_dialog info_dialog warn_dialog) ],

);
$EXPORT_TAGS{all} = [ map { @$_ } values %EXPORT_TAGS ];
@EXPORT_OK = map { @$_ } values %EXPORT_TAGS;

use c;
use log;
use common;

use Gtk2;
use Gtk2::Gdk::Keysyms;

unless ($::no_ugtk_init) {
    !check_for_xserver() and die "Cannot be run in console mode.\n";
    $::one_message_has_been_translated and warn("N() was called from $::one_message_has_been_translated BEFORE gtk2 initialisation, replace it with a N_() AND a translate() later.\n"), c::_exit(1);

    Gtk2->init;
    c::bind_textdomain_codeset($_, 'UTF8') foreach 'libDrakX', @::textdomains;
    $::need_utf8_i18n = 1;
}


$border = 5;


# -=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---
#                 wrappers
#
# Functional-style wrappers to existing Gtk functions; allows to program in
# a more functional way, and especially, first, to avoid using temp
# variables, and second, to "see" directly in the code the user interface
# you're building.

sub gtkdestroy                { $_[0] and $_[0]->destroy }
sub gtkflush()                { Gtk2->main_iteration while Gtk2->events_pending }
sub gtkhide                   { $_[0]->hide; $_[0] }
sub gtkmove                   { $_[0]->window->move($_[1], $_[2]); $_[0] }
sub gtkpack                   { gtkpowerpack(1, 1, @_) }
sub gtkpack_                  { gtkpowerpack('arg', 1, @_) }
sub gtkpack__                 { gtkpowerpack(0, 1, @_) }
sub gtkpack2                  { gtkpowerpack(1, 0, @_) }
sub gtkpack2_                 { gtkpowerpack('arg', 0, @_) }
sub gtkpack2__                { gtkpowerpack(0, 0, @_) }
sub gtkput                    { $_[0]->put(gtkshow($_[1]), $_[2], $_[3]); $_[0] }
sub gtkresize                 { $_[0]->window->resize($_[1], $_[2]); $_[0] }
sub gtkset_active             { $_[0]->set_active($_[1]); $_[0] }
sub gtkset_border_width       { $_[0]->set_border_width($_[1]); $_[0] }
sub gtkset_editable           { $_[0]->set_editable($_[1]); $_[0] }
sub gtkset_selectable         { $_[0]->set_selectable($_[1]); $_[0] }
sub gtkset_justify            { $_[0]->set_justify($_[1]); $_[0] }
sub gtkset_alignment          { $_[0]->set_alignment($_[1], $_[2]); $_[0] }
sub gtkset_layout             { $_[0]->set_layout($_[1]); $_[0] }
sub gtkset_modal              { $_[0]->set_modal($_[1]); $_[0] }
sub gtkset_mousecursor_normal { gtkset_mousecursor('left-ptr', @_) }
sub gtkset_mousecursor_wait   { gtkset_mousecursor('watch', @_) }
sub gtkset_relief             { $_[0]->set_relief($_[1]); $_[0] }
sub gtkset_sensitive          { $_[0]->set_sensitive($_[1]); $_[0] }
sub gtkset_visibility         { $_[0]->set_visibility($_[1]); $_[0] }
sub gtkset_tip                { $_[0]->set_tip($_[1], $_[2]) if $_[2]; $_[1] }
sub gtkset_shadow_type        { $_[0]->set_shadow_type($_[1]); $_[0] }
sub gtkset_style              { $_[0]->set_style($_[1]); $_[0] }
sub gtkset_size_request       { $_[0]->set_size_request($_[1], $_[2]); $_[0] }
sub gtkshow                   { $_[0]->show; $_[0] }
sub gtksize                   { $_[0]->size($_[1], $_[2]); $_[0] }
sub gtkset_markup             { $_[0]->set_markup($_[1]); $_[0] }
sub gtkset_line_wrap          { $_[0]->set_line_wrap($_[1]); $_[0] }

sub gtkadd {
    my $w = shift;
    foreach (@_) {
	my $l = $_;
	ref $l or $l = Gtk2::Label->new($l);
	$w->add(gtkshow($l));
    }
    $w
}

sub gtkappend {
    my $w = shift;
    foreach (@_) {
	my $l = $_;
	ref $l or $l = Gtk2::Label->new($l);
	$w->append(gtkshow($l));
    }
    $w
}

sub gtkappenditems {
    my $w = shift;
    $_->show foreach @_;
    $w->append_items(@_);
    $w
}

# append page to a notebook
sub gtkappend_page {
    my $w = shift;
    $w->append_page(@_);
    $w
}

sub gtkentry {
    my ($text) = @_;
    my $e = Gtk2::Entry->new;
    $text and $e->set_text($text);
    $e;
}

sub gtksetstyle { 
    my ($w, $s) = @_;
    $w->set_style($s);
    $w;
}

sub gtkradio {
    my $def = shift;
    my $radio;
    map { gtkset_active($radio = Gtk2::RadioButton->new_with_label($radio ? $radio->get_group : undef, $_), $_ eq $def) } @_;
}

sub gtkroot() {
    my $root if 0;
    $root ||= Gtk2::Gdk->get_default_root_window;
}

sub gtkset_text {
    my ($w, $s) = @_;
    $w->set_text($s);
    $w;
}

sub gtkcombo_setpopdown_strings {
    my $w = shift;
    $w->set_popdown_strings(@_);
    $w;
}

sub gtkset_mousecursor {
    my ($type, $w) = @_;
    ($w || gtkroot())->set_cursor(Gtk2::Gdk::Cursor->new($type));
}

sub gtksignal_connect {
    my $w = shift;
    $w->signal_connect(@_);
    $w;
}

sub gtkset_name {
    my ($widget, $name) = @_;
    $widget->set_name($name);
    $widget;
}


sub gtkpowerpack {
    #- Get Default Attributes (if any). 2 syntaxes allowed :
    #- gtkpowerpack( {expand => 1, fill => 0}, $box...) : the attributes are picked from a specified hash ref
    #- gtkpowerpack(1, 0, 1, $box, ...) : the attributes are picked from the non-ref list, in the order (expand, fill, padding, pack_end).
    my @attributes_list = qw(expand fill padding pack_end);
    my $default_attrs = {};
    if (ref($_[0]) eq 'HASH') {
	$default_attrs = shift;
    } elsif (!ref($_[0])) {
	foreach (@attributes_list) {
	    ref($_[0]) and last;
	    $default_attrs->{$_} = shift;
	}
    }
    my $box = shift;

    while (@_) {
	#- Get attributes (if specified). 4 syntaxes allowed (default values are undef ie. false...) :
	#- gtkpowerpack({defaultattrs}, $box, $widget1, $widget2, ...) : the attrs are picked from the default ones (if they exist)
	#- gtkpowerpack($box, {fill=>1, expand=>0, ...}, $widget1, ...) : the attributes are picked from a specified hash ref
	#- gtkpowerpack($box, [1,0,1], $widget1, ...) : the attributes are picked from the array ref : (expand, fill, padding, pack_end).
	#- gtkpowerpack({attr=>'arg'}, $box, 1, $widget1, 0, $widget2, etc...) : the 'arg' value will tell gtkpowerpack to always read the 
	#- attr value directly in the arg list (avoiding confusion between value 0 and Gtk::Label("0"). That can simplify some writings but
	#- this arg(s) MUST then be present...
	my (%attr, $attrs);
	ref($_[0]) eq 'HASH' || ref($_[0]) eq 'ARRAY' and $attrs = shift;
	foreach (@attributes_list) {
	    if (($default_attrs->{$_} || '') eq 'arg') {
		ref($_[0]) and die "error in packing definition\n";
		$attr{$_} = shift;
		ref($attrs) eq 'ARRAY' and shift @$attrs;
	    } elsif (ref($attrs) eq 'HASH' && defined($attrs->{$_})) {
		$attr{$_} = $attrs->{$_};
	    } elsif (ref($attrs) eq 'ARRAY') {
		$attr{$_} = shift @$attrs;
	    } elsif (defined($default_attrs->{$_})) {
		$attr{$_} = int $default_attrs->{$_};
	    } else {
		$attr{$_} = 0;
	    }
	}
	#- Get and pack the widget (create it if necessary to  a label...)
	my $widget = ref($_[0]) ? shift : Gtk2::Label->new(shift);
	my $pack_call = 'pack_'.($attr{pack_end} ? 'end' : 'start');
	$box->$pack_call($widget, $attr{expand}, $attr{fill}, $attr{padding});
	$widget->show;
    }
    return $box;
}

sub gtktreeview_children {
    my ($model, $iter) = @_;
    my @l;
    $model && $iter or return;
    for (my $p = $model->iter_children($iter); $p; $p = $model->iter_next($p)) {
	push @l, $p;
    }
    @l;
}



# -=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---
#                 create
#
# Helpers that allow omitting common operations on common widgets
# (e.g. create widgets with good default properties)

sub create_pixbutton {
    my ($label, $pix, $reverse_order) = @_;
    my @label_and_pix = (0, $label, if_($pix, 0, $pix));
    gtkadd(Gtk2::Button->new,
	   gtkpack_(Gtk2::HBox->new(0, 3),
		    1, "",
		    $reverse_order ? reverse(@label_and_pix) : @label_and_pix,
		    1, ""));
}

sub create_adjustment {
    my ($val, $min, $max) = @_;
    Gtk2::Adjustment->new($val, $min, $max + 1, 1, ($max - $min + 1) / 10, 1);
}

sub create_scrolled_window {
    my ($W, $o_policy, $o_viewport_shadow) = @_;
    my $w = Gtk2::ScrolledWindow->new(undef, undef);
    $w->set_policy($o_policy ? @$o_policy : ('automatic', 'automatic'));
    if (member(ref($W), qw(Gtk2::Layout Gtk2::Text Gtk2::TextView Gtk2::TreeView))) {
	$w->add($W)
    } else {
	$w->add_with_viewport($W);
    }
    $o_viewport_shadow and gtkset_shadow_type($w->child, $o_viewport_shadow);
    $W->can('set_focus_vadjustment') and $W->set_focus_vadjustment($w->get_vadjustment);
    $W->show;
    if (ref($W) eq 'Gtk2::TextView') {
    	gtkadd(gtkset_shadow_type(Gtk2::Frame->new, 'in'), $w)
    } else {
	$w
    }
}

sub n_line_size {
    my ($nbline, $type, $widget) = @_;
    my $spacing = ${{ text => 3, various => 17 }}{$type};
    my %fontinfo = gtkfontinfo($widget);
    round($nbline * ($fontinfo{ascent} + $fontinfo{descent} + $spacing) + 8);
}

sub create_box_with_title {
    my $o = shift;

    my $nbline = sum(map { round(length($_) / 60 + 1/2) } map { split "\n" } @_);
    my $box = Gtk2::VBox->new(0,0);
    if ($nbline == 0) {
	$o->{box_size} = 0;
	return $box;
    }
    $o->{box_size} = n_line_size($nbline, 'text', $box);
    if (@_ <= 2 && $nbline > 4) {
	$o->{icon} && !$::isWizard and 
	  eval { gtkpack__($box, gtkset_border_width(gtkpack_(Gtk2::HBox->new(0,0), 1, gtkcreate_img($o->{icon})),5)) };
	my $wanted = $o->{box_size};
	$o->{box_size} = min(200, $o->{box_size});
	my $has_scroll = $o->{box_size} < $wanted;

	my $wtext = Gtk2::TextView->new;
	$wtext->set_left_margin(3);
	$wtext->can_focus($has_scroll);
	$wtext->signal_connect(button_press_event => sub { 1 }); #- disable selecting text and popping the contextual menu (GUI team says it's *horrible* to be able to do select text!)
	chomp(my $text = join("\n", @_));
	my $scroll = create_scrolled_window(gtktext_insert($wtext, $text));
	$scroll->set_size_request(400, $o->{box_size});
	gtkpack_($box, 0, $scroll);
    } else {
	my $a = !$::no_separator;
	undef $::no_separator;
     my $new_label = sub {
         my ($txt) = @_;
         my $w = ref($txt) ? $txt : Gtk2::WrappedLabel->new($txt);
         gtkset_name($w, "Title");
     };
	if ($o->{icon} && (!$::isWizard || $::isInstall)) {
	    gtkpack__($box,
		      gtkpack_(Gtk2::HBox->new(0,0),
			       0, gtkset_size_request(Gtk2::VBox->new(0,0), 15, 0),
			       0, eval { gtkcreate_img($o->{icon}) },
			       0, gtkset_size_request(Gtk2::VBox->new(0,0), 15, 0),
			       1, gtkpack_($o->{box_title} = Gtk2::VBox->new(0,0),
					   1, Gtk2::HBox->new(0,0),
					   (map {
					       my $w = $new_label->($_);
					       $::isWizard and $w->set_justify("left");
					       (0, $w);
					   } map { ref($_) ? $_ : warp_text($_) } @_),
					   1, Gtk2::HBox->new(0,0),
					  )
			      ),
		      if_($a, Gtk2::HSeparator->new)
		     )
	} else {
	    gtkpack__($box,
		      if_($::isWizard, gtkset_size_request(Gtk2::Label->new, 0, 10)),
		      (map {
			  my $w = $new_label->($_);
			  $::isWizard ? gtkpack__(Gtk2::HBox->new(0,0), gtkset_size_request(Gtk2::Label->new, 20, 0), $w)
			              : $w
		      } map { ref($_) ? $_ : warp_text($_) } @_),
		      if_($::isWizard, gtkset_size_request(Gtk2::Label->new, 0, 15)),
		      if_($a, Gtk2::HSeparator->new)
		     )
	}
    }
}

sub _create_dialog {
    my ($title, $o_options) = @_;
    my $dialog = Gtk2::Dialog->new;
    $dialog->set_title($title);
    $dialog->set_position('center-on-parent');  # center-on-parent doesn't work
    $dialog->set_size_request($o_options->{width} || -1, $o_options->{height} || -1);
    $dialog->set_modal(1);
    $dialog->set_transient_for($o_options->{transient}) if $o_options->{transient};
    $dialog;
}


# drakfloppy / drakfont / harddrake2 / mcc
sub create_dialog {
    my ($title, $label, $o_options) = @_;
    my $ret = 0;
    my $dialog = _create_dialog($title, $o_options);
    $dialog->set_border_width(10);
    my $text = ref($label) ? $label : $o_options->{use_markup} ? gtkset_markup(Gtk2::WrappedLabel->new, $label) : Gtk2::WrappedLabel->new($label);
    gtkpack($dialog->vbox,
            gtkpack_(Gtk2::HBox->new,
                     if_($o_options->{stock}, 0, Gtk2::Image->new_from_stock($o_options->{stock}, 'dialog')),
                     1, $o_options->{scroll} ? create_scrolled_window($text, [ 'never', 'automatic' ]) : $text,
                    ),
           );

    if ($o_options->{cancel}) {
	my $button2 = Gtk2::Button->new(N("Cancel"));
	$button2->signal_connect(clicked => sub { $ret = 0; $dialog->destroy; Gtk2->main_quit });
	$button2->can_default(1);
	$dialog->action_area->pack_start($button2, 1, 1, 0);
    }

    my $button = Gtk2::Button->new(N("Ok"));
    $button->can_default(1);
    $button->signal_connect(clicked => sub { $ret = 1; $dialog->destroy; Gtk2->main_quit });
    $dialog->action_area->pack_start($button, 1, 1, 0);
    $button->grab_default;

    $dialog->show_all;
    Gtk2->main;
    $ret;
}

sub info_dialog {
    my ($title, $label, $o_options) = @_;
    $o_options ||= { };
    add2hash_($o_options, { stock => 'gtk-dialog-info' });
    create_dialog($title, $label, $o_options);
}

sub warn_dialog {
    my ($title, $label, $o_options) = @_;
    $o_options ||= { };
    add2hash_($o_options, { stock => 'gtk-dialog-warning', cancel => 1 });
    create_dialog($title, $label, $o_options);
}

sub err_dialog {
    my ($title, $label, $o_options) = @_;
    $o_options ||= { };
    add2hash_($o_options, { stock => 'gtk-dialog-error' });
    create_dialog($title, $label, $o_options);
}

sub create_hbox { gtkset_layout(gtkset_border_width(Gtk2::HButtonBox->new, 3), $_[0] || 'spread') }
sub create_vbox { gtkset_layout(Gtk2::VButtonBox->new, $_[0] || 'spread') }

sub create_factory_menu_ {
    my ($type, $name, $window, @menu_items) = @_;
    my $widget = Gtk2::ItemFactory->new($type, $name, my $accel_group = Gtk2::AccelGroup->new);
    $widget->create_items($window, @menu_items);
    $window->add_accel_group($accel_group);
    ($widget->get_widget($name), $widget);
}

sub create_factory_popup_menu { create_factory_menu_("Gtk2::Menu", '<main>', @_) }
sub create_factory_menu { create_factory_menu_("Gtk2::MenuBar", '<main>', @_) }

sub create_menu {
    my $title = shift;
    my $w = Gtk2::MenuItem->new($title);
    $w->set_submenu(gtkshow(gtkappend(Gtk2::Menu->new, @_)));
    $w
}

sub create_notebook {
    my $n = Gtk2::Notebook->new;
    while (@_) {
	my ($title, $book) = splice(@_, 0, 2);
	add2notebook($n, $title, $book);
    }
    $n
}

sub create_packtable {
    my ($options, @l) = @_;
    my $w = Gtk2::Table->new(0, 0, $options->{homogeneous} || 0);
    each_index {
	my ($i, $l) = ($::i, $_);
	each_index {
	    my $j = $::i;
	    if ($_) {
		ref $_ or $_ = Gtk2::Label->new($_);
		$j != $#$l && !$options->{mcc} ?
		  $w->attach($_, $j, $j + 1, $i, $i + 1,
			     'fill', 'fill', 5, 0) :
		  $w->attach($_, $j, $j + 1, $i, $i + 1,
			     ['expand', 'fill'], ref($_) eq 'Gtk2::ScrolledWindow' || $_->get_data('must_grow') ? ['expand', 'fill'] : [], 0, 0);
		$_->show;
	    }
	} @$l;
    } @l;
    $w->set_col_spacings($options->{col_spacings} || 0);
    $w->set_row_spacings($options->{row_spacings} || 0);
    $w
}

sub create_okcancel {
    my ($w, $o_ok, $o_cancel, $o_spread, @other) = @_;
    my $wizard_buttons = $::isWizard && !$w->{pop_it};
    my $cancel = defined $o_cancel || defined $o_ok ? $o_cancel : $wizard_buttons ? N("<- Previous") : N("Cancel");
    my $ok = defined $o_ok ? $o_ok : $wizard_buttons ? ($::Wizard_finished ? N("Finish") : N("Next ->")) : N("Ok");
    my $b1 = gtksignal_connect($w->{ok} = Gtk2::Button->new($ok), clicked => $w->{ok_clicked} || sub { $w->{retval} = 1; Gtk2->main_quit });
    my $b2 = $cancel && gtksignal_connect($w->{cancel} = Gtk2::Button->new($cancel), clicked => $w->{cancel_clicked} || sub { log::l("default cancel_clicked"); undef $w->{retval}; Gtk2->main_quit });
    gtksignal_connect($w->{wizcancel} = Gtk2::Button->new(N("Cancel")), clicked => sub { die 'wizcancel' }) if $wizard_buttons && !$::isInstall;
    my @l = grep { $_ } $wizard_buttons ? (if_(!$::isInstall, $w->{wizcancel}), 
                                           if_(!$::Wizard_no_previous, $b2), $b1) : ($::isInstall ? ($b1, $b2) : $b2, $b1);
    my @l2 = map { gtksignal_connect(Gtk2::Button->new($_->[0]), clicked => $_->[1]) } grep {  $_->[2] } @other;
    my @r2 = map { gtksignal_connect(Gtk2::Button->new($_->[0]), clicked => $_->[1]) } grep { !$_->[2] } @other;

    my $box = create_hbox($o_spread || "edge");
    
    $box->pack_start($_, 0, 0, 1) foreach @l2;
    $box->pack_end($_, 0, 0, 1) foreach uniq(@r2, @l);
    foreach (@l2, @r2, @l) {
	$_->show;
	$_->can_default($wizard_buttons);
    }
    $box;
}

sub _setup_paned {
    my ($paned, $child1, $child2, %options) = @_;
    foreach ([ 'resize1', 0 ], [ 'shrink1', 1 ], [ 'resize2', 1 ], [ 'shrink2', 1 ]) {
        $options{$_->[0]} = $_->[1] unless defined($options{$_->[0]});
    }
    $paned->pack1(gtkshow($child1), $options{resize1}, $options{shrink1});
    $paned->pack2(gtkshow($child2), $options{resize2}, $options{shrink2});
    gtkshow($paned);
}

sub create_vpaned {
    _setup_paned(Gtk2::VPaned->new, @_);
}

sub create_hpaned {
    _setup_paned(Gtk2::HPaned->new, @_);
}


# -=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---
#                 helpers
#
# Functions that do typical operations on widgets, that you may need in
# several places of your programs.

sub _find_imgfile {
    my ($f, @extensions) = shift;
    @extensions or @extensions = qw(.png .xpm);
    if ($f !~ m|^/|) {
	foreach my $path (icon_paths()) {
	    -e "$path/$f$_" and $f = "$path/$f$_" foreach '', @extensions;
	}
    }
    return $f;
}

# use it if you want to display an icon/image in your app
sub gtkcreate_img {
    return Gtk2::Image->new_from_file(_find_imgfile(@_));
}

# use it if you want to draw an image onto a drawingarea
sub gtkcreate_pixbuf {
    return Gtk2::Gdk::Pixbuf->new_from_file(_find_imgfile(@_));
}

sub gtktext_append { gtktext_insert(@_, append => 1) }

# choose one of the two styles:
# - gtktext_insert($textview, "My text..");
# - gtktext_insert($textview, [ [ 'first text',  { 'foreground' => 'blue', 'background' => 'green', ... } ],
#			        [ 'second text' ],
#		                [ 'third', { 'font' => 'Serif 15', ... } ],
#                               ... ]);
sub gtktext_insert {
    my ($textview, $t, %opts) = @_;
    my $buffer = $textview->get_buffer;
    if (ref($t) eq 'ARRAY') {
        $opts{append} or $buffer->set_text('');
        foreach my $token (@$t) {
            my $iter1 = $buffer->get_end_iter;
            my $c = $buffer->get_char_count;
            if ($token->[0] =~ /^Gtk2::Gdk::Pixbuf/) {
                $buffer->insert_pixbuf($iter1, $token->[0]);
                next;
            }
            $buffer->insert($iter1, $token->[0]);
            if ($token->[1]) {
                my $tag = $buffer->create_tag(rand());
                $tag->set(%{$token->[1]});
                $buffer->apply_tag($tag, $iter1 = $buffer->get_iter_at_offset($c), $buffer->get_end_iter);
            }
        }
    } else {
        $buffer->set_text($t);
    }
    #- the following line is needed to move the cursor to the beginning, so that if the
    #- textview has a scrollbar, it won't scroll to the bottom when focusing (#3633)
    $buffer->place_cursor($buffer->get_start_iter);
    $textview->set_wrap_mode($opts{wrap_mode} || 'word');
    $textview->set_editable($opts{editable} || 0);
    $textview->set_cursor_visible($opts{visible} || 0);
    $textview;
}

# extracts interesting font metrics for a given widget
sub gtkfontinfo {
    my ($widget) = @_;
    my $context = $widget->get_pango_context;
    my $metrics = $context->get_metrics($context->get_font_description, $context->get_language);
    my %fontinfo;
    foreach (qw(ascent descent approximate_char_width approximate_digit_width)) {
	no strict;
	my $func = "get_$_";
	$fontinfo{$_} = Gtk2::Pango->pixels($metrics->$func);
    }
    %fontinfo;
}

sub gtkmodify_font {
    my ($w, $arg) = @_;
    $w->modify_font(ref($arg) ? $arg : Gtk2::Pango::FontDescription->from_string($arg));
    $w;
}

sub gtkset_property {
    my ($w, $property, $value) = @_;
    $w->set_property($property, $value);
    $w;
}

sub set_back_pixbuf {
    my ($widget, $pixbuf) = @_;
    my $window = $widget->window;
    my ($width, $height) = ($pixbuf->get_width, $pixbuf->get_height);
    my $pixmap = Gtk2::Gdk::Pixmap->new($window, $width, $height, $window->get_depth);
    $pixbuf->render_to_drawable($pixmap, $widget->style->fg_gc('normal'), 0, 0, 0, 0, $width, $height, 'none', 0, 0);
    $window->set_back_pixmap($pixmap, 0);
}

sub fill_tiled_coords {
    my ($widget, $pixbuf, $x_back, $y_back, $width, $height) = @_;
    my ($x2, $y2) = (0, 0);
    while (1) {
	$x2 = 0;
	while (1) {
	    $pixbuf->render_to_drawable($widget->window, $widget->style->fg_gc('normal'),
					0, 0, $x2, $y2, $x_back, $y_back, 'none', 0, 0);
	    $x2 += $x_back;
	    $x2 >= $width and last;
	}
	$y2 += $y_back;
	$y2 >= $height and last;
    }
}

sub fill_tiled {
    my ($widget, $pixbuf) = @_;
    my ($window_width, $window_height) = $widget->window->get_size;
    fill_tiled_coords($widget, $pixbuf, $pixbuf->get_width, $pixbuf->get_height, $window_width, $window_height);
}

sub add2notebook {
    my ($n, $title, $book) = @_;
    $n->append_page($book, gtkshow(Gtk2::Label->new($title)));
    $book->show;
}

sub string_size {
    my ($widget, $text) = @_;
    my $layout = $widget->create_pango_layout($text);
    my @size = $layout->get_pixel_size;
    @size;
}

sub string_width {
    my ($widget, $text) = @_;
    my ($width, undef) = string_size($widget, $text);
    $width;
}

sub string_height {
    my ($widget, $text) = @_;
    my (undef, $height) = string_size($widget, $text);
    $height;
}

sub get_text_coord {
    my ($text, $widget4style, $max_width, $max_height, $can_be_greater, $can_be_smaller, $centeredx, $centeredy, $o_wrap_char) = @_;
    my $wrap_char = $o_wrap_char || ' ';
    my $idx = 0;
    my $real_width = 0;
    my $real_height = 0;
    my @lines;
    my @widths;
    my @heights;
    $heights[0] = 0;
    my $max_width2 = $max_width;
    my $height = 0;
    my $width = 0;
    my $flag = 1;
    my @t = split($wrap_char, $text);
    my @t2;
    if ($::isInstall && $::o->{locale}{lang} =~ /ja|zh/) {
	@t = map { $_ . $wrap_char } @t;
	$wrap_char = '';
	foreach (@t) {
	    my @c = split('');
	    my $i = 0;
	    my $el = '';
	    while (1) {
		$i >= @c and last;
		$el .= $c[$i];
		if (ord($c[$i]) >= 128) { $el .= $c[$i+1]; $i++; push @t2, $el; $el = '' }
		$i++;
	    }
	    $el ne '' and push @t2, $el;
	}
    } else {
	@t2 = @t;
    }
    foreach (@t2) {
	my $l = string_width($widget4style, $_ . (!$flag ? $wrap_char : ''));
	if ($width + $l > $max_width2 && !$flag) {