package partition_table; # $Id$ use diagnostics; use strict; use vars qw(@ISA %EXPORT_TAGS @EXPORT_OK @important_types @important_types2 @fields2save @bad_types); @ISA = qw(Exporter); %EXPORT_TAGS = ( types => [ qw(type2name type2fs name2type fs2type isExtended isExt2 isThisFs isTrueFS isSwap isDos isWin isFat isSunOS isOtherAvailableFS isPrimary isRawLVM isRawRAID isRAID isLVM isNT isMountableRW isNonMountable isPartOfLVM isPartOfRAID isPartOfLoopback isLoopback isMounted isBusy isSpecial maybeFormatted isApple isAppleBootstrap) ], ); @EXPORT_OK = map { @$_ } values %EXPORT_TAGS; use common; use partition_table::raw; use detect_devices; use log; @important_types = ('Linux native', 'Linux swap', if_(arch() =~ /i.86/, 'Journalised FS: ext3', 'Journalised FS: ReiserFS', 'Journalised FS: JFS', 'Journalised FS: XFS', 'DOS FAT16', 'FAT32'), if_(arch() =~ /ia64/, 'Journalised FS: ext3', 'Journalised FS: ReiserFS', 'Journalised FS: XFS', 'FAT32'), if_(arch() =~ /ppc/, 'Journalised FS: ext3', 'Journalised FS: ReiserFS', 'Journalised FS: JFS', 'Journalised FS: XFS', 'Apple HFS Partition', 'Apple Bootstrap')); @important_types2 = ('Linux RAID', 'Linux Logical Volume Manager partition'); @fields2save = qw(primary extended totalsectors isDirty needKernelReread); @bad_types = ('Empty', 'DOS 3.3+ Extended Partition', 'Win95: Extended partition, LBA-mapped', 'Linux extended partition'); my %types = ( 0x0 => 'Empty', if_(arch() =~ /^ppc/, 0x183 => 'Journalised FS: ReiserFS', 0x283 => 'Journalised FS: XFS', 0x383 => 'Journalised FS: JFS', 0x483 => 'Journalised FS: ext3', 0x401 => 'Apple Partition', 0x401 => 'Apple Bootstrap', 0x402 => 'Apple HFS Partition', ), if_(arch() =~ /^i.86/, 0x183 => 'Journalised FS: ReiserFS', 0x283 => 'Journalised FS: XFS', 0x383 => 'Journalised FS: JFS', 0x483 => 'Journalised FS: ext3', ), if_(arch() =~ /^ia64/, 0x100 => 'Various', 0x183 => 'Journalised FS: ReiserFS', 0x283 => 'Journalised FS: XFS', 0x483 => 'Journalised FS: ext3', ), if_(arch() =~ /^sparc/, 0x1 => 'SunOS boot', 0x2 => 'SunOS root', 0x3 => 'SunOS swap', 0x4 => 'SunOS usr', 0x5 => 'Whole disk', 0x6 => 'SunOS stand', 0x7 => 'SunOS var', 0x8 => 'SunOS home', ), if_(arch() =~ /^i.86/, 0x1 => 'DOS 12-bit FAT', 0x2 => 'XENIX root', 0x3 => 'XENIX /usr', 0x4 => 'DOS 16-bit FAT (up to 32M)', 0x5 => 'DOS 3.3+ Extended Partition', 0x6 => 'DOS FAT16', 0x7 => 'NTFS (or HPFS)', 0x8 => 'OS/2 (v1.0-1.3 only) / AIX boot partition / SplitDrive / Commodore DOS / DELL partition spanning multiple drives / QNX 1.x and 2.x ("qny")', ), 0x9 => 'AIX data partition / Coherent filesystem / QNX 1.x and 2.x ("qnz")', 0xa => 'OS/2 Boot Manager / Coherent swap partition / OPUS', 0xb => 'FAT32', 0xc => 'Win98 FAT32, LBA-mapped', 0xe => 'Win95: DOS 16-bit FAT, LBA-mapped', 0xf => 'Win95: Extended partition, LBA-mapped', 0x10 => 'OPUS (?)', 0x11 => 'Hidden DOS 12-bit FAT', 0x12 => 'Compaq/HP config partition', 0x14 => 'Hidden DOS 16-bit FAT <32M', 0x16 => 'Hidden DOS 16-bit FAT >=32M', 0x17 => 'Hidden IFS (e.g., HPFS)', 0x18 => 'AST Windows swapfile', 0x1b => 'Hidden WIN95 OSR2 32-bit FAT', 0x1c => 'Hidden WIN95 OSR2 32-bit FAT, LBA-mapped', 0x1e => 'Hidden FAT95', 0x22 => 'Used for Oxygen Extended Partition Table by ekstazya@sprint.ca.', 0x24 => 'NEC DOS 3.x', 0x35 => 'JFS (OS/2)', 0x38 => 'THEOS ver 3.2 2gb partition', 0x39 => 'THEOS ver 4 spanned partition', 0x3a => 'THEOS ver 4 4gb partition', 0x3b => 'THEOS ver 4 extended partition', 0x3c => 'PartitionMagic recovery partition', 0x40 => 'Venix 80286', 0x41 => 'Linux/MINIX (sharing disk with DRDOS) / Personal RISC Boot / PPC PReP (Power PC Reference Platform) Boot', 0x42 => 'Windows Dynamic Partition', 0x43 => 'Linux native (sharing disk with DRDOS)', 0x45 => 'EUMEL/Elan', 0x46 => 'EUMEL/Elan 0x46', 0x47 => 'EUMEL/Elan 0x47', 0x48 => 'EUMEL/Elan 0x48', 0x4d => 'QNX4.x', 0x4e => 'QNX4.x 2nd part', 0x4f => 'QNX4.x 3rd part / Oberon partition', 0x50 => 'OnTrack Disk Manager (older versions) RO', 0x51 => 'OnTrack Disk Manager RW (DM6 Aux1) / Novell', 0x52 => 'CP/M / Microport SysV/AT', 0x53 => 'Disk Manager 6.0 Aux3', 0x54 => 'Disk Manager 6.0 Dynamic Drive Overlay', 0x55 => 'EZ-Drive', 0x56 => 'Golden Bow VFeature Partitioned Volume. / DM converted to EZ-BIOS', 0x57 => 'DrivePro', 0x5c => 'Priam EDisk', 0x61 => 'SpeedStor', 0x63 => 'Unix System V (SCO, ISC Unix, UnixWare, ...), Mach, GNU Hurd', 0x64 => 'PC-ARMOUR protected partition / Novell Netware 2.xx', 0x65 => 'Novell Netware 3.xx or 4.xx', 0x67 => 'Novell', 0x68 => 'Novell 0x68', 0x69 => 'Novell 0x69', 0x70 => 'DiskSecure Multi-Boot', 0x75 => 'IBM PC/IX', 0x80 => 'MINIX until 1.4a', 0x81 => 'MINIX since 1.4b, early Linux / Mitac disk manager', 0x82 => 'Linux swap', 0x83 => 'Linux native', 0x84 => 'OS/2 hidden C: drive / Hibernation partition', 0x85 => 'Linux extended partition', 0x86 => 'Old Linux RAID partition superblock / NTFS volume set', 0x87 => 'NTFS volume set', 0x8a => 'Linux Kernel Partition (used by AiR-BOOT)', 0x8e => 'Linux Logical Volume Manager partition', 0x93 => 'Amoeba', 0x94 => 'Amoeba bad block table', 0x99 => 'DCE376 logical drive', 0xa0 => 'IBM Thinkpad hibernation partition / Phoenix NoteBIOS Power Management "Save-to-Disk" partition', 0xa5 => 'BSD/386, 386BSD, NetBSD, FreeBSD', 0xa6 => 'OpenBSD', 0xa7 => 'NEXTSTEP', 0xa9 => 'NetBSD', 0xaa => 'Olivetti Fat 12 1.44Mb Service Partition', 0xb7 => 'BSDI filesystem', 0xb8 => 'BSDI swap partition', 0xbe => 'Solaris boot partition', 0xc0 => 'CTOS / REAL/32 secure small partition', 0xc1 => 'DRDOS/secured (FAT-12)', 0xc4 => 'DRDOS/secured (FAT-16, < 32M)', 0xc6 => 'DRDOS/secured (FAT-16, >= 32M) / Windows NT corrupted FAT16 volume/stripe set', 0xc7 => 'Windows NT corrupted NTFS volume/stripe set / Syrinx boot', 0xcb => 'reserved for DRDOS/secured (FAT32)', 0xcc => 'reserved for DRDOS/secured (FAT32, LBA)', 0xcd => 'CTOS Memdump?', 0xce => 'reserved for DRDOS/secured (FAT16, LBA)', 0xd0 => 'REAL/32 secure big partition', 0xd1 => 'Old Multiuser DOS secured FAT12', 0xd4 => 'Old Multiuser DOS secured FAT16 <32M', 0xd5 => 'Old Multiuser DOS secured extended partition', 0xd6 => 'Old Multiuser DOS secured FAT16 >=32M', 0xd8 => 'CP/M-86', 0xdb => 'Digital Research CP/M, Concurrent CP/M, Concurrent DOS / CTOS (Convergent Technologies OS -Unisys) / KDG Telemetry SCPU boot', 0xdd => 'Hidden CTOS Memdump?', 0xe1 => 'DOS access or SpeedStor 12-bit FAT extended partition', 0xe3 => 'DOS R/O or SpeedStor', 0xe4 => 'SpeedStor 16-bit FAT extended partition < 1024 cyl.', 0xeb => 'BeOS', 0xee => 'EFI GPT', 0xef => 'EFI (FAT-12/16/32)', 0xf1 => 'SpeedStor 0xf1', 0xf2 => 'DOS 3.3+ secondary partition', 0xf4 => 'SpeedStor large partition / Prologue single-volume partition', 0xf5 => 'Prologue multi-volume partition', 0xfd => 'Linux RAID', 0xfe => 'SpeedStor > 1024 cyl. or LANstep / IBM PS/2 IML (Initial Microcode Load) partition, located at the end of the disk. / Windows NT Disk Administrator hidden partition / Linux Logical Volume Manager partition (old)', 0xff => 'Xenix Bad Block Table', ); my %type2fs = ( arch() =~ /^ppc/ ? ( 0x07 => 'hpfs', ) : ( 0x07 => 'ntfs', ), arch() !~ /sparc/ ? ( 0x01 => 'vfat', 0x04 => 'vfat', 0x05 => 'ignore', 0x06 => 'vfat', ) : ( 0x01 => 'ufs', 0x02 => 'ufs', 0x04 => 'ufs', 0x06 => 'ufs', 0x07 => 'ufs', 0x08 => 'ufs', ), 0x0b => 'vfat', 0x0c => 'vfat', 0x0e => 'vfat', 0x1b => 'vfat', 0x1c => 'vfat', 0x1e => 'vfat', 0x82 => 'swap', 0x83 => 'ext2', 0x183 => 'reiserfs', 0x283 => 'xfs', 0x383 => 'jfs', 0x483 => 'ext3', 0x401 => 'apple', 0x402 => 'hfs', ); my %types_rev = reverse %types; my %fs2type = reverse %type2fs; 1; sub important_types { my @l = (@important_types, if_($::expert, @important_types2, sort values %types)); difference2(\@l, \@bad_types); } sub type2fs { $type2fs{$_[0]{type}} || $_[0]{type} } sub fs2type { $fs2type{$_[0]} || $_[0] } sub type2name { $types{$_[0]} || $_[0] } sub name2type { local ($_) = @_; /0x(.*)/ ? hex $1 : $types_rev{$_} || $_; } sub isWholedisk { arch() =~ /^sparc/ && $_[0]{type} == 5 } sub isExtended { arch() !~ /^sparc/ && ($_[0]{type} == 5 || $_[0]{type} == 0xf || $_[0]{type} == 0x85) } sub isRawLVM { $_[0]{type} == 0x8e } sub isRawRAID { $_[0]{type} == 0xfd } sub isSwap { type2fs($_[0]) eq 'swap' } sub isExt2 { type2fs($_[0]) eq 'ext2' } sub isDos { arch() !~ /^sparc/ && ${{ 1 => 1, 4 => 1, 6 => 1 }}{$_[0]{type}} } sub isWin { ${{ 0xb => 1, 0xc => 1, 0xe => 1, 0x1b => 1, 0x1c => 1, 0x1e => 1 }}{$_[0]{type}} } sub isFat { isDos($_[0]) || isWin($_[0]) } sub isSunOS { arch() =~ /sparc/ && ${{ 0x1 => 1, 0x2 => 1, 0x4 => 1, 0x6 => 1, 0x7 => 1, 0x8 => 1 }}{$_[0]{type}} } sub isNT { arch() !~ /^sparc/ && $_[0]{type} == 0x7 } sub isApple { type2fs($_[0]) eq 'apple' && defined $_[0]{isDriver} } sub isAppleBootstrap { type2fs($_[0]) eq 'apple' && defined $_[0]{isBoot} } sub isHiddenMacPart { defined $_[0]{isMap} } sub isThisFs { type2fs($_[1]) eq $_[0] } sub isTrueFS { member(type2fs($_[0]), qw(ext2 reiserfs xfs jfs ext3)) } sub isOtherAvailableFS { isFat($_[0]) || isSunOS($_[0]) || isThisFs('hfs', $_[0]) || isThisFs('ntfs', $_[0]) } #- other OS that linux can access its filesystem sub isMountableRW { (isTrueFS($_[0]) || isOtherAvailableFS($_[0])) && !isThisFs('ntfs', $_[0]) } sub isNonMountable { isRawRAID($_[0]) || isRawLVM($_[0]) } sub isPartOfLVM { defined $_[0]{lvm} } sub isPartOfRAID { defined $_[0]{raid} } sub isPartOfLoopback { defined $_[0]{loopback} } sub isRAID { $_[0]{device} =~ /^md/ } sub isUBD { $_[0]{device} =~ /^ubd/ } #- should be always true during an $::uml_install sub isLVM { $_[0]{VG_name} } sub isLoopback { defined $_[0]{loopback_file} } sub isMounted { $_[0]{isMounted} } sub isBusy { isMounted($_[0]) || isPartOfRAID($_[0]) || isPartOfLVM($_[0]) || isPartOfLoopback($_[0]) } sub isSpecial { isRAID($_[0]) || isLVM($_[0]) || isLoopback($_[0]) || isUBD($_[0]) } sub maybeFormatted { $_[0]{isFormatted} || !$_[0]{notFormatted} } #- works for both hard drives and partitions ;p sub description { my ($hd) = @_; my $win = $hd->{device_windobe}; sprintf "%s%s (%s%s%s%s)", $hd->{device}, $win && " [$win:]", formatXiB($hd->{totalsectors} || $hd->{size}, 512), $hd->{info} && ", $hd->{info}", $hd->{mntpoint} && ", " . $hd->{mntpoint}, $hd->{type} && ", " . type2name($hd->{type}); } sub isPrimary { my ($part, $hd) = @_; foreach (@{$hd->{primary}{raw}}) { $part eq $_ and return 1 } 0; } sub adjustStartAndEnd { my ($hd, $part) = @_; $hd->adjustStart($part); $hd->adjustEnd($part); } sub verifyNotOverlap { my ($a, $b) = @_; $a->{start} + $a->{size} <= $b->{start} || $b->{start} + $b->{size} <= $a->{start}; } sub verifyInside { my ($a, $b) = @_; $b->{start} <= $a->{start} && $a->{start} + $a->{size} <= $b->{start} + $b->{size}; } sub verifyParts_ { foreach my $i (@_) { foreach (@_) { next if !$i || !$_ || $i == $_ || isWholedisk($i) || isExtended($i); #- avoid testing twice for simplicity :-) if (isWholedisk($_)) { verifyInside($i, $_) or cdie sprintf("partition sector #$i->{start} (%s) is not inside whole disk (%s)!", formatXiB($i->{size}, 512), formatXiB($_->{size}, 512)); } elsif (isExtended($_)) { verifyNotOverlap($i, $_) or log::l(sprintf("warning partition sector #$i->{start} (%s) is overlapping with extended partition!", formatXiB($i->{size}, 512))); #- only warning for this one is acceptable } else { verifyNotOverlap($i, $_) or cdie sprintf("partitions sector #$i->{start} (%s) and sector #$_->{start} (%s) are overlapping!", formatXiB($i->{size}, 512), formatXiB($_->{size}, 512)); } } } } sub verifyParts { my ($hd) = @_; verifyParts_(get_normal_parts($hd)); } sub verifyPrimary { my ($pt) = @_; $_->{start} > 0 || arch() =~ /^sparc/ || die "partition must NOT start at sector 0" foreach @{$pt->{normal}}; verifyParts_(@{$pt->{normal}}, $pt->{extended}); } sub assign_device_numbers { my ($hd) = @_; my $i = 1; my $start = 1; #- on PPC we need to assign device numbers to the holes too - big FUN! #- not if it's an IBM machine using a DOS partition table though if (arch() =~ /ppc/ && detect_devices::get_mac_model() !~ /^IBM/) { #- first sort the normal parts $hd->{primary}{normal} = [ sort { $a->{start} <=> $b->{start} } @{$hd->{primary}{normal}} ]; #- now loop through them, assigning partition numbers - reserve one for the holes foreach (@{$hd->{primary}{normal}}) { if ($_->{start} > $start) { log::l("PPC: found a hole on $hd->{prefix} before $_->{start}, skipping device..."); $i++; } $_->{device} = $hd->{prefix} . $i; $_->{devfs_device} = $hd->{devfs_prefix} . '/part' . $i; $start = $_->{start} + $_->{size}; $i++; } } else { foreach (@{$hd->{primary}{raw}}) { $_->{device} = $hd->{prefix} . $i; $_->{devfs_device} = $hd->{devfs_prefix} . '/part' . $i; $i++; } foreach (map { $_->{normal} } @{$hd->{extended} || []}) { my $dev = $hd->{prefix} . $i; push @{$hd->{partitionsRenumbered}}, [ $_->{device}, $dev ] if $_->{device} && $dev ne $_->{device}; $_->{device} = $dev; $_->{devfs_device} = $hd->{devfs_prefix} . '/part' . $i; $i++; } } #- try to figure what the windobe drive letter could be! # #- first verify there's at least one primary dos partition, otherwise it #- means it is a secondary disk and all will be false :( my ($c, @others) = grep { isFat($_) } @{$hd->{primary}{normal}}; $i = ord 'C'; $c->{device_windobe} = chr($i++) if $c; $_->{device_windobe} = chr($i++) foreach grep { isFat($_) } map { $_->{normal} } @{$hd->{extended}}; $_->{device_windobe} = chr($i++) foreach @others; } sub remove_empty_extended { my ($hd) = @_; my $last = $hd->{primary}{extended} or return; @{$hd->{extended}} = grep { if ($_->{normal}) { $last = $_; } else { %{$last->{extended}} = $_->{extended} ? %{$_->{extended}} : (); } $_->{normal}; } @{$hd->{extended}}; adjust_main_extended($hd); } sub adjust_main_extended { my ($hd) = @_; if (!is_empty_array_ref $hd->{extended}) { my ($l, @l) = @{$hd->{extended}}; # the first is a special case, must recompute its real size my $start = round_down($l->{normal}{start} - 1, $hd->{geom}{sectors}); my $end = $l->{normal}{start} + $l->{normal}{size}; my $only_linux = 1; my $has_win_lba = 0; foreach (map { $_->{normal} } $l, @l) { $start = min($start, $_->{start}); $end = max($end, $_->{start} + $_->{size}); $only_linux &&= isTrueFS($_) || isSwap($_); $has_win_lba ||= $_->{type} == 0xc || $_->{type} == 0xe; } $l->{start} = $hd->{primary}{extended}{start} = $start; $l->{size} = $hd->{primary}{extended}{size} = $end - $start; } if (!@{$hd->{extended} || []} && $hd->{primary}{extended}) { %{$hd->{primary}{extended}} = (); #- modify the raw entry delete $hd->{primary}{extended}; } verifyParts($hd); #- verify everything is all right } sub adjust_local_extended { my ($hd, $part) = @_; foreach (@{$hd->{extended} || []}) { $_->{normal} == $part or next; $_->{size} = $part->{size} + $part->{start} - $_->{start}; last; } } sub get_normal_parts { my ($hd) = @_; @{$hd->{primary}{normal} || []}, map { $_->{normal} } @{$hd->{extended} || []} } sub get_normal_parts_and_holes { my ($hd) = @_; my ($start, $last) = ($hd->first_usable_sector, $hd->last_usable_sector); ref($hd) or print("get_normal_parts_and_holes: bad hd" . backtrace(), "\n"); my @l = map { my $current = $start; $start = $_->{start} + $_->{size}; my $hole = { start => $current, size => $_->{start} - $current, type => 0, rootDevice => $hd->{device} }; $hole, $_; } sort { $a->{start} <=> $b->{start} } grep { !isWholedisk($_) } get_normal_parts($hd); push @l, { start => $start, size => $last - $start, type => 0, rootDevice => $hd->{device} }; grep { $_->{type} || $_->{size} >= $hd->cylinder_size } @l; } sub read_one($$) { my ($hd, $sector) = @_; my ($pt, $info); #- it can be safely considered that the first sector is used to probe the partition table #- but other sectors (typically for extended partition ones) have to match this type! if (!$sector) { my @parttype = ( if_(arch() =~ /^ia64/, 'gpt'), arch() =~ /^sparc/ ? ('sun', 'bsd') : ('dos', 'bsd', 'sun', 'mac'), ); foreach ('empty', @parttype, 'lvm_PV', 'unknown') { /unknown/ and die "unknown partition table format on disk " . $hd->{file}; eval { # perl_checker: require partition_table::bsd # perl_checker: require partition_table::dos # perl_checker: require partition_table::empty # perl_checker: require partition_table::gpt # perl_checker: require partition_table::lvm_PV # perl_checker: require partition_table::mac # perl_checker: require partition_table::sun require "partition_table/$_.pm"; bless $hd, "partition_table::$_"; ($pt, $info) = $hd->read($sector); log::l("found a $_ partition table on $hd->{file} at sector $sector"); }; $@ or last; } } else { #- keep current blessed object for that, this means it is neccessary to read sector 0 before. ($pt, $info) = $hd->read($sector); } my @extended = $hd->hasExtended ? grep { isExtended($_) } @$pt : (); my @normal = grep { $_->{size} && $_->{type} && !isExtended($_) } @$pt; @extended > 1 and die "more than one extended partition"; $_->{rootDevice} = $hd->{device} foreach @normal, @extended; { raw => $pt, extended => $extended[0], normal => \@normal, info => $info }; } sub read { my ($hd) = @_; my $pt = read_one($hd, 0) or return 0; $hd->{primary} = $pt; undef $hd->{extended}; verifyPrimary($pt); eval { my $need_removing_empty_extended; $pt->{extended} and read_extended($hd, $pt->{extended}, \$need_removing_empty_extended) || return 0; if ($need_removing_empty_extended) { #- special case when hda5 is empty, it must be skipped #- (windows XP generates such partition tables) remove_empty_extended($hd); #- includes adjust_main_extended } }; die "extended partition: $@" if $@; assign_device_numbers($hd); remove_empty_extended($hd); 1; } sub read_extended { my ($hd, $extended, $need_removing_empty_extended) = @_; my $pt = read_one($hd, $extended->{start}) or return 0; $pt = { %$extended, %$pt }; push @{$hd->{extended}}, $pt; @{$hd->{extended}} > 100 and die "oops, seems like we're looping here :( (or you have more than 100 extended partitions!)"; if (@{$pt->{normal}} == 0) { $$need_removing_empty_extended = 1; delete $pt->{normal}; print "need_removing_empty_extended\n"; } elsif (@{$pt->{normal}} > 1) { die "more than one normal partition in extended partition"; } else { $pt->{normal} = $pt->{normal}[0]; #- in case of extended partitions, the start sector is local to the partition or to the first extended_part! $pt->{normal}{start} += $pt->{start}; #- the following verification can broke an existing partition table that is #- correctly read by fdisk or cfdisk. maybe the extended partition can be #- recomputed to get correct size. if (!verifyInside($pt->{normal}, $extended)) { $extended->{size} = $pt->{normal}{start} + $pt->{normal}{size}; verifyInside($pt->{normal}, $extended) or die "partition $pt->{normal}{device} is not inside its extended partition"; } } if ($pt->{extended}) { $pt->{extended}{start} += $hd->{primary}{extended}{start}; return read_extended($hd, $pt->{extended}, $need_removing_empty_extended); } else { 1; } } # write the partition table sub write { my ($hd) = @_; $hd->{isDirty} or return; $hd->{readonly} and die "a read-only partition table should not be dirty!"; #- set first primary partition active if no primary partitions are marked as active. if (my @l = @{$hd->{primary}{raw}}) { foreach (@l) { $_->{local_start} = $_->{start}; $_->{active} ||= 0; } $l[0]{active} = 0x80 if !any { $_->{active} } @l; } #- last chance for verification, this make sure if an error is detected, #- it will never be writed back on partition table. verifyParts($hd); $hd->write(0, $hd->{primary}{raw}, $hd->{primary}{info}) or die "writing of partition table failed"; #- should be fixed but a extended exist with no real extended partition, that blanks mbr! if (arch() !~ /^sparc/) { foreach (@{$hd->{extended}}) { # in case of extended partitions, the start sector must be local to the partition $_->{normal}{local_start} = $_->{normal}{start} - $_->{start}; $_->{extended} and $_->{extended}{local_start} = $_->{extended}{start} - $hd->{primary}{extended}{start}; $hd->write($_->{start}, $_->{raw}) or die "writing of partition table failed"; } } $hd->{isDirty} = 0; $hd->{hasBeenDirty} = 1; #- used in undo (to know if undo should believe isDirty or not) if ($hd->{needKernelReread} && ref($hd->{needKernelReread}) eq 'ARRAY' && $::isStandalone) { #- we've only been adding partitions. Try special add_partition (using BLKPG_ADD_PARTITION) local *F; partition_table::raw::openit($hd, *F) or goto force_reread; foreach (@{$hd->{needKernelReread}}) { c::add_partition(fileno F, $_->{start}, $_->{size}, $_->{device} =~ /(\d+)$/) or goto force_reread; } } elsif ($hd->{needKernelReread}) { force_reread: #- now sync disk and re-read the partition table common::sync(); my @magic_parts = grep { $_->{isMounted} && $_->{real_mntpoint} } get_normal_parts($hd); foreach (@magic_parts) { syscall_('umount', $_->{real_mntpoint}) or log::l(N("error unmounting %s: %s", $_->{real_mntpoint}, $!)); } $hd->kernel_read; foreach (@magic_parts) { syscall_('mount', $_->{real_mntpoint}, type2fs($_), c::MS_MGC_VAL()) or log::l(N("mount failed: ") . $!); } } $hd->{needKernelReread} = 0; } sub active { my ($hd, $part) = @_; $_->{active} = 0 foreach @{$hd->{primary}{normal}}; $part->{active} = 0x80; $hd->{isDirty} = 1; } # remove a normal partition from hard drive hd sub remove { my ($hd, $part) = @_; my $i; #- first search it in the primary partitions $i = 0; foreach (@{$hd->{primary}{normal}}) { if ($_ eq $part) { splice(@{$hd->{primary}{normal}}, $i, 1); %$_ = (); #- blank it $hd->raw_removed($hd->{primary}{raw}); return $hd->{isDirty} = $hd->{needKernelReread} = 1; } $i++; } my ($first, $second, $third) = map { $_->{normal} } @{$hd->{extended} || []}; if ($third && $first eq $part) { die "Can't handle removing hda5 when hda6 is not the second partition" if $second->{start} > $third->{start}; } #- otherwise search it in extended partitions foreach (@{$hd->{extended} || []}) { $_->{normal} eq $part or next; delete $_->{normal}; #- remove it remove_empty_extended($hd); assign_device_numbers($hd); return $hd->{isDirty} = $hd->{needKernelReread} = 1; } 0; } # create of partition at starting at `start', of size `size' and of type `type' (nice comment, uh?) sub add_primary { my ($hd, $part) = @_; { local $hd->{primary}{normal}; #- save it to fake an addition of $part, that way add_primary do not modify $hd if it fails push @{$hd->{primary}{normal}}, $part; adjust_main_extended($hd); #- verify $hd->raw_add($hd->{primary}{raw}, $part); } push @{$hd->{primary}{normal}}, $part; #- really do it } sub add_extended { arch() =~ /^sparc|ppc/ and die N("Extended partition not supported on this platform"); my ($hd, $part, $extended_type) = @_; $extended_type =~ s/Extended_?//; my $e = $hd->{primary}{extended}; if ($e && !verifyInside($part, $e)) { #-die "sorry, can't add outside the main extended partition" unless $::unsafe; my $end = $e->{start} + $e->{size}; my $start = min($e->{start}, $part->{start}); $end = max($end, $part->{start} + $part->{size}) - $start; { #- faking a resizing of the main extended partition to test for problems local $e->{start} = $start; local $e->{size} = $end - $start; eval { verifyPrimary($hd->{primary}) }; $@ and die N("You have a hole in your partition table but I can't use it. The only solution is to move your primary partitions to have the hole next to the extended partitions."); } } if ($e && $part->{start} < $e->{start}) { my $l = first(@{$hd->{extended}}); #- the first is a special case, must recompute its real size $l->{start} = round_down($l->{normal}{start} - 1, $hd->cylinder_size()); $l->{size} = $l->{normal}{start} + $l->{normal}{size} - $l->{start}; my $ext = { %$l }; unshift @{$hd->{extended}}, { type => 5, raw => [ $part, $ext, {}, {} ], normal => $part, extended => $ext }; #- size will be autocalculated :) } else { my ($ext, $ext_size) = is_empty_array_ref($hd->{extended}) ? ($hd->{primary}, -1) : #- -1 size will be computed by adjust_main_extended (top(@{$hd->{extended}}), $part->{size}); my %ext = (type => $extended_type || 5, start => $part->{start}, size => $ext_size); $hd->raw_add($ext->{raw}, \%ext); $ext->{extended} = \%ext; push @{$hd->{extended}}, { %ext, raw => [ $part, {}, {}, {} ], normal => $part }; } $part->{start}++; $part->{size}--; #- let it start after the extended partition sector adjustStartAndEnd($hd, $part); adjust_main_extended($hd); } sub add { my ($hd, $part, $primaryOrExtended, $forceNoAdjust) = @_; get_normal_parts($hd) >= ($hd->{device} =~ /^rd/ ? 7 : $hd->{device} =~ /^(sd|ida|cciss|ataraid)/ ? 15 : 63) and cdie "maximum number of partitions handled by linux reached"; $part->{notFormatted} = 1; $part->{isFormatted} = 0; $part->{rootDevice} = $hd->{device}; $part->{start} ||= 1 if arch() !~ /^sparc/; #- starting at sector 0 is not allowed adjustStartAndEnd($hd, $part) unless $forceNoAdjust; my $nb_primaries = $hd->{device} =~ /^rd/ ? 3 : 1; if (arch() =~ /^sparc|ppc/ || $primaryOrExtended eq 'Primary' || $primaryOrExtended !~ /Extended/ && @{$hd->{primary}{normal} || []} < $nb_primaries) { eval { add_primary($hd, $part) }; goto success if !$@; } if ($hd->hasExtended) { eval { add_extended($hd, $part, $primaryOrExtended) }; goto success if !$@; } { add_primary($hd, $part); } success: assign_device_numbers($hd); $hd->{isDirty} = 1; push @{$hd->{needKernelReread} ||= []}, $part if !$hd->{needKernelReread} || ref($hd->{needKernelReread}) eq 'ARRAY' } # search for the next partition sub next { my ($hd, $part) = @_; first( sort { $a->{start} <=> $b->{start} } grep { $_->{start} >= $part->{start} + $part->{size} } get_normal_parts($hd) ); } sub next_start { my ($hd, $part) = @_; my $next = &next($hd, $part); $next ? $next->{start} : $hd->{totalsectors}; } sub load { my ($hd, $file, $force) = @_; local *F; open F, $file or die N("Error reading file %s", $file); my $h; { local $/ = "\0"; eval ; } $@ and die N("Restoring from file %s failed: %s", $file, $@); ref $h eq 'ARRAY' or die N("Bad backup file"); my %h; @h{@fields2save} = @$h; $h{totalsectors} == $hd->{totalsectors} or $force or cdie "bad totalsectors"; #- unsure we don't modify totalsectors local $hd->{totalsectors}; @{$hd}{@fields2save} = @$h; delete @$_{qw(isMounted isFormatted notFormatted toFormat toFormatUnsure)} foreach get_normal_parts($hd); $hd->{isDirty} = $hd->{needKernelReread} = 1; } sub save { my ($hd, $file) = @_; my @h = @{$hd}{@fields2save}; require Data::Dumper; eval { output($file, Data::Dumper->Dump([\@h], ['$h']), "\0") } or die N("Error writing to file %s", $file); } 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 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 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 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
package ugtk2;

use diagnostics;
use strict;
use vars qw(@ISA %EXPORT_TAGS @EXPORT_OK @icon_paths $wm_icon $force_center_at_pos $force_center $force_focus $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 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 ) ],

    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;
}
Gtk2->croak_execeptions if (!$::no_ugtk_init || $::isInstall) && 0.95 < $Gtk2::VERSION ;


$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::WrappedLabel->new($l);
	$w->add(gtkshow($l));
    }
    $w
}

sub gtkadd_widget {
    my $sg = shift;
    map {
        my $l = $_;
        ref $l or $l = Gtk2::WrappedLabel->new($l);
        $sg->add_widget($l);
        $l;
    } @_;
}

sub gtkappend {
    my $w = shift;
    foreach my $l (@_) {
	ref $l or $l = Gtk2::WrappedLabel->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::WrappedLabel->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) =~ /Gtk2::TextView|Gtk2::TreeView/) {
    	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));
     my $width = 400;
     $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;
                            });
     $scroll->set_size_request($width, 200);
	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);
					   } @_),
					   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
		      } @_),
		      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
    may_set_icon($dialog, $wm_icon || $::Wizard_pix_up || "wiz_default_up.png");
    $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') }