summaryrefslogtreecommitdiffstats
path: root/perl-install/standalone.pm
blob: cae5a58c8453a3ef1c441b5fd0038e38bdfb4be7 (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
package standalone; # $Id: standalone.pm 262870 2009-10-27 10:53:55Z tv $

use c;
use strict;
use subs qw(exit);
use common qw(N N_ if_ backtrace);
use Config;

BEGIN { unshift @::textdomains, 'libDrakX-standalone' }

#- for sanity (if a use standalone is made during install, MANY problems will happen)
require 'log.pm'; #- "require log" causes some pb, perl thinking that "log" is the log() function
if ($::isInstall) {
    log::l('ERROR: use standalone made during install :-(');
    log::l('backtrace: ' . backtrace());
}
$::isStandalone = 1;

$ENV{SHARE_PATH} ||= "/usr/share";

eval { #- allow standalone.pm to be used in drakxtools-backend without perl-Locale-gettext
    c::init_setlocale();
    Locale::gettext::bindtextdomain('libDrakX', "/usr/share/locale");
};

$::license = N_("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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
");

my $progname = common::basename($0);

my %usages = (
           'diskdrake' => "[--{" . join(",", qw(hd nfs smb dav removable fileshare)) . "}]",
           'drakbackup' => N_("[--config-info] [--daemon] [--debug] [--default] [--show-conf]
Backup and Restore application

--default             : save default directories.
--debug               : show all debug messages.
--show-conf           : list of files or directories to backup.
--config-info         : explain configuration file options (for non-X users).
--daemon              : use daemon configuration. 
--help                : show this message.
--version             : show version number.
"),

           'drakboot' => N_("[--boot]
OPTIONS:
  --boot            - enable to configure boot loader
default mode: offer to configure autologin feature"),
           'drakbug' => N_("[OPTIONS] [PROGRAM_NAME]

OPTIONS:
  --help            - print this help message.
  --report          - program should be one of %s tools
  --incident        - program should be one of %s tools"),
           'drakconnect' => N_("[--add]
  --add             - \"add a network interface\" wizard
  --del             - \"delete a network interface\" wizard
  --skip-wizard     - manage connections
  --internet        - configure internet
  --wizard          - like --add"),
           'drakfont' => N_("
Font Importation and monitoring application

OPTIONS:
--windows_import : import from all available windows partitions.
--xls_fonts      : show all fonts that already exist from xls
--install        : accept any font file and any directory.
--uninstall      : uninstall any font or any directory of font.
--replace        : replace all font if already exist
--application    : 0 none application.
                 : 1 all application available supported.
                 : name_of_application like  so for staroffice 
                 : and gs for ghostscript for only this one."),
           'draksec' => "[--debug]
--debug: print debugging information",
           'drakTermServ' => N_("[OPTIONS]...
%s Terminal Server Configurator
--enable         : enable MTS
--disable        : disable MTS
--start          : start MTS
--stop           : stop MTS
--adduser        : add an existing system user to MTS (requires username)
--deluser        : delete an existing system user from MTS (requires username)
--addclient      : add a client machine to MTS (requires MAC address, IP, nbi image name)
--delclient      : delete a client machine from MTS (requires MAC address, IP, nbi image name)"),
	      'drakxtv' => "[--no-guess]",
	      'drakupdate_fstab' => " [--add | --del] <device>\n",
	      'keyboardrake' => N_("[keyboard]"),
           'logdrake' => N_("[--file=myfile] [--word=myword] [--explain=regexp] [--alert]"),
           'net_monitor' => N_("[OPTIONS]
Network & Internet connection and monitoring application

--defaultintf interface : show this interface by default
--connect : connect to internet if not already connected
--disconnect : disconnect to internet if already connected
--force : used with (dis)connect : force (dis)connection.
--status : returns 1 if connected 0 otherwise, then exit.
--quiet : do not be interactive. To be used with (dis)connect."),
	      'printerdrake' => " [--skiptest] [--cups] [--lprng] [--lpd] [--pdq]",
	      'rpmdrake' => N_("[OPTION]...
  --no-confirmation      do not ask first confirmation question in %s Update mode
  --no-verify-rpm        do not verify packages signatures
  --changelog-first      display changelog before filelist in the description window
  --merge-all-rpmnew     propose to merge all .rpmnew/.rpmsave files found"),
           'scannerdrake' => N_("[--manual] [--device=dev] [--update-sane=sane_source_dir] [--update-usbtable] [--dynamic=dev]"),
	      'XFdrake' => N_(" [everything]
       XFdrake [--noauto] monitor
       XFdrake resolution"),
	      );

$usages{$_} = $usages{rpmdrake} foreach qw(rpmdrake-remove MageiaUpdate);
$usages{Xdrakres} = $usages{XFdrake};


sub exit {
    explanations('### Program is exiting ###');
    CORE::exit(@_);
}

sub __exit {
    explanations('### Program is exiting ###');
    c::_exit(@_);
}


sub real_version() {
    return "VER"; # version automatically set from Makefile
}

sub version() {
    print 'Drakxtools version ' . real_version() . '
Copyright (C) 1999-2008 Mandriva by <install@mandriva.com>
',  $::license, "\n";
}

if (!$::no_global_argv_parsing) {
my ($i, @new_ARGV);
foreach (@ARGV) {
    $i++;
    if (/^-(-help|h)$/) {
	version();
	print N("\nUsage: %s  [--auto] [--beginner] [--expert] [-h|--help] [--noauto] [--testing] [-v|--version] ", $progname),
       if_($usages{$progname}, common::translate($usages{$progname})), "\n";
#    print N("\nUsage: "), $::usage, "\n" if $::usage;
	CORE::exit(0);
    } elsif (/^-(-version|v)$/) {
	version();
	CORE::exit(0);
    } elsif (/^--embedded$/) {
	$::XID = splice @ARGV, $i, 1;
	$::isEmbedded = 1;
    } elsif (/^--expert$/) {
	$::expert = 1;
    } elsif (/^--noauto$/) {
	$::noauto = /-noauto/;
    } elsif (/^--auto$/) {
	$::auto = 1;
    } elsif (/^--testing$/) {
	$::testing = 1;
    } elsif (/^--beginner$/) {
	$::expert = 0;
    } else {
	push @new_ARGV, $_;
    }
}

@ARGV = @new_ARGV;
}

################################################################################

#- stuff will go to special /var/log/explanations file
my $standalone_name;
sub explanations { log::explanations("@_") }

our @common_functs = qw(renamef linkf symlinkf output substInFile mkdir_p rm_rf cp_af touch setVarsInSh setExportedVarsInSh setExportedVarsInCsh update_gnomekderc);
our @builtin_functs = qw(chmod chown __exit exit unlink link symlink rename system);
our @drakx_modules = qw(Xconfig::card Xconfig::default Xconfig::main Xconfig::monitor Xconfig::parse Xconfig::proprietary Xconfig::resolution_and_depth Xconfig::screen Xconfig::test Xconfig::various Xconfig::xfree any bootloader bootlook c commands crypto detect_devices devices diskdrake diskdrake::hd_gtk diskdrake::interactive diskdrake::removable diskdrake::removable_gtk diskdrake::smbnfs_gtk fs fsedit http keyboard lang log loopback lvm modules::parameters modules mouse my_gtk network network::adsl network::ethernet network::connection network::isdn_consts network::isdn network::modem network::netconnect network::network fs::remote::nfs fs::remote::smb network::tools partition_table partition_table_bsd partition_table::dos partition_table::empty partition_table::gpt partition_table::mac partition_table::raw partition_table::sun printer printerdrake proxy raid run_program scanner services steps swap timezone network::drakfirewall network::shorewall);

sub bug_handler {
    my ($error, $is_signal) = @_;

    # exceptions in eval are OK:
    return if $error && $^S ne '0' && !$is_signal;

    # exceptions with "\n" are normal ways to quit:
    if (!$is_signal && eval { $error eq MDK::Common::String::formatError($error) }) {
        warn $error;
        exit(255);
    }

    # we want the full backtrace:
    if ($is_signal) {
        my $ctrace = c::C_backtrace();
        $ctrace =~ s/0:.*(\d+:[^:]*Perl_sighandler)/$1/sig;
        $error .= "\nGlibc's trace:\n$ctrace\n";
    }
    $error .= "Perl's trace:\n" . common::backtrace() if $error;

    my $progname = $0;

    # do not loop if drakbug crashes and do not complain about wizcancel:
    if ($progname =~ /drakbug/ || $error =~ /wizcancel/ || !-x '/usr/bin/drakbug') {
    	warn $error;
    	exit(1);
    }
    $progname =~ s|.*/||;
    exec('drakbug',  if_($error, '--error', $error), '--incident', $progname);
    c::_exit(1);
}

if (!$ENV{DISABLE_DRAKBUG}) {
    $SIG{SEGV} = sub { bug_handler(@_, 1) };
    $SIG{__DIE__} = \&bug_handler;
}

sub import() {
    ($standalone_name = $0) =~ s|.*/||;
    c::openlog($standalone_name . "[$$]");
    explanations('### Program is starting ###');

    eval "*common::$_ = *$_" foreach @common_functs;

    foreach my $f (@builtin_functs) {
	eval "*$_" . "::$f = *$f" foreach @drakx_modules;
	eval "*" . caller() . "::$f = *$f";
    }
}


sub renamef {
    explanations "moved file $_[0] to $_[1]";
    goto &MDK::Common::File::renamef;
}

sub linkf {
    explanations "hard linked file $_[0] to $_[1]";
    goto &MDK::Common::File::linkf;
}

sub symlinkf {
    explanations "symlinked file $_[0] to $_[1]";
    goto &MDK::Common::File::symlinkf;
}

sub output {
    explanations "created file $_[0]";
    goto &MDK::Common::File::output;
}

sub substInFile(&@) {
    explanations "modified file $_[1]";
    goto &MDK::Common::File::substInFile;
}

sub mkdir_p {
    explanations "created directory $_[0] (and parents if necessary)";
    goto &MDK::Common::File::mkdir_p;
}

sub rm_rf {
    explanations "removed files/directories (recursively) @_";
    goto &MDK::Common::File::rm_rf;
}

sub cp_af {
    my $retval = MDK::Common::File::cp_af(@_);
    my $dest = pop @_;
    explanations "copied recursively @_ to $dest";
    return $retval;
}

sub touch {
    explanations "touched file @_";
    goto &MDK::Common::File::touch;
}

sub setVarsInSh {
    explanations "modified file $_[0]";
    goto &MDK::Common::System::setVarsInSh;
}

sub setExportedVarsInSh {
    explanations "modified file $_[0]";
    goto &MDK::Common::System::setExportedVarsInSh;
}

sub setExportedVarsInCsh {
    explanations "modified file $_[0]";
    goto &MDK::Common::System::setExportedVarsInCsh;
}

sub update_gnomekderc {
    explanations "modified file $_[0]";
    goto &MDK::Common::System::update_gnomekderc;
}


sub chmod {
    my $retval = CORE::chmod(@_);
    my $mode = shift @_;
    explanations sprintf("changed mode of %s to %o", $_, $mode) foreach @_;
    return $retval;
}

sub chown {
    my $retval = CORE::chown(@_);
    my $uid = shift @_;
    my $gid = shift @_;
    explanations sprintf("changed owner of $_ to $uid.$gid") foreach @_;
    return $retval;
}

sub unlink {
    explanations "removed files/directories @_";
    CORE::unlink(@_);
}

sub link {
    explanations "hard linked file $_[0] to $_[1]";
    CORE::link($_[0], $_[1]);
}

sub symlink {
    explanations "symlinked file $_[0] to $_[1]";
    CORE::symlink($_[0], $_[1]);
}

sub rename {
    explanations "renamed file $_[0] to $_[1]" if -r $_[0];
    CORE::rename($_[0], $_[1]);
}

sub system {
    explanations "launched command: @_";
    CORE::system(@_);
}

1;
l str">@icon_paths $wm_icon $grab $border); #- leave it on one line, for automatic removal of the line at package creation @ISA = qw(Exporter); %EXPORT_TAGS = ( wrappers => [ qw(gtkadd gtkadd_widget 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 gtkcolor gtkcreate_img gtkcreate_pixbuf gtkfontinfo gtkset_background n_line_size set_back_pixbuf set_back_pixmap 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 gtkcreate_frame) ], 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 mygtk2 qw(gtknew); #- do not import gtkadd which conflicts with ugtk2 version use Gtk2; use Gtk2::Gdk::Keysyms; $border = 5; sub wm_icon() { $wm_icon || $::Wizard_pix_up || "wiz_default_up.png" } # -=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=--- # 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 { mygtk2::may_destroy($_[0]) } sub gtkflush() { mygtk2::flush() } 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 = gtknew('WrappedLabel', text => $l); $w->add(gtkshow($l)); } $w; } sub gtkadd_widget { my $sg = shift; map { my $l = $_; ref $l or $l = gtknew('WrappedLabel', text => $l); $sg->add_widget($l); $l; } @_; } sub gtkappend { my $w = shift; foreach my $l (@_) { ref $l or $l = gtknew('WrappedLabel', text => $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 ($notebook, $page, $o_title) = @_; $notebook->append_page($page, $o_title); $notebook; } sub gtkentry { my ($text) = @_; my $e = gtknew('Entry'); $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() { mygtk2::root_window() } sub gtkcolor { &mygtk2::rgb2color } sub gtkset_background { &mygtk2::set_root_window_background } 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)); $w; } 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 : gtknew('WrappedLabel', text => 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(gtknew('Button'), gtknew('HBox', spacing => 3, children => [ 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::Html2::View 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->set_left_margin(6) if ref($W) =~ /Gtk2::TextView/; $W->show; if (ref($W) =~ /Gtk2::TextView|Gtk2::TreeView/) { gtknew('Frame', shadow_type => 'in', child => $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, @l) = @_; my $nbline = sum(map { round(length($_) / 60 + 1/2) } map { split "\n" } @l); my $box = gtknew('VBox'); if ($nbline == 0) { $o->{box_size} = 0; return $box; } $o->{box_size} = n_line_size($nbline, 'text', $box); if (@l <= 2 && $nbline > 4) { $o->{icon} && !$::isWizard and eval { gtkpack__($box, gtknew('HBox', border_width => 5, children_loose => [ gtkcreate_img($o->{icon}) ])) }; my $wanted = $o->{box_size}; $o->{box_size} = min(200, $o->{box_size}); my $has_scroll = $o->{box_size} < $wanted; chomp(my $text = join("\n", @l)); my $wtext = gtknew('TextView', text => $text); $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!) my $width = 400; my $scroll = gtknew('ScrolledWindow', child => $wtext, width => $width, height => 200); $scroll->signal_connect(realize => sub { my $layout = $wtext->create_pango_layout($text); $layout->set_width(($width - 10) * Gtk2::Pango->scale); $wtext->set_size_request($width, min(200, ($layout->get_pixel_size)[1] + 10)); $scroll->set_size_request($width, min(200, ($layout->get_pixel_size)[1] + 10)); $o->{rwindow}->queue_resize; }); gtkpack_($box, $o->{box_allow_grow} || 0, $scroll); } else { my $a = !$::no_separator; undef $::no_separator; my $new_label = sub { my ($txt) = @_; ref($txt) ? $txt : gtknew('WrappedLabel', text => $txt); }; if ($o->{icon} && (!$::isWizard || $::isInstall)) { gtkpack__($box, gtknew('HBox', children => [ 0, gtknew('VBox', width => 15), 0, eval { gtkcreate_img($o->{icon}) }, 0, gtknew('VBox', width => 15), 1, $o->{box_title} = gtknew('VBox', children_loose => [ gtknew('HBox', children => [ (map { my $w = $new_label->($_); $::isWizard and $w->set_justify("left"); (0, $w); } @l), 1, gtknew('HBox'), ]) ]) ]), if_($a, gtknew('HSeparator')) ); } else { gtkpack__($box, if_($::isWizard, gtknew('Label', height => 10)), (map { my $w = $new_label->($_); $::isWizard ? gtknew('HBox', children_tight => [ gtknew('Label', width => 20), $w ]) : $w; } @l), if_($::isWizard, gtknew('Label', height => 15)), if_($a, gtknew('HSeparator')), ); } } } sub _create_dialog { my ($title, $o_options) = @_; my $options = $o_options || {}; #- keep compatibility with "transient" now called "transient_for" $options->{transient_for} = delete $options->{transient} if $options->{transient}; gtknew('Dialog', title => $title, position_policy => 'center-on-parent', # center-on-parent does not work modal => 1, if_(!$::isInstall, icon_no_error => wm_icon()), %$options, allow_unknown_options => 1, ); } # drakfloppy / drakfont / harddrake2 / mcc sub create_dialog { my ($title, $label, $o_options) = @_; my $ret = 0; my $dialog = gtkset_border_width(_create_dialog($title, $o_options), 10); $dialog->set_border_width(10); my $text = ref($label) ? $label : $o_options->{use_markup} ? gtknew('WrappedLabel', text_markup => $label) : gtknew('WrappedLabel', text => $label); gtkpack($dialog->vbox, gtknew('HBox', children => [ if_($o_options->{stock}, 0, Gtk2::Image->new_from_stock($o_options->{stock}, 'dialog'), 0, gtknew('Label', text => " "), ), 1, $o_options->{scroll} ? create_scrolled_window($text, [ 'never', 'automatic' ]) : $text, ]), ); if ($o_options->{cancel}) { $dialog->action_area->pack_start( gtknew('Button', text => N("Cancel"), clicked => sub { $ret = 0; $dialog->destroy; Gtk2->main_quit }, can_default => 1), 1, 1, 0); } my $button = gtknew('Button', text => N("Ok"), can_default => 1, clicked => sub { $ret = 1; $dialog->destroy; Gtk2->main_quit }); $dialog->action_area->pack_start($button, 1, 1, 0); $button->grab_default; $dialog->set_has_separator(0); $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 { gtknew('HButtonBox', layout => $_[0]) } sub create_vbox { gtknew('VButtonBox', layout => $_[0]) } 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 $book = gtknew('Notebook'); while (@_) { my ($page, $title) = splice(@_, 0, 2); gtkappend_page($book, $page, $title); } $book; } sub create_packtable { my ($options, @l) = @_; my $w = Gtk2::Table->new(0, 0, $options->{homogeneous} || 0); add2hash_($options, { xpadding => 5, ypadding => 0 }); each_index { my ($i, $l) = ($::i, $_); each_index { my $j = $::i; if ($_) { ref $_ or $_ = gtknew('WrappedLabel', text => $_); $j != $#$l && !$options->{mcc} ? $w->attach($_, $j, $j + 1, $i, $i + 1, 'fill', 'fill', $options->{xpadding}, $options->{ypadding}) : $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); gtkset_border_width($w, $::isInstall ? 3 : 10); } sub create_okcancel { my ($w, $o_ok, $o_cancel, $_o_spread, @other) = @_; # @other is a list of extra buttons (usually help (eg: XFdrake/drakx caller) or advanced (eg: interactive caller) button) # extra buttons have the following structure [ label, handler, is_first, pack_right ] local $::isWizard = $::isWizard && !$w->{pop_it}; my $cancel; if (defined $o_cancel || defined $o_ok) { $cancel = $o_cancel; } elsif (!$::Wizard_no_previous) { $cancel = $::isWizard ? N("Previous") : N("Cancel"); } my $ok = defined $o_ok ? $o_ok : $::isWizard ? ($::Wizard_finished ? N("Finish") : N("Next")) : N("Ok"); my $bok = $ok && ($w->{ok} = gtknew('Button', text => $ok, clicked => $w->{ok_clicked} || sub { $w->{retval} = 1; Gtk2->main_quit })); my $bprev; if ($cancel) { $bprev = $w->{cancel} = gtknew('Button', text => $cancel, clicked => $w->{cancel_clicked} || sub { log::l("default cancel_clicked"); undef $w->{retval}; Gtk2->main_quit }); } $w->{wizcancel} = gtknew('Button', text => N("Cancel"), clicked => sub { die 'wizcancel' }) if $::isWizard && !$::isInstall; my $f = sub { $w->{buttons}{$_[0][0]} = gtknew('Button', text => $_[0][0], clicked => $_[0][1]) }; my @left = ((map { $f->($_) } grep { $_->[2] && !$_->[3] } @other), map { $f->($_) } grep { !$_->[2] && !$_->[3] } @other); my @right = ((map { $f->($_) } grep { $_->[2] && $_->[3] } @other), map { $f->($_) } grep { !$_->[2] && $_->[3] } @other); # we put space to group buttons in two packs (but if there's only one when not in wizard mode) # but in the installer where all windows run in wizard mode because of design even when not in a wizard step $bprev = gtknew('Label') if !$cancel && $::Wizard_no_previous && !@left && !@right; if ($::isWizard) { # wizard mode: order is cancel/left_extras/white/right_extras/prev/next unshift @left, $w->{wizcancel} if !$::isInstall; push @right, $bprev, $bok; } else { # normal mode: cancel/ok button follow GNOME's HIG unshift @left, $bprev; push @left, gtknew('Label') if $ok && $cancel; # space buttons but if there's only one button push @right, $bok; } gtknew('VBox', spacing => 5, children_loose => [ gtknew('HBox', height => 5), gtknew('HSeparator'), gtknew('HBox', children_loose => [ map { gtknew('HButtonBox', layout => $_->[1], children_loose => [ map { $_->can_default($::isWizard); $_; } grep { $_ } @{$_->[0]} ]); } ([ \@left, 'start' ], [ \@right, 'end' ], ) ]), ]); } 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, @_); } sub gtkcreate_frame { my ($label) = @_; gtknew('Frame', text => $label, border_width => 5); } # -=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=---=-=--- # helpers # # Functions that do typical operations on widgets, that you may need in # several places of your programs. sub _find_imgfile { my ($name) = @_; if ($name =~ m|/| && -f $name) { $name; } else { foreach my $path (icon_paths()) { foreach ('', '.png', '.xpm') { my $file = "$path/$name$_"; -f $file and return $file; } } } } # use it if you want to display an icon/image in your app sub gtkcreate_img { gtknew('Image', file => $_[0]); } # use it if you want to draw an image onto a drawingarea sub gtkcreate_pixbuf { gtknew('Pixbuf', file => $_[0]); } sub gtktext_append { gtktext_insert(@_, append => 1) } sub may_set_icon { my ($w, $name) = @_; if (my $f = $name && _find_imgfile($name)) { $w->set_icon(gtkcreate_pixbuf($f)); } } sub gtktext_insert { &mygtk2::_text_insert } sub icon_paths { &mygtk2::_icon_paths } sub add_icon_path { &mygtk2::add_icon_path } sub set_main_window_size { my ($o) = @_; mygtk2::set_main_window_size($o->{rwindow}); } # 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 set_back_pixmap { my ($w) = @_; return if !$w->realized; my $window = $w->window; my $pixmap = $w->{back_pixmap} ||= Gtk2::Gdk::Pixmap->new($window, 1, 2, $window->get_depth); my $style = $w->get_style; $pixmap->draw_points($style->bg_gc('normal'), 0, 0); $pixmap->draw_points($style->base_gc('normal'), 0, 1); $window->set_back_pixmap($pixmap); } 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(gtknew('Label', text => $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, $currentx, $currenty) = @_; my $wrap_char = ' '; my @lines; my $current_text; my @t = split($wrap_char, $text); my @t2; if ($::isInstall && $::o->{locale}{lang} =~ /ja|zh/) { use locale; @t = map { $_ . $wrap_char } @t; $wrap_char = ''; foreach (@t) { my @c = split(/\b/); 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; } my $add_line = sub { my ($w, $h) = string_size($widget4style, $current_text); push @lines, { text => $current_text, width => $w, height => $h + 1, 'x' => $currentx, 'y' => $currenty }; }; my $width; foreach my $word (@t2) { my $w = string_width($widget4style, $word . $wrap_char); if ($currentx + $width + $w > $max_width) { $add_line->(); $current_text = $word; $width = $w; $currentx = 0; $currenty += $lines[-1]{height}; } else { $current_text .= ($current_text ne '' ? $wrap_char : '') . $word; $width += $w; } } #- if wrap_char was at the end, do not forget it, for cases when bold/nonbold text follows $text =~ /$wrap_char$/ and $current_text .= $wrap_char; $add_line->(); return @lines; } sub wrap_paragraph { my ($text, $widget4style, $border, $max_width) = @_; $max_width -= 2*$border; my @lines; my $ydec; foreach my $paragraph (@$text) { my @paragraph_lines; my $center; if (ref($paragraph) eq 'ARRAY') { my ($text, %options) = @$paragraph; $center = $options{center}; $paragraph = $text; } if ($paragraph ne '') { my @elements; while ($paragraph =~ m|(.*?)<b>(.*?)</b>(.*)|) { $1 ne '' and push @elements, [ $1, bold => 0 ]; push @elements, [ $2, bold => 1 ]; $paragraph = $3; } $paragraph ne '' and push @elements, [ $paragraph, bold => 0 ]; my $currentx; foreach (@elements) { my ($text, %options) = @$_; #- hack :( if ' ' is at the beginning, do not forget it, substitute #- with an unbreakable space because gtk allocates too much space otherwise if ($text =~ /^ (.*)/) { use utf8; $text = ' ' . $1; } my @newlines = get_text_coord($text, $widget4style, $max_width, $currentx, $ydec); $currentx = $newlines[-1]{'x'} + $newlines[-1]{width}; $ydec = $newlines[-1]{'y'}; $options{bold} and $currentx++; $_->{options} = \%options foreach @newlines; push @paragraph_lines, @newlines; }