diff options
author | ribet | 2007-03-21 10:19:39 +0000 |
---|---|---|
committer | ribet | 2007-03-21 10:19:39 +0000 |
commit | c5866f304210618979d03c561b1e3f6f83200bce (patch) | |
tree | 7c81ae161f78cdf952f3d3a33184f8bf322c9bd8 /src/MTools | |
parent | a023d10b564d8c29566304f7777b4ec87c5b7b4d (diff) | |
download | mtc-c5866f304210618979d03c561b1e3f6f83200bce.zip mtc-c5866f304210618979d03c561b1e3f6f83200bce.tar.gz mtc-c5866f304210618979d03c561b1e3f6f83200bce.tar.bz2 mtc-c5866f304210618979d03c561b1e3f6f83200bce.tar.xz |
Import initial
Diffstat (limited to 'src/MTools')
36 files changed, 9300 insertions, 0 deletions
diff --git a/src/MTools/Adapters/WacomAdapter.pm b/src/MTools/Adapters/WacomAdapter.pm new file mode 100644 index 0000000..5d6c77a --- /dev/null +++ b/src/MTools/Adapters/WacomAdapter.pm @@ -0,0 +1,159 @@ +package MTools::Adapters::WacomAdapter; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +use strict; +use MTools; +use MTools::MObjet; +use MTools::MIvy; +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class, $adresse, $ivy_name, $wacom_adresse) = @_; + my $self = new MTools::MObjet (); + if (!defined $wacom_adresse) + { + $wacom_adresse = 'default'; + } + bless $self, $class; + $self -> {__pointer_status} = 0; + $self -> {__ivy} = new MTools::MIvy ($adresse, $ivy_name); + $self -> {__ivy} -> binding ('pad_event wacom_id='.$wacom_adresse.' button=(.*) status=(.*) time=(.*)', [\&wacom_event, $self, 'buttons']); + $self -> {__ivy} -> binding ('slider_event wacom_id='.$wacom_adresse.' value=(.*) side=(.*) time=(.*)', [\&wacom_event, $self, 'sliders']); + $self -> {__ivy} -> binding ('pointer_event wacom_id='.$wacom_adresse.' x=(.*) y=(.*) presure=(.*) tilt_x=(.*) tilt_y=(.*) wheel=(.*) predicted_x=(.*) predicted_y=(.*) type=(.*) serial_number=(.*) time=(.*)', [\&wacom_event, $self, 'pointers']); + return $self; + +} + +sub binding { + my ($self, $reg, $cb) = @_; + if ($reg eq '<WSlider>') + { + push (@{$self -> {sliders} -> {all}}, $cb); + } + elsif ($reg =~ /\<WSlider(.*)-(.*)\>/) + { + push (@{$self -> {sliders} -> {$1} -> {$2}}, $cb); + } + elsif ($reg =~ /\<WSlider(.*)\>/) + { + push (@{$self -> {sliders} -> {$1} -> {all}}, $cb); + } + elsif ($reg eq '<WButton>') + { + push (@{$self -> {buttons} -> {all}}, $cb); + } + elsif ($reg =~ /\<WButton(.*)-(.*)\>/) + { + push (@{$self -> {buttons} -> {$1} -> {$2}}, $cb); + } + elsif ($reg =~ /\<WButton(.*)\>/) + { + push (@{$self -> {buttons} -> {$1} -> {all}}, $cb); + } + elsif ($reg eq '<WPointer>') + { + push (@{$self -> {pointers} -> {all}}, $cb); + } + elsif ($reg =~ /\<WPointer(.*)-(.*)\>/) + { + push (@{$self -> {pointers} -> {$1} -> {$2}}, $cb); + } + elsif ($reg =~ /\<WPointer(.*)\>/) + { + push (@{$self -> {pointers} -> {$1} -> {all}}, $cb); + } + else + { + die "Can't recognize a wacom event in $reg\n"; + } +} + +sub wacom_event { + my ($agent, $self, $type, $value, $status, $time, @others) = @_; + my @callbacks = (); + my @args = (); + if ($type eq 'sliders') + { + my $nb = 0; + if ($value != 0) + { + while ($value != 1) + { + $value = $value / 2; + $nb ++; + } + $nb++; + } + $value = $nb; + } + if ($type eq 'pointers') + { + $status = $others [5]; + if ($status =~ /(.*)_(.*)_(.*)_(.*)/) + { + $status = $3; + } + elsif ($status =~ /(.*)_(.*)_(.*)/) + { + $status = $2; + } + if ($time == 0) + { + $value = 'Release'; + $self -> {__pointer_status} = 0; + } + else + { + if ($self -> {__pointer_status}) + { + $value = 'Motion'; + } + else + { + $value = 'Press'; + $self -> {__pointer_status} = 1; + } + } + } + if (defined $self -> {$type} -> {all}) + { + push (@callbacks, @{$self -> {$type} -> {all}}); + } + if (defined $self -> {$type} -> {$status} -> {all}) + { + push (@callbacks, @{$self -> {$type} -> {$status} -> {all}}); + } + if (defined $self -> {$type} -> {$status} -> {$value}) + { + push (@callbacks, @{$self -> {$type} -> {$status} -> {$value}}); + } + for (my $i = 0; $i < @callbacks; $i ++) + { + executer ($callbacks[$i], $value, $status, $type); + } +} + + +1; diff --git a/src/MTools/Anim/MOpacity.pm b/src/MTools/Anim/MOpacity.pm new file mode 100644 index 0000000..e1882ba --- /dev/null +++ b/src/MTools/Anim/MOpacity.pm @@ -0,0 +1,143 @@ +package MTools::Anim::MOpacity; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# MOpacity permet de realiser une animation sur la transparence d'un objet +# +# proprietes : +# * -visible : permet d'activer ou non l'animation +# * from_opacity : valeur initiale de l'opacite au depart de l'animation +# * to_opacity : valeur de l'opacite a la fin de l'animation +# * duration : duree de l'animation +# * loop : marque le caractere repetitif ou non de l'animation +# * targets : objets cible de cette animation +# Evenements : +# * ANIMATION_END : Notifie lorque l'annimation se termine +# * OPACITY_CHANGED : Notifie lorsque la valeur de l'opacite est changee au cours de l'animation +# * ANIMATION_ABORD : Notifie lorsque l'animation est stoppee avant la fin +# Fonctions : +# * start : demarre l'animation +# * stop: arrete l'animation +# * isRunning : test si l'animation est en cours + +use strict; +use MTools; +use MTools::MObjet; + +use Anim; +use Anim::Pacing::Linear; +use Anim::Path::Rectilinear; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class, %options) = @_; + my $self = new MTools::MObjet (); + bless $self, $class; + + $self -> recordProperty ('-visible', 0); + $self -> recordProperty ('from_opacity', 0); + $self -> recordProperty ('to_opacity', 0); + $self -> recordProperty ('duration', 1); + $self -> recordProperty ('loop', 0); + $self -> recordProperty ('targets', undef); + $self -> recordEvent ('ANIMATION_END'); + $self -> recordEvent ('OPACITY_CHANGED'); + $self -> recordEvent ('ANIMATION_ABORD'); + $self -> plisten ('-visible', sub { + my ($src, $key, $val) = @_; + if ($val == 0) + { + $self -> stop (); + } + else + { + $self -> start (); + } + }); + $self -> {__animation} = undef; + $self -> mconfigure (%options); + return $self; +} + +sub start { + my ($self) = @_; + my $pacing = new Anim::Pacing::Linear (-duration => $self -> mget ('duration')); + $self -> {__opacitydep} = my $opacitydep = $self -> mget ('from_opacity'); + + my $animationpath = new Anim::Path::Rectilinear ( + -xdep => 0, + -ydep => 0, + -xdest => $self -> mget ('to_opacity') - $opacitydep, + -ydest => 0, + ); + $self -> {__opacity} = $opacitydep; + $self -> {__animation} = my $animation = new Anim ( + -pacing => $pacing, + -resources => [ + $animationpath, + -command => sub { $self -> __event (@_)}, + -endcommand => sub {$self -> notify ('ANIMATION_END');$self -> {__animation} = undef;}, + ], + -stopcommand => sub {$self -> notify ('ANIMATION_ABORD', $self -> {__opacity});$self -> {__animation} = undef;}, + -loop => $self -> mget ('loop'), + ); + $animation -> start (); +} + +sub stop { + my ($self) = @_; + if (defined $self -> {__animation}) + { + $self -> {__animation} -> stop (); + } +} + +sub __event { + my ($self, $opacity) = @_; + $opacity += $self -> {__opacitydep}; + my @targets = (); + my $target = $self -> mget ('targets'); + if (ref ($target) eq 'ARRAY') + { + @targets = @{$target}; + } + else + { + push (@targets, $target); + } + for (my $i = 0; $i < @targets; $i++) + { + $targets [$i] -> mconfigure ('-alpha' => $opacity); + } + $self -> {__opacity} = $opacity; + $self -> notify ('OPACITY_CHANGED', $opacity); +} + +sub isRunning { + my ($self) = @_; + return defined $self -> {__animation}; +} + +1; diff --git a/src/MTools/Anim/MPath.pm b/src/MTools/Anim/MPath.pm new file mode 100644 index 0000000..6fcbb2f --- /dev/null +++ b/src/MTools/Anim/MPath.pm @@ -0,0 +1,193 @@ +package MTools::Anim::MPath; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# MPath permet de realiser une animation de deplacement suivant un chemin +# +# proprietes : +# * -visible : permet d'activer ou non l'animation +# * path : chemin +# * duration : duree de l'animation +# * loop : marque le caractere repetitif ou non de l'animation +# * targets : objets cible de cette animation +# Evenements : +# * ANIMATION_END : Notifie lorque l'annimation se termine +# * VALUE_CHANGED : Notifie lorsque la valeur de l'opacite est changee au cours de l'animation +# * ANIMATION_ABORD : Notifie lorsque l'animation est stoppee avant la fin +# Fonctions : +# * start : demarre l'animation +# * stop: arrete l'animation +# * isRunning : test si l'animation est en cours + +use strict; +use MTools; +use MTools::MObjet; + +use Anim; +use Anim::Pacing::Linear; +use Anim::Path::Rectilinear; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class, %options) = @_; + my $self = new MTools::MObjet (); + bless $self, $class; + + $self -> recordProperty ('-visible', 0); + $self -> recordProperty ('path', []); + $self -> recordProperty ('duration', 1); + $self -> recordProperty ('loop', 0); + $self -> recordProperty ('targets', undef); + $self -> recordEvent ('ANIMATION_END'); + $self -> recordEvent ('VALUE_CHANGED'); + $self -> recordEvent ('ANIMATION_ABORD'); + $self -> plisten ('path', [$self, 'pathchanged']); + $self -> plisten ('-visible', sub { + my ($src, $key, $val) = @_; + if ($val == 0) + { + $self -> stop (); + } + else + { + $self -> start (); + } + }); + $self -> {__animation} = undef; + $self -> {__length} = 0; + $self -> {__x} = 0; + $self -> {__y} = 0; + $self -> {__vx} = 0; + $self -> {__vy} = 0; + $self -> mconfigure (%options); + return $self; +} + +sub pathchanged { + my ($self, $src, $key, $value) = @_; + my @points = @{$value}; + my $length = 0; + for (my $i = 0; $i < @points - 1; $i ++) + { + my $x = $points [$i + 1] -> [0] - $points [$i] -> [0]; + my $y = $points [$i + 1] -> [1] - $points [$i] -> [1]; + $length += sqrt ($x * $x + $y * $y); + } + $self -> {__length} = $length; +} + +sub start { + my ($self) = @_; + + my @points = @{$self -> mget ('path')}; + if (!defined @points || @points <= 0) {return;} + $self -> {__x} = $points [0] -> [0]; + $self -> {__y} = $points [0] -> [1]; + my $pacing = new Anim::Pacing::Linear (-duration => $self -> mget ('duration')); + $self -> {__percentage} = 0; + my $animationpath = new Anim::Path::Rectilinear ( + -xdep => 0, + -ydep => 0, + -xdest => 100, + -ydest => 0, + ); + $self -> {__animation} = my $animation = new Anim ( + -pacing => $pacing, + -resources => [ + $animationpath, + -command => sub { $self -> __event (@_)}, + -endcommand => sub {$self -> notify ('ANIMATION_END'); $self -> {__animation} = undef;}, + ], + -stopcommand => sub { + $self -> notify ('ANIMATION_ABORD', $self -> __getPoint ($self -> {__percentage})); + $self -> {__animation} = undef; + }, + -loop => $self -> mget ('loop'), + ); + $animation -> start (); +} + +sub stop { + my ($self) = @_; + if (defined $self -> {__animation}) + { + $self -> {__animation} -> stop (); + } +} + +sub __getPoint { + my ($self, $percentage) = @_; + my @points = @{$self -> mget ('path')}; + my $length = $self -> {__length} * $percentage / 100; + my $x = 0; + my $y = 0; + my $vx = 0; + my $vy = 0; + for (my $i = 0; $i < @points - 1; $i ++) + { + $vx = $x = $points [$i + 1] -> [0] - $points [$i] -> [0]; + $vy = $y = $points [$i + 1] -> [1] - $points [$i] -> [1]; + my $d = sqrt ($x * $x + $y * $y); + $length -= $d; + if ($length <= 0) + { + $d = ($d + $length) / $d; + $x = $d * $x + $points [$i] -> [0]; + $y = $d * $y + $points [$i] -> [1]; + $i = @points; + } + } + return ($x, $y, $vx, $vy); +} + +sub __event { + my ($self, $percentage) = @_; + my ($x, $y, $vx, $vy) = $self -> __getPoint ($percentage); + my @targets = (); + my $target = $self -> mget ('targets'); + if (ref ($target) eq 'ARRAY') + { + @targets = @{$target}; + } + else + { + push (@targets, $target); + } + for (my $i = 0; $i < @targets; $i++) + { + $targets [$i] -> translate ($x - $self -> {__x}, $y - $self -> {__y}); + } + $self -> {__x} = $x; + $self -> {__y} = $y; + $self -> {__percentage} = $percentage; + $self -> notify ('VALUE_CHANGED', $x, $y, $vx, $vy); +} + +sub isRunning { + my ($self) = @_; + return defined $self -> {__animation}; +} + +1; diff --git a/src/MTools/Anim/MScalor.pm b/src/MTools/Anim/MScalor.pm new file mode 100644 index 0000000..cbdc49d --- /dev/null +++ b/src/MTools/Anim/MScalor.pm @@ -0,0 +1,154 @@ +package MTools::Anim::MScalor; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# MScalor permet de realiser une animation de scale sur l'objet +# +# proprietes : +# * -visible : permet d'activer ou non l'animation +# * center_x, center_y : coordonnees du centre de la transformation +# * from_x, from_y : valeur initiale de la transformation +# * to_x, to_y : valeur finale de la transformation +# * duration : duree de l'animation +# * loop : marque le caractere repetitif ou non de l'animation +# * targets : objets cible de cette animation +# Evenements : +# * ANIMATION_END : Notifie lorque l'annimation se termine +# * SCALED : Notifie lorsque la valeur de l'opacite est changee au cours de l'animation +# * ANIMATION_ABORD : Notifie lorsque l'animation est stoppee avant la fin +# Fonctions : +# * start : demarre l'animation +# * stop: arrete l'animation +# * isRunning : test si l'animation est en cours + +use strict; +use MTools; +use MTools::MObjet; + +use Anim; +use Anim::Pacing::Linear; +use Anim::Path::Rectilinear; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class, %options) = @_; + my $self = new MTools::MObjet (); + bless $self, $class; + + $self -> recordProperty ('-visible', 0); + $self -> recordProperty ('center_x', 0); + $self -> recordProperty ('center_y', 0); + $self -> recordProperty ('from_x', 0); + $self -> recordProperty ('from_y', 0); + $self -> recordProperty ('to_x', 0); + $self -> recordProperty ('to_y', 0); + $self -> recordProperty ('duration', 1); + $self -> recordProperty ('loop', 0); + $self -> recordProperty ('targets', undef); + $self -> recordEvent ('ANIMATION_END'); + $self -> recordEvent ('SCALED'); + $self -> recordEvent ('ANIMATION_ABORD'); + $self -> plisten ('-visible', sub { + my ($src, $key, $val) = @_; + if ($val == 0) + { + $self -> stop (); + } + else + { + $self -> start (); + } + }); + $self -> {__animation} = undef; + $self -> mconfigure (%options); + return $self; +} + +sub start { + my ($self) = @_; + my $pacing = new Anim::Pacing::Linear (-duration => $self -> mget ('duration')); + $self -> {__xdep} = my $xdep = $self -> mget ('from_x'); + $self -> {__ydep} = my $ydep = $self -> mget ('from_y'); + + my $animationpath = new Anim::Path::Rectilinear ( + -xdep => 0, + -ydep => 0, + -xdest => $self -> mget ('to_x') - $xdep, + -ydest => $self -> mget ('to_y') - $ydep, + ); + $self -> {__x} = $xdep; + $self -> {__y} = $ydep; + $self -> {__animation} = my $animation = new Anim ( + -pacing => $pacing, + -resources => [ + $animationpath, + -command => sub { $self -> __event (@_)}, + -endcommand => sub {$self -> notify ('ANIMATION_END');$self -> {__animation} = undef;}, + ], + -stopcommand => sub {$self -> notify ('ANIMATION_ABORD', $self -> {__x}, $self -> {__y});$self -> {__animation} = undef;}, + -loop => $self -> mget ('loop'), + ); + $animation -> start (); +} + +sub stop { + my ($self) = @_; + if (defined $self -> {__animation}) + { + $self -> {__animation} -> stop (); + } +} + +sub __event { + my ($self, $x, $y) = @_; + my $cx = $self -> mget ('center_x'); + my $cy = $self -> mget ('center_y'); + $x += $self -> {__xdep}; + $y += $self -> {__ydep}; + my @targets = (); + my $target = $self -> mget ('targets'); + if (ref ($target) eq 'ARRAY') + { + @targets = @{$target}; + } + else + { + push (@targets, $target); + } + for (my $i = 0; $i < @targets; $i++) + { + scale ($targets [$i], $x / $self -> {__x}, $y / $self -> {__y}, $cx, $cy); + } + $self -> {__x} = $x; + $self -> {__y} = $y; + $self -> notify ('SCALED', $x, $y, $cx, $cy); +} + +sub isRunning { + my ($self) = @_; + return defined $self -> {__animation}; +} + +1; diff --git a/src/MTools/Anim/MTranslator.pm b/src/MTools/Anim/MTranslator.pm new file mode 100644 index 0000000..3ac0544 --- /dev/null +++ b/src/MTools/Anim/MTranslator.pm @@ -0,0 +1,166 @@ +package MTools::Anim::MTranslator; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# MTranslator permet de realiser une animation de translation sur l'objet +# +# proprietes : +# * -visible : permet d'activer ou non l'animation +# * from_x, from_y : valeur initiale de la transformation +# * to_x, to_y : valeur finale de la transformation +# * duration : duree de l'animation +# * loop : marque le caractere repetitif ou non de l'animation +# * targets : objets cible de cette animation +# Evenements : +# * ANIMATION_END : Notifie lorque l'annimation se termine +# * MOTION : Notifie lorsque la valeur de l'opacite est changee au cours de l'animation +# * ANIMATION_ABORD : Notifie lorsque l'animation est stoppee avant la fin +# Fonctions : +# * start : demarre l'animation +# * stop: arrete l'animation +# * isRunning : test si l'animation est en cours + + +use strict; +use MTools; +use MTools::MObjet; + +use Anim; +use Anim::Pacing::Linear; +use Anim::Path::Rectilinear; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class, %options) = @_; + my $self = {}; + bless $self, $class; + + $self -> recordProperty ('-visible', 0); + $self -> recordProperty ('from_x', $options {from_x} ? $options {from_x} : 0); + $self -> recordProperty ('from_y', $options {from_y} ? $options {from_y} : 0); + $self -> recordProperty ('to_x', $options {to_x} ? $options {to_x} : 0); + $self -> recordProperty ('to_y', $options {to_y} ? $options {to_y} : 0); + $self -> recordProperty ('duration', $options {duration} ? $options {duration} : 1); + $self -> recordProperty ('loop', $options {loop} ? $options {loop} : 0); + $self -> recordProperty ('targets', $options {targets}); + + $self -> recordEvent ('ANIMATION_END'); + $self -> recordEvent ('MOTION'); + $self -> recordEvent ('ANIMATION_ABORDED'); + + $self -> plisten ('-visible', sub { + my ($src, $key, $val) = @_; + if ($val == 0) + { + $self -> stop (); + } + else + { + $self -> start (); + } + }); + $self -> {__animation} = undef; + $self -> mconfigure (%options); + return $self; +} + +sub stop { + my ($self) = @_; + if (defined $self -> {__animation}) + { + $self -> {__animation} -> stop (); + } +} + +sub start { + my ($self) = @_; + my $pacing = new Anim::Pacing::Linear (-duration => $self -> mget ('duration')); + $self -> {__xdep} = my $xdep = $self -> mget ('from_x'); + $self -> {__ydep} = my $ydep = $self -> mget ('from_y'); + + my $animationpath = new Anim::Path::Rectilinear ( + -xdep => 0, + -ydep => 0, + -xdest => $self -> mget ('to_x') - $xdep, + -ydest => $self -> mget ('to_y') - $ydep, + ); + $self -> {__x} = $xdep; + $self -> {__y} = $ydep; + $self -> {__animation} = my $animation = new Anim ( + -pacing => $pacing, + -resources => [ + $animationpath, + -command => sub { $self -> event (@_)}, + -endcommand => sub { + $self -> {__animation} = undef; + $self -> notify ('ANIMATION_END'); + }, + ], + -stopcommand => sub { + $self -> {__animation} = undef; + $self -> notify ('ANIMATION_ABORDED', $self -> {__x}, $self -> {__y}); + }, + -loop => $self -> mget ('loop'), + ); + $animation -> start (); +} + +sub isRunning { + my ($self) = @_; + return defined $self -> {__animation}; +} + + +sub event { + my ($self, $x, $y) = @_; + $x += $self -> {__xdep}; + $y += $self -> {__ydep}; + my @targets = (); + my $target = $self -> mget ('targets'); + if (ref ($target) eq 'ARRAY') + { + @targets = @{$target}; + } + else + { + push (@targets, $target); + } + for (my $i = 0; $i < @targets; $i++) + { + if (ref ($targets [$i]) eq 'MTools::Comp::MMover') + { + $target -> setPos ($x, $y); + $target -> notify ('MOVED', $x, $y, "mvd"); + } + else + { + $targets [$i] -> translate ($x - $self -> {__x}, $y - $self -> {__y}); + } + } + $self -> {__x} = $x; + $self -> {__y} = $y; + $self -> notify ('MOTION', $x, $y); +} +1; diff --git a/src/MTools/Comp/MAntiRecouvrement.pm b/src/MTools/Comp/MAntiRecouvrement.pm new file mode 100644 index 0000000..1e10edd --- /dev/null +++ b/src/MTools/Comp/MAntiRecouvrement.pm @@ -0,0 +1,240 @@ +package MTools::Comp::MAntiRecouvrement; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Encapsule l'algorithme d'anti-recouvrement des objets et gere les objets anti-recouvres +# IMPORTANT : Les objets anti-recouvre doivent heriter de MTools::GUI::MAntiRecouvrementGroup +# +# BUG : La propriete '-visible' devrait permettre d'activer ou non l'anti-recouvrement global des objets. +# Ce n'est pas le cas aujourd'hui, cette popriete est inactive +# +# Fonctions : +# * addObject : permet d'inclure un objet heritant de MTools::GUI::MAntiRecouvrementGroup dans l'algorithme d'anti-recouvrement +# * removeObjet : permet de sortir un objet de l'algorithme d'anti-recouvrement + +use strict; +use MTools; +use MTools::MObjet; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class) = @_; + my $self = new MTools::MObjet (); + bless $self, $class; + + $self -> recordProperty ('-visible', 1); + $self -> recordEvent ('ITEM_MOVED'); + $self -> {__objects} = (); + $self -> {__known_objects} = (); + $self -> {__ask_move} = (); + $self -> {__ask_reaction} = (); + + return $self; +} + +sub addObject { + my ($self, $ob) = @_; + my $ever_known = 0; + if (defined $self -> {__known_objects}) + { + my @known = @{$self -> {__known_objects}}; + for (my $i = 0; $i < @known; $i ++) + { + if ($known [$i] eq $ob) + { + $ever_known = 1; + last; + } + } + } + if (!$ever_known) + { + binding ($ob, '__HANDLE_MOVING', [$self, \&__on_handle_moving_on_track]); + binding ($ob, '__PUSH_BACK', [$self, \&__on_push_back_on_track]); + binding ($ob, '__ENQUEUE_MOVING', [$self, \&__on_enqueue_moving_on_track]); + push (@{$self -> {__known_objects}}, $ob); + } + if (!defined $ob -> {__added} || $ob -> {__added} == 0) + { + push (@{$self -> {__objects}}, $ob); + } + $ob -> update_bbox (); + $ob -> {__added} = 1; + $ob -> translate (0, 0); +} + +sub removeObject { + my ($self, $target) = @_; + for (my $i = @{$self -> {__objects}} - 1; $i >= 0; $i --) + { + if (@{$self -> {__objects}} [$i] eq $target) + { + @{$self -> {__objects}} [$i] -> {__added} = 0; + splice (@{$self -> {__objects}}, $i, 1); + } + } +} + +sub __on_handle_moving_on_track { + my ($self) = @_; + my ($first_work, $first_track, $current_track, $intersection); + while (scalar @{$self -> {__ask_move}} > 0) + { + $first_work = $self -> {__ask_move} -> [0]; + $first_track = $first_work -> [0]; + my ($firstx, $firsty) = ($first_track -> mget ('x'), $first_track -> mget ('y')); + for (my $i = 0; $i < @{$self -> {__objects}}; $i++) + { + $current_track = @{$self -> {__objects}} [$i]; + next if ($current_track eq $first_track); + my ($x, $y) = ($current_track -> mget ('x'), $current_track -> mget ('y')); + $intersection = __intersection ( + $firstx, $firsty, + $first_track -> mget ('width'), $first_track -> mget ('height'), + $x, $y, + $current_track -> mget ('width'), $current_track-> mget ('height') + ); + next if (($intersection -> [2] == 0) and ($intersection -> [3] == 0)); + if ($intersection -> [2] < $intersection -> [3]) + { + if ($firstx < $x) + { + $current_track -> __try_move ($intersection -> [2], 0, $first_work -> [3]); + } + else + { + $current_track -> __try_move(-$intersection -> [2], 0, $first_work -> [3]); + } + } + else + { + if ($firsty < $y) + { + $current_track -> __try_move (0, $intersection -> [3], $first_work -> [3]); + } + else + { + $current_track -> __try_move (0, -$intersection -> [3], $first_work -> [3]); + } + } + } + shift @{$self -> {__ask_move}}; + } + $self -> notify ('ITEM_MOVED'); +} + +sub __on_push_back_on_track { + my ($self, $track, $delta_x, $delta_y, $path) = @_; + push @{$path}, $track; + my @other_path = @{$path}; + $self -> __on_enqueue_moving_on_track ($track, $delta_x, $delta_y, [@other_path]); + $track -> __update_xy ($delta_x, $delta_y); + my ($current_track, $push_x, $push_y, $intersection); + my ($firstx, $firsty) = ($track -> mget ('x'), $track -> mget ('y')); + + for (my $i = 0; $i < @{$self -> {__objects}}; $i++) + { + $current_track = @{$self -> {__objects}} [$i]; + next if $current_track eq $track; + my ($x, $y) = ($current_track -> mget ('x'), $current_track -> mget ('y')); + $intersection = __intersection ( + $firstx, $firsty, + $track -> mget ('width'), $track -> mget ('height'), + $x, $y, + $current_track -> mget ('width'), $current_track -> mget ('height') + ); + $push_x = 0; + $push_y = 0; + $push_x = $intersection -> [2] if ($intersection -> [2] <= $delta_x); + $push_x = -$intersection -> [2] if ($intersection -> [2] <= -$delta_x); + $push_y = $intersection -> [3] if ($intersection -> [3] <= $delta_y); + $push_y = -$intersection -> [3] if ($intersection -> [3] <= -$delta_y); + $self -> __on_push_back_on_track ($current_track, $push_x, $push_y, $path) + if ((($push_x != 0) or ($push_y != 0)) and (__occurences ($current_track, @{$path}) < 3)); + } + pop @{$path}; +} + +sub __intersection { + my ($x1, $y1, $w1, $h1, $x2, $y2, $w2, $h2) = @_; + my ($x, $y, $w, $h); + $x = &__max_of ($x1, $x2); + $w = &__min_of ($x1 + $w1, $x2 + $w2) - $x; + if ($w > 0) + { + $y = &__max_of ($y1, $y2); + $h = &__min_of ($y1 + $h1, $y2 + $h2) - $y; + if ($h > 0) + { + return [$x, $y, $w, $h]; + } + } + return [0, 0, 0, 0]; +} + +sub __min_of { + my (@values) = @_; + my $res = $values [0]; + foreach (@values) + { + $res = $_ if ($_ <= $res); + } + return $res; +} + +sub __max_of { + my (@values) = @_; + my $res = $values [0]; + foreach (@values) + { + $res = $_ if ($_ >= $res); + } + return $res; +} + +sub __occurences { + my ($val,@tab) = @_; + my $result = 0; + if (($#tab != -1) and (defined $val)) + { + foreach (@tab) + { + if (($_ eq $val) or ($_ =~ m/$val/)) + { + $result++; + } + } + } + return $result; +} + +sub __on_enqueue_moving_on_track { + my ($self, $track, $delta_x, $delta_y, $path) = @_; + push @{$self -> {__ask_move}}, [$track, $delta_x, $delta_y, $path]; +} + + + +1; diff --git a/src/MTools/Comp/MFlicker.pm b/src/MTools/Comp/MFlicker.pm new file mode 100644 index 0000000..fd622c8 --- /dev/null +++ b/src/MTools/Comp/MFlicker.pm @@ -0,0 +1,79 @@ +package MTools::Comp::MFlicker; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Le composant permet d'ajouter un comportement de clignotement ? un objet cible +# +# Parametres : +# +# * target : objet cible du tremblement +# * periode : periode du clignottement +# Propriete : +# * flick : demarre le clignottement +# * show : rend l'objet cible toujours visible +# * hide : rend l'objet cible toujours masque + +use strict; +use MTools; +use MTools::MObjet; +use MTools::MTimer; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MSwitch/; +} + +use Tk; + +sub new { + my ($class, $target, $periode) = @_; + my $self = new MTools::MObjet (); + $self -> {__target} = $target; + $self -> {__target} -> mconfigure (-visible => 0); + bless $self, $class; + + $self -> recordProperty ('periode', $periode); + + $self -> {__timer} = new MTools::MTimer ($periode, 1, sub { + $self -> {__target} -> mconfigure (-visible => !$self -> {__target} -> mget (-visible)); + }); + + plink ([$self, 'periode'], [$self -> {__timer}, 'timeout']); + + return $self; +} + +sub flick { + my ($self) = @_; + $self -> {__timer} -> start (); +} + +sub show { + my ($self) = @_; + $self -> {__timer} -> stop (); + $self -> {__target} -> mconfigure (-visible => 1); +} + +sub hide { + my ($self) = @_; + $self -> {__timer} -> stop (); + $self -> mconfigure ('state' => 'unvisible'); +} + +1; diff --git a/src/MTools/Comp/MFocuser.pm b/src/MTools/Comp/MFocuser.pm new file mode 100644 index 0000000..cb821ae --- /dev/null +++ b/src/MTools/Comp/MFocuser.pm @@ -0,0 +1,89 @@ +package MTools::Comp::MFocuser; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# L'objet MFocuser permet de gerer le focus entre plusieurs objets +# +# Parametres : +# * @targets : objets entre lesquels est gere le focus +# Fonctions : +# * add : permet de prendre en compte un nouvel objet +# * setFocused : force le focus sur un objet + +use strict; +use MTools; +use MTools::MObjet; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class, @targets) = @_; + my $self = {}; + bless $self, $class; + + $self -> recordEvent ('GET_FOCUS'); + $self -> recordEvent ('SET_FOCUS'); + + $self -> {__targets} = \@targets; + for (my $i; $i < @targets; $i++) + { + $targets [$i] -> binding ('GET_FOCUS', ['setFocused', $self]); + } + + $self -> binding ('SET_FOCUS', ['setFocused', $self]); + + return $self; +} + +sub add { + my ($self, $tg) = @_; + push (@{$self -> {__targets}}, $tg); + $tg -> binding ('GET_FOCUS', ['setFocused', $self]); +} + +sub setFocused { + my ($self, $tg) = @_; + if (!defined $self -> {__targets}) {return;} + my @tgs = @{$self -> {__targets}}; + my $from_children = 0; + for (my $i; $i < @tgs; $i++) + { + if ($tgs [$i] ne $tg) + { + $tgs [$i] -> notify ('SET_FOCUS'); + } + else + { + $from_children = 1; + } + } + if ($from_children) + { + $self -> notify ('GET_FOCUS', $self); + } +} + +1; + + diff --git a/src/MTools/Comp/MInertie.pm b/src/MTools/Comp/MInertie.pm new file mode 100644 index 0000000..9b820a0 --- /dev/null +++ b/src/MTools/Comp/MInertie.pm @@ -0,0 +1,153 @@ +package MTools::Comp::MInertie; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +use strict; +use MTools; +use MTools::MObjet; +use Time::HiRes; + +use MTools::MTimer; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class, $target, %options) = @_; + my $self = new MTools::MObjet (); + bless $self, $class; + + my $msg_pressed = defined $options {msg_pressed} ? $options {msg_pressed} : 'PRESSED'; + my $msg_moved = defined $options {msg_moved} ? $options {msg_moved} : 'MOVED'; + my $msg_released = defined $options {msg_released} ? $options {msg_released} : 'RELEASED'; + my $msg_stopped = defined $options {msg_stopped} ? $options {msg_stopped} : 'INERTIE_STOPPED'; + + delete $options {msg_pressed}; + delete $options {msg_moved}; + delete $options {msg_released}; + delete $options {msg_stopped}; + + $self -> recordProperty ('target', $target); + $self -> recordProperty ('-visible', 1); + $self -> recordProperty ('rate', 0.85); + $self -> recordProperty ('inertie_callback', 'translate'); + + $self -> recordEvent ($msg_stopped); + $self -> mconfigure (%options); + + $self -> {__old_t} = 0; + $self -> {__old_x} = 0; + $self -> {__old_y} = 0; + $self -> {__x} = 0; + $self -> {__y} = 0; + $self -> {__t} = 0; + $self -> {__vx} = 0; + $self -> {__vy} = 0; + + $self -> {__msg_stopped} = $msg_stopped; + + $target -> binding ($msg_pressed, [$self, 'target_pressed']); + $target -> binding ($msg_moved, [$self, 'target_moved']); + $target -> binding ($msg_released, [$self, 'target_released']); + + $self -> {timer_inertie} = new MTools::MTimer (1000/60, 1, [$self, 'inertie']); + + return $self; +} + +sub interrupt { + my ($self) = @_; + $self -> {timer_inertie} -> stop (); +} + +sub target_pressed { + my ($self, $x, $y, $t) = @_; + $self -> interrupt (); + $self -> {__old_x} = 0; + $self -> {__old_y} = 0; + $self -> {__old_t} = 0; + $self -> {__x} = 0; + $self -> {__y} = 0; + $self -> {__t} = 0; +} + +sub target_moved { + my ($self, $x, $y, $t) = @_; + if (!defined $t) + { + $t = Time::HiRes::gettimeofday(); + } + $self -> {__old_x} = $self -> {__x}; + $self -> {__old_y} = $self -> {__y}; + $self -> {__old_t} = $self -> {__t}; + $self -> {__x} = $x; + $self -> {__y} = $y; + $self -> {__t} = $t; +} + +sub target_released { + my ($self, $x, $y, $t) = @_; + if (!defined $t) + { + $t = Time::HiRes::gettimeofday(); + } + my $dt = $self -> {__t} - $self -> {__old_t}; + my $dx = $self -> {__x} - $self -> {__old_x}; + my $dy = $self -> {__y} - $self -> {__old_y}; + if ($dt && $self -> mget ('-visible')) + { + $self -> {__vx} = ($dx * 1000) / ($dt * 60); + $self -> {__vy} = ($dy * 1000) / ($dt * 60); + $self -> {timer_inertie} -> start(); + } + else + { + $self -> notify ($self -> {__msg_stopped}); + } + $self -> {__old_x} = 0; + $self -> {__old_y} = 0; + $self -> {__old_t} = 0; + $self -> {__x} = 0; + $self -> {__y} = 0; + $self -> {__t} = 0; +} + +sub inertie { + my ($self) = @_; + my $rate = $self -> mget ('rate'); + $self -> {__vx} *= $rate; + $self -> {__vy} *= $rate; + if ((abs $self -> {__vx} <= 2) and (abs $self -> {__vy} <= 2)) + { + $self -> notify ($self -> {__msg_stopped}); + $self -> {timer_inertie} -> stop(); + return; + } + my $dx = $self -> {__vx}; + my $dy = $self -> {__vy}; + my $target = $self -> mget ('target'); + my $callback = $self -> mget ('inertie_callback'); + $target -> $callback ($dx, $dy); +} + +1; diff --git a/src/MTools/Comp/MMover.pm b/src/MTools/Comp/MMover.pm new file mode 100644 index 0000000..8282943 --- /dev/null +++ b/src/MTools/Comp/MMover.pm @@ -0,0 +1,221 @@ +package MTools::Comp::MMover; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Le composant MMover permet de donner un comportement prehensible a un objet zinc. Les deplacements peuvent etre contraints a un espace defin +# +# Parametres : +# * src : objet source des evenements de deplacement +# * targets : objets deplaces +# * button : bouton de la souris utilise pour genere le deplacement +# Proprietes : +# * x_min, y_min, x_max, y_max : contraintes de l'espace dans lequel peut se deplacer le strip +# * allower : fonction permettre d'appliquer une contrainte plus complexe sur l'objet +# * x, y : position de l'objet modifiee par le MMover +# * targets : objets deplaces +# * -visible : active ou desactive le comportement prehensible + +use strict; +use MTools; +use MTools::MObjet; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class, $src, $targets, $button, %options) = @_; + my $self = {}; + bless $self, $class; + + $self -> recordProperty ('x_min', -10000); + $self -> recordProperty ('y_min', -10000); + $self -> recordProperty ('x_max', 10000); + $self -> recordProperty ('y_max', 10000); + $self -> recordProperty ('-visible', 1); + $self -> recordProperty ('x', 0); + $self -> recordProperty ('y', 0); + $self -> recordProperty ('targets', $targets); + $self -> recordProperty ('allower', undef); + + $self -> mconfigure (%options); + + $self -> recordEvent ('PRESSED'); + $self -> recordEvent ('MOVED'); + $self -> recordEvent ('RELEASED'); + + $button = 1 if ! defined $button; + binding ($src, "<Button-$button>", [\&__pressed, $self, Ev('x'), Ev('y'), Ev('t')]); + binding ($src, "<Button$button-Motion>", [\&__moved, $self, Ev('x'), Ev('y'), Ev('t')]); + binding ($src, "<ButtonRelease-$button>", [\&__released, $self, Ev('x'), Ev('y'), Ev('t')]); + + $self -> {__last_mouse_x} = 0; + $self -> {__last_mouse_y} = 0; + + return $self; +} + +sub setPos { + my ($self, $x, $y) = @_; + my $dx = $x - $self -> mget ('x'); + my $dy = $y - $self -> mget ('y'); + my $tgs = $self -> mget ('targets'); + my @targets; + if (ref ($tgs) eq 'ARRAY') + { + @targets = @{$tgs}; + for (my $i = 0; $i < @targets; $i++) + { + $targets [$i] -> translate ($dx, $dy); + } + } + else + { + $tgs -> translate ($dx, $dy); + } + $self -> mconfigure ('x', $x); + $self -> mconfigure ('y', $y); +} + +sub __pressed { + my ($self, $x, $y, $t) = @_; + if(!$self -> mget('-visible')) {return;} + $self -> {__started} = 1; + $self -> {__last_mouse_x} = $x; + $self -> {__last_mouse_y} = $y; + $self -> notify ('PRESSED', $self -> {__last_mouse_x}, $self -> {__last_mouse_y}, $t); +} + +sub __moved { + my ($self, $x, $y, $t) = @_; + if (!$self -> {__started}) {return;} + if(!$self -> mget('-visible')) {return;} + + my $dx = $x - $self -> {__last_mouse_x}; + my $dy = $y - $self -> {__last_mouse_y}; + + my $x_min = $self -> mget('x_min'); + my $y_min = $self -> mget('y_min'); + my $x_max = $self -> mget('x_max'); + my $y_max = $self -> mget('y_max'); + my $current_x = $self -> mget ('x'); + my $current_y = $self -> mget ('y'); + if($current_x + $dx > $x_max) + { + $x -= $current_x + $dx - $x_max; + $dx -= $current_x + $dx - $x_max; + } + if($current_y + $dy > $y_max) + { + $y -= $current_y + $dy - $y_max; + $dy -= $current_y + $dy - $y_max; + } + if($current_x + $dx < $x_min) + { + + $x -= $current_x + $dx - $x_min; + $dx -= $current_x + $dx - $x_min; + } + if($current_y + $dy < $y_min) + { + $y -= $current_y + $dy - $y_min; + $dy -= $current_y + $dy - $y_min; + } + if( $dx == 0 && $dy == 0 ) + { + return; + } + my $allower = $self -> mget ('allower'); + if ($allower) + { + my ($ddx, $ddy) = executer ($allower, $current_x, $current_y, $dx, $dy); + $x -= $ddx; + $dx -= $ddx; + $y -= $ddy; + $dy -= $ddy; + if( $dx == 0 && $dy == 0 ) + { + return; + } + } + $self -> {__last_mouse_x} = $x; + $self -> {__last_mouse_y} = $y; + $current_x += $dx; + $current_y += $dy; + $self -> notify ('MOVED', $current_x, $current_y, $t); + $self -> setPos ($current_x, $current_y); +} + +sub __released { + my ($self, $x, $y, $t) = @_; + $self -> {__started} = 0; + if(!$self -> mget('-visible')) {return;} + $self -> notify ('RELEASED', $self -> {__last_mouse_x}, $self -> {__last_mouse_y}, $t); +} + +sub translate { + my ($self, $dx, $dy, $t) = @_; + my $x_min = $self -> mget('x_min'); + my $y_min = $self -> mget('y_min'); + my $x_max = $self -> mget('x_max'); + my $y_max = $self -> mget('y_max'); + my $current_x = $self -> mget ('x'); + my $current_y = $self -> mget ('y'); + if($current_x + $dx > $x_max) + { + $dx -= $current_x + $dx - $x_max; + } + if($current_y + $dy > $y_max) + { + $dy -= $current_y + $dy - $y_max; + } + if($current_x + $dx < $x_min) + { + + $dx -= $current_x + $dx - $x_min; + } + if($current_y + $dy < $y_min) + { + $dy -= $current_y + $dy - $y_min; + } + if( $dx == 0 && $dy == 0 ) + { + return; + } + my $allower = $self -> mget ('allower'); + if ($allower) + { + my ($ddx, $ddy) = executer ($allower, $current_x, $current_y, $dx, $dy); + $dx -= $ddx; + $dy -= $ddy; + if( $dx == 0 && $dy == 0 ) + { + return; + } + } + $current_x += $dx; + $current_y += $dy; + $self -> setPos ($current_x, $current_y); + $self -> notify ('MOVED', $current_x, $current_y, $t); +} + +1; diff --git a/src/MTools/Comp/MMultiSelection.pm b/src/MTools/Comp/MMultiSelection.pm new file mode 100644 index 0000000..f124720 --- /dev/null +++ b/src/MTools/Comp/MMultiSelection.pm @@ -0,0 +1,754 @@ +package MTools::Comp::MMultiSelection; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + + +# Le composant MMultiSelection associe deux comportements : +# 1. Selection multiple d'objets repartis eventuellement dans plusieurs plans. +# La selection des objets est geree en les entourant et des-entourant. +# Si un objet est selectionne dans le plan 1, les objets situes dans les plans 2, 3, etc. sont negliges. +# De meme, si un objet est selectionne dans le plan, les objets situes dans les plans 3, 4, etc. sont negliges. +# 2. Deux interactions peuvent-etre initiees depuis la zone de selection. Si l'interaction est demarree +# au-dessus d'un objet, on deplace les objets selectionnes. Si on demarre un interaction au-dessus du fond, +# on demarre une operation de designation de cibles. +# +# Les cibles et les objets selectionnables doivent declarer des proprietes particulieres. Il n'y a ce jour de +# composant definissant ces interfaces, c'est un tord... Qui est volontaire :) +# +# Les source doivent definir les prorpiete +# barycentre_x +# barycentre_y +# La position d'un objet est definie par +# la valeur de barycentre_x plus optionnelement la valeur de la propriete x si celle-ci est definie +# la valeur de barycentre_y plus optionnelement la valeur de la propriete y si celle-ci est definie +# Les cibles doivent emettre les evenements +# DRAGENTER +# DRAGLEAVE +# RELEASEDOVER +# +# NOTA : le deuxieme comportement devrait etre dissocie de l'objet multi-selection... +# Cela reste a faire egalement +# +# Parametres : +# * src : Objet sur lequel est effectue l'interaction de selection +# * dessin : Group parent du dessin de la selection +# * reference a la frame principale +# Proprietes : +# * delay : duree pendant laquelle le dessin de la selection s'estompe et pendant laquelle le demarrage de la +# seconde interaction est possible +# * inertie : coefficient d'inertie dqns le deplacement de la fleche +# Evenements : +# * PRESSED : Notifie lorsque l'on demarre la selection +# * MOVED : Notifie lorsque la selection evolue +# * RELEASED : Notifie lorsque la selection est terminee +# * FLECHEPRESSED : Notifie lorsque une seconde interaction est demarree depuis la zone de selection +# * FLECHEMOVED : Notifie lorsque la seconde interaction evolue +# * FLECHERELEASED : Notifie lorsque la seconde interaction se termine +# * SELECTION_CHANGED : Notifie lorsque le statut d'un objet a change +# Fonctions : +# * addObject : $multi -> addObject ($objet, $plan) +# Ajoute l'objet $objet dans le plan de selection $plan +# * removeObject : $multi -> removeObject ($objet, $plan) +# Supprime l'objet $objet du plan de selection $plan +# * addDropTarget : $multi -> addDropTarget ($target) +# Ajoute la cible $target +# * removeDropTarget : $multi -> removeDropTarget ($target) +# Supprime la cible $target +# * applySelection : $multi -> applySelection ($plan, $fonction, @parametres) +# Applique la fonction $fonction (@parametres) ? tous les objets selectionnes dans le plan $plan +# * applyAll : $multi -> applyAll ($plan, $fonction, @parametres) +# Applique la fonction $fonction (@parametres) ? tous les objets du plan $plan +# * getSelectedPlan : $multi -> getSelectedPlan () +# Retourne l'index du plan selectionne +# * getSelection : $multi -> getSelection ($plan) +# Retourne la liste des objets selectionnes dans le plan $plan si $plan est d?fini +# sinon retourne $multi -> getSelection ($multi -> getSelectedPlan ()) +# + + + +use strict; +use MTools; +use MTools::MObjet; +use Math::Trig; +use MTools::Anim::MOpacity; +use MTools::Comp::MInertie; +use MTools::MGroup; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class, $src, $dessin, $frame, %options) = @_; + my $self = new MTools::MObjet (); + bless $self, $class; + + $self -> recordProperty ('delay', 0); + $self -> recordProperty ('inertie', 0.6); + $self -> recordEvent ('PRESSED'); + $self -> recordEvent ('MOVED'); + $self -> recordEvent ('RELEASED'); + $self -> recordEvent ('FLECHEPRESSED'); + $self -> recordEvent ('FLECHEMOVED'); + $self -> recordEvent ('FLECHERELEASED'); + $self -> recordEvent ('SELECTION_CHANGED'); + $self -> recordEvent ('DESELECT_ALL'); + $self -> mconfigure (%options); + + binding ($src, '<Button-1>', [\&__pressed, $self, Ev('x'), Ev('y'), Ev('t')]); + binding ($src, '<Button1-Motion>', [\&__moved, $self, Ev('x'), Ev('y'), Ev('t')]); + binding ($src, '<ButtonRelease-1>', [\&__released, $self, Ev('x'), Ev('y'), Ev('t')]); + + $self -> {__inertie} = my $inertie = new MTools::Comp::MInertie( + $self, + 'rate' => $self -> mget ('inertie'), + ); + binding ($inertie, 'INERTIE_STOPPED', [$self, \&__fin_moved]); + + my $inertie = new MTools::Comp::MInertie( + $self, + 'rate' => 0.75, + 'msg_pressed' => 'FLECHEPRESSED', + 'msg_moved' => 'FLECHEMOVED', + 'msg_released' => 'FLECHERELEASED', + 'msg_stopped' => 'FLECHEINERTIE_STOPPED', + 'inertie_callback' => '__translate_fleche', + ); + binding ($inertie, 'FLECHEINERTIE_STOPPED', [$self, \&__fin_fleche_moved]); + + $self -> {__frame} = $frame; + $self -> {__drop_targets} = (); + $self -> {__objects} = (); + $self -> {__points} = (); + $self -> {__owns_data} = (); + $self -> {__source} = minstance ($src); + + $self -> {__gp_anime} = my $group = new MTools::MGroup ($dessin); + + push (@{$self -> {__owns_data}}, minstance ($src)); + push (@{$self -> {__owns_data}}, minstance ($group)); + + $self -> {__anim__disparition} = new MTools::Anim::MOpacity ( + duration => 0.8, + targets => $group, + from_opacity => 100, + to_opacity => 0, + ); + + binding ($self -> {__anim__disparition}, 'ANIMATION_END', [$self, \&__clear]); + + $self -> {__curve_bck} = $zinc -> add ('curve', minstance($group), [[0,0],[0,0]], + -linecolor => "#888888;50", + -linewidth => 2, + -smoothrelief => 1, + -priority => 10, + -visible => 1, + -sensitive => 1, + -filled => 0, + ); + $self -> {__curve} = $zinc -> add ('curve', minstance($group), [[0,0],[0,0]], + -linecolor => "#FFFFFF;90", + -linewidth => 1, + -smoothrelief => 1, + -priority => 10, + -visible => 1, + -sensitive => 1, + -fillcolor => "#FFFFFF;10", + -filled => 1, + ); + push (@{$self -> {__owns_data}}, minstance ($self -> {__curve})); + + $self -> {__fleche} = $zinc -> add ('curve', minstance($dessin), [[0,0],[0,0]], + -linecolor => "black", + -linewidth => 2, + -priority => 10, + -visible => 1, + -sensitive => 0, + ); + push (@{$self -> {__owns_data}}, minstance ($self -> {__fleche})); + + $self -> {__ph_fleche} = $zinc -> add ('curve', minstance($dessin), [[0,0],[0,0]], + -linecolor => "black", + -linewidth => 2, + -priority => 10, + -visible => 1, + -sensitive => 0, + ); + push (@{$self -> {__owns_data}}, minstance ($self -> {__ph_fleche})); + + $self -> {__pb_fleche} = $zinc -> add ('curve', minstance($dessin), [[0,0],[0,0]], + -linecolor => "black", + -linewidth => 2, + -priority => 10, + -visible => 1, + -sensitive => 0, + ); + push (@{$self -> {__owns_data}}, minstance ($self -> {__pb_fleche})); + + binding ($self -> {__curve}, '<Button-1>', [\&__fleche_pressed, $self, Ev('x'), Ev('y'), Ev('t')]); + binding ($self -> {__curve}, '<Button1-Motion>', [\&__fleche_moved, $self, Ev('x'), Ev('y'), Ev('t')]); + binding ($self -> {__curve}, '<ButtonRelease-1>', [\&__fleche_released, $self, Ev('x'), Ev('y'), Ev('t')]); + $self -> {__fleche_points} = (); + $self -> {__fleche_started} = 0; + $self -> {__drag_started} = 0; + return $self; +} + +sub __hide_cursor { + my ($self) = @_; + my $frame = $self -> {__frame}; + $frame -> {window} -> Tk::configure ( + -cursor => [ '@'.Tk::findINC('emptycursor.xbm'), + Tk::findINC('emptycursor.mask'), + 'black', 'black' + ] + ); +} + +sub __show_cursor { + my ($self) = @_; + my $frame = $self -> {__frame}; + $frame -> {window} -> Tk::configure ( + -cursor => "", + ); +} + +sub addObject { + my ($self, $object, $plan) = @_; + if (!defined $plan) {$plan = 0;} + if (!$object -> propertyExists ('barycentre_x')) + { + print "MMultiSelection Error property barycentre_x isn't defined in $object\n"; + return; + } + if (!$object -> propertyExists ('barycentre_y')) + { + print "MMultiSelection Error property barycentre_y isn't defined in $object\n"; + return; + } + $object -> {__surround_angle} = 0; + push (@{$self -> {__objects} [$plan]}, $object); +} + +sub removeObject { + my ($self, $target, $plan) = @_; + if (!defined $plan) {$plan = 0;} + for (my $i = @{$self -> {__objects} [$plan]} - 1; $i >= 0; $i --) + { + if (@{$self -> {__objects} [$plan]} [$i] eq $target) + { + splice (@{$self -> {__objects} [$plan]}, $i, 1); + last; + } + } +} + +sub addDropTarget { + my ($self, $target) = @_; + push (@{$self -> {__drop_targets}}, $target); +} + +sub removeDropTarget { + my ($self, $target) = @_; + if ($self -> {__last_notified} == $target) + { + $self -> {__last_notified} = undef; + } + for (my $i = @{$self -> {__drop_targets}} - 1; $i >= 0; $i--) + { + if (@{$self -> {__drop_targets}} [$i] eq $target) + { + splice (@{$self -> {__drop_targets}}, $i, 1); + last; + } + } +} + +sub __clear { + my ($self) = @_; + $self -> {__anim__disparition} -> stop (); + $self -> {__inertie} -> interrupt (); + $self -> {__fleche_started} = 0; + $self -> {__drag_started} = 0; + $self -> {__points} = (); + $self -> {__fleche_points} = (); + $self -> __reset_surrounding (); + $zinc -> coords ($self -> {__ph_fleche}, 0, [[0,0],[0,0]]); + $zinc -> coords ($self -> {__pb_fleche}, 0, [[0,0],[0,0]]); + $zinc -> coords ($self -> {__fleche}, 0, [[0,0],[0,0]]); + $zinc -> coords ($self -> {__curve}, 0, [[0,0],[0,0]]); + $zinc -> coords ($self -> {__curve_bck}, 0, [[0,0],[0,0]]); + $self -> {__gp_anime} -> mconfigure ( + -alpha => 100, + ); +} + +sub __pressed { + my ($self, $x, $y, $t) = @_; + $self -> __clear (); + push (@{$self -> {__points}}, [$x, $y]); + $self -> notify ('PRESSED', $x, $y, $t); + $self -> notify ('DESELECT_ALL'); +} + +sub __released { + my ($self, $x, $y, $t) = @_; + my $pt = $self -> {__points}[@{$self -> {__points}} - 2]; + $self -> notify ('RELEASED', $x - $pt -> [0], $y - $pt -> [1], $t); +} + +sub __fin_moved { + my ($self) = @_; + if (!$self -> {__fleche_started} && !$self -> {__drag_started}) + { + $self -> {__anim__disparition} -> start (); + } +} + +sub __moved { + my ($self, $x, $y, $t) = @_; + push (@{$self -> {__points}}, [$x, $y]); + my @pts = @{$self -> {__points}}; + $zinc -> coords ($self -> {__curve}, 0, \@pts); + $zinc -> coords ($self -> {__curve_bck}, 0, \@pts); + my $pt = $self -> {__points}[@{$self -> {__points}} - 2]; + $self -> notify ('MOVED', $x - $pt -> [0], $y - $pt -> [1], $t); + $self -> __update_all (); +} + +sub translate { + my ($self, $dx, $dy) = @_; + my $pt = $self -> {__points}[@{$self -> {__points}} - 1]; + push (@{$self -> {__points}}, [$pt -> [0] - $dx, $pt -> [1] - $dy]); + my @pts = @{$self -> {__points}}; + $zinc -> coords ($self -> {__curve}, 0, \@pts); + $zinc -> coords ($self -> {__curve_bck}, 0, \@pts); + $self -> __update_all (); +} + +sub __fleche_pressed { + my ($self, $x, $y, $t) = @_; + my @all = $zinc -> find ('overlapping', $x, $y, $x + 1, $y +1); + if ($all [1] == $self -> {__source}) + { + $self -> {__fleche_points} = (); + push (@{$self -> {__fleche_points}}, [$x, $y]); + $self -> {__fleche_started} = 1; + $self -> __hide_cursor (); + $self -> notify ('FLECHEPRESSED', $x, $y, $t); + $self -> __stop_animation (); + } + else + { + $self -> {__drag_started} = 1; + $self -> {__lx} = $x; + $self -> {__ly} = $y; + $self -> notify ('FLECHEPRESSED', $x, $y, $t); + } +} + +sub __stop_animation { + my ($self) = @_; + $self -> {__anim__disparition} -> stop (); + $self -> {__gp_anime} -> mconfigure ( + -alpha => 100, + ); +} + +sub __fleche_released { + my ($self, $x, $y, $t) = @_; + if ($self -> {__fleche_started}) + { + my $pt = $self -> {__fleche_points}[@{$self -> {__fleche_points}} - 1]; + $self -> notify ('FLECHERELEASED', $x - $pt -> [0], $y - $pt -> [1], $t); + } + else + { + $self -> notify ('FLECHERELEASED', $x - $self -> {__lx}, $y - $self -> {__ly}, $t); + $self -> {__lx} = $x; + $self -> {__ly} = $y; + } + +} + +sub __fin_fleche_moved { + my ($self) = @_; + if ($self -> {__fleche_started}) + { + $self -> __clear (); + if (defined $self -> {__last_notified}) + { + $self -> {__last_notified} -> notify ('RELEASEDOVER', $self); + $self -> {__last_notified} = undef; + } + elsif (defined $self -> {__secondary_last_notified}) + { + $self -> {__secondary_last_notified} -> notify ('RELEASEDOVER', $self); + $self -> {__secondary_last_notified} = undef; + } + $self -> __show_cursor (); + } + else + { + } +} + +sub __fleche_moved { + my ($self, $x, $y, $t) = @_; + if ($self -> {__fleche_started}) + { + push (@{$self -> {__fleche_points}}, [$x, $y]); + my @pts = @{$self -> {__fleche_points}}; + $zinc -> coords ($self -> {__fleche}, 0, \@pts); + my $pt = $self -> {__fleche_points}[@{$self -> {__fleche_points}} - 2]; + $self -> notify ('FLECHEMOVED', $x - $pt -> [0], $y - $pt -> [1], $t); + $self -> __update_fleche_moved ($x, $y); + } + else + { + $self -> notify ('FLECHEMOVED', $x - $self -> {__lx}, $y - $self -> {__ly}, $t); + $self -> __translate_selection ($x - $self -> {__lx}, $y - $self -> {__ly}); + $self -> {__lx} = $x; + $self -> {__ly} = $y; + } +} + +sub __translate_fleche { + my ($self, $dx, $dy) = @_; + if ($self -> {__fleche_started}) + { + my $pt = $self -> {__fleche_points}[@{$self -> {__fleche_points}} - 1]; + push (@{$self -> {__fleche_points}}, [$pt -> [0] - $dx, $pt -> [1] - $dy]); + my @pts = @{$self -> {__fleche_points}}; + $zinc -> coords ($self -> {__fleche}, 0, \@pts); + $self -> __update_fleche_moved ($pt -> [0] - $dx, $pt -> [1] - $dy); + } + else + { + $self -> __translate_selection (-$dx, -$dy); + } +} + +sub __translate_selection { + my ($self, $dx, $dy) = @_; + my @oldy = $self -> applySelection (0, 'mget', 'y'); + my @oldx = $self -> applySelection (0, 'mget', 'x'); + my @selection = $self -> getSelection (); + for (my $i = 0; $i < @selection; $i ++) + { + my $x = $selection [$i] -> mget ('x'); + my $pdx = $dx - ($x - $oldx [$i]); + my $y = $selection [$i] -> mget ('y'); + my $pdy = $dy - ($y - $oldy [$i]); + $selection [$i] -> translate ($pdx, $pdy); + } +} + +sub __update_fleche_moved { + my ($self, $x, $y) = @_; + my $pt; + if (@{$self -> {__fleche_points}} > 2) + { + $pt = $self -> {__fleche_points}[@{$self -> {__fleche_points}} - 3]; + } + else + { + $pt = $self -> {__fleche_points}[@{$self -> {__fleche_points}} - 2]; + } + my $xa = $x - $pt -> [0]; + my $ya = $y - $pt -> [1]; + if ($xa + $ya == 0) {return;} + + my $norme = sqrt ($xa * $xa + $ya * $ya); + $xa = $xa * 8 / $norme; + $ya = $ya * 8 / $norme; + + if ( $xa != 0) + { + my $yb = sqrt ((10 * 10 - $xa * $xa - $ya * $ya) / (1 + $ya * $ya / ($xa * $xa))); + my $xb = -$yb * $ya / $xa; + $zinc -> coords ($self -> {__ph_fleche}, 0, [[$x, $y], [$x + $xb - $xa, $y + $yb - $ya]]); + $zinc -> coords ($self -> {__pb_fleche}, 0, [[$x, $y], [$x - $xb - $xa, $y - $yb - $ya]]); + } + else + { + my $xb = sqrt (10 * 10 - $ya * $ya); + my $yb = 0; + $zinc -> coords ($self -> {__ph_fleche}, 0, [[$x, $y], [$x + $xb - $xa, $y + $yb - $ya]]); + $zinc -> coords ($self -> {__pb_fleche}, 0, [[$x, $y], [$x - $xb - $xa, $y - $yb - $ya]]); + } + my @all = $zinc -> find ('overlapping', $x, $y, $x + 1, $y +1); + + if (defined $self -> {__drop_targets}) + { + my @selected; + my @owns = @{$self -> {__owns_data}}; + for (my $i = 0; $i < @all; $i++) + { + my $find = 0; + for (my $j = 0; $j < @owns; $j ++) + { + if ($all [$i] == $owns [$j]) + { + $find = 1; + } + } + if (!$find) + { + push (@selected, $all [$i]); + } + } + if (defined @selected) + { + my @targets = @{$self -> {__drop_targets}}; + my $last_notified = $self -> {__last_notified}; + $self -> {__last_notified} = undef; + for (my $i = 0; $i < @targets; $i ++) + { + if (minstance ($targets [$i]) == $selected [0] || minstance ($targets [$i]) == $selected [1]) + { + if ($last_notified != $targets [$i]) + { + $targets [$i] -> notify ('DRAGENTER'); + } + $self -> {__last_notified} = $targets [$i]; + } + else + { + if ($last_notified == $targets [$i]) + { + $targets [$i] -> notify ('DRAGLEAVE'); + } + } + } + } + } +} + +sub getObjectBellow { + my ($self, $x, $y, @objects) = @_; + my @all = $zinc -> find ('overlapping', $x, $y, $x + 1, $y +1); + my @owns = @{$self -> {__owns_data}}; + my @below; + for (my $i = 0; $i < @all; $i++) + { + my $find = 0; + for (my $j = 0; $j < @owns; $j ++) + { + if ($all [$i] == $owns [$j]) + { + $find = 1; + } + } + if (!$find) + { + push (@below, $all [$i]); + } + } + my $nb = @below; + my @elements; + for (my $i = 0; $i < $nb; $i ++) + { + my @fils = $zinc -> find ('ancestors', $below [$i]); + push (@elements, '-'.$below [$i], @fils); + } + my $main; + for (my $j = 0; $j < @elements; $j ++) + { + if (index($elements [$j], '-') == 0) + { + $elements [$j] = substr ($elements [$j], 1, length ($elements [$j])); + $main = $elements [$j]; + } + for (my $i = 0; $i < @objects; $i++) + { + if (minstance ($objects [$i]) == $elements [$j]) + { + return ($objects [$i], $main); + } + } + } + return undef; +} + +sub __update_all { + my ($self) = @_; + my $selection_changed = 0; + $self -> {_selected} = 0; + $self -> {__selected_plan} = -1; + if (defined $self -> {__objects}) + { + my @object_plan = @{$self -> {__objects}}; + for (my $j = 0; $j < @object_plan; $j ++) + { + if (defined $self -> {__objects} [$j]) + { + my @items = @{$self -> {__objects} [$j]}; + for (my $i = 0; $i < @items; $i++) + { + $selection_changed = $selection_changed || $self -> __update_surrouding ($items [$i], ($self -> {__selected_plan} != -1), $self -> {__points}); + } + if ($self -> {_selected} && $self -> {__selected_plan} == -1) + { + $self -> {__selected_plan} = $j; + } + } + } + } + if ($selection_changed) + { + $self -> notify ('SELECTION_CHANGED', $self) + } +} + +sub getSelectedPlan { + my ($self) = @_; + return $self -> {__selected_plan}; +} + +sub __update_surrouding { + my ($self, $item, $force_non_sel, $coords) = @_; + my $center_x = $item -> mget ('barycentre_x'); + if ($item -> propertyExists ('x')) + { + $center_x += $item -> mget ('x'); + } + my $center_y = $item -> mget ('barycentre_y'); + if ($item -> propertyExists ('y')) + { + $center_y += $item -> mget ('y'); + } + my ($tmp,$ref); + $ref = -$self -> __angle($coords, @{$coords} - 1, $center_x, $center_y, 0); + $tmp = -$self -> __angle($coords, @{$coords} - 2, $center_x, $center_y, $ref); + $item -> {__surround_angle} += $tmp; + $tmp = $self -> __angle($coords, 0, $center_x, $center_y, $ref); + if ($force_non_sel) + { + if ($item -> isSelected ()) + { + $item -> setSelected (0); + } + } + else + { + if (abs ($item -> {__surround_angle} + $tmp) > 2) + { + $self -> {_selected} ++; + if (!$item -> isSelected ()) + { + $item -> setSelected (1); + return 1; + } + } + else + { + if ($item -> isSelected ()) + { + $item -> setSelected (0); + return 1; + } + } + } + return 0; +} + +sub __angle { + my ($self, $coords, $index, $center_x, $center_y, $ref) = @_; + my $angle; + my $tab = $coords -> [$index]; + $angle = atan2 ($tab -> [1] - $center_y, $tab -> [0] - $center_x) + $ref; + $angle -= 2*pi if ($angle > pi); + $angle += 2*pi if ($angle < - pi); + return $angle; +} + +sub __reset_surrounding { + my ($self) = @_; + if (defined $self -> {__objects}) + { + my @object_plan = @{$self -> {__objects}}; + for (my $j = 0; $j < @object_plan; $j ++) + { + if (defined $self -> {__objects} [$j]) + { + my @items = @{$self -> {__objects} [$j]}; + for (my $i = 0; $i < @items; $i++) + { + $items [$i] -> {__surround_angle} = 0; + } + } + } + } +} + +sub applySelection { + my ($self, $plan, $fct, @args) = @_; + my @retour; + if (defined $self -> {__objects} [$plan]) + { + my @items = @{$self -> {__objects} [$plan]}; + for (my $i = 0; $i < @items; $i++) + { + if ($items [$i] -> isSelected ()) + { + push (@retour, $items [$i] -> $fct (@args)); + } + } + } + return @retour; +} + +sub applyAll { + my ($self, $plan, $fct, @args) = @_; + my @retour; + if (defined $self -> {__objects} [$plan]) + { + my @items = @{$self -> {__objects} [$plan]}; + for (my $i = 0; $i < @items; $i++) + { + push (@retour, $items [$i] -> $fct (@args)); + } + } + return @retour; +} + +sub getSelection { + my ($self, $plan) = @_; + if (!defined $plan) {$plan = $self -> getSelectedPlan ();} + my @selection; + if (defined $self -> {__objects} [$plan]) + { + my @items = @{$self -> {__objects} [$plan]}; + for (my $i = 0; $i < @items; $i++) + { + if ($items [$i] -> isSelected ()) + { + push (@selection, $items [$i]); + } + } + } + return @selection; +} + +1; diff --git a/src/MTools/Comp/MReconizer.pm b/src/MTools/Comp/MReconizer.pm new file mode 100644 index 0000000..9605eb9 --- /dev/null +++ b/src/MTools/Comp/MReconizer.pm @@ -0,0 +1,145 @@ +package MTools::Comp::MReconizer; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Le composant permet de rendre un objet zinc sensible a la reco de geste +# +# Parametres : +# * src : objet rendu sensible et donc source des evenements +# * button : bouton de la souris utilise pour genere la reco de geste +# * %options : table de hash permettant la configuration initiale des proprietes +# Proprietes : +# * animation_duration : duree de l'animation de disparition du feedback +# * color : couleur du feedback +# * callback : callback appelee sur reconnaissance +# Evenements : +# * START_GESTURE_RECO : evenement survenant lors du demarrage d'un geste +# * RECONIZED : evenement survenant lorsque un geste est reconnu + +use strict; +use MTools; +use MTools::MObjet; +use Recogestures; + +use MTools::Anim::MOpacity; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class, $src, $button, %options) = @_; + my $self = new MTools::MObjet (); + bless $self, $class; + + $button = 1 if ! defined $button; + + $self -> recordEvent ('RECONIZED'); + $self -> recordEvent ('START_GESTURE_RECO'); + $self -> recordProperty ('animation_duration', 0.5); + $self -> recordProperty ('color', 'blue'); + $self -> recordProperty ('callback', undef); + + $self -> mconfigure (%options); + + binding ($src, "<Button-$button>", [\&__pressed, $self, Ev('x'), Ev('y')]); + binding ($src, "<Button$button-Motion>", [\&__moved, $self, Ev('x'), Ev('y')]); + binding ($src, "<ButtonRelease-$button>", [\&__released, $self, Ev('x'), Ev('y')]); + + $self -> binding ('RECONIZED', sub { + my $methode = $self -> mget ('callback'); + if (defined $methode) + { + executer ($methode, @_); + } + }); + $self -> {__dessin} = undef; + + $self -> {__dessin} = my $dessin = new MTools::MGroup (1); + $self -> {__fleche} = $zinc -> add ('curve', minstance($dessin), [[0,0],[0,0]], + -linecolor => 'blue', + -linewidth => 2, + -priority => 10, + -visible => 1, + -sensitive => 0, + ); + + $self -> {__anim__disparition} = new MTools::Anim::MOpacity ( + duration => 0.8, + targets => $dessin, + from_opacity => 100, + to_opacity => 0, + ); + binding ($self -> {__anim__disparition}, 'ANIMATION_END', [$self, \&__clear]); + plink ([$self, 'color'], [$self -> {__fleche}, '-linecolor']); + plink ([$self, 'animation_duration'], [$self -> {__anim__disparition}, 'duration']); + + return $self; +} + +sub __clear () { + my ($self, $x, $y) = @_; + $self -> {__points} = (); + $zinc -> coords ($self -> {__fleche}, 0, [[0,0],[0,0]]); + $self -> {__dessin} -> mconfigure ( + -alpha => 100, + ); +} + +sub __pressed { + my ($self, $x, $y) = @_; + ($x, $y) = $zinc -> transform('device', minstance ($self -> {__dessin}), [$x, $y]); + if (defined $self -> {__dessin}) + { + push (@{$self -> {__points}}, [$x, $y]); + } + $self -> notify ('START_GESTURE_RECO', $x, $y); +} + +sub __moved { + my ($self, $x, $y) = @_; + ($x, $y) = $zinc -> transform('device', minstance ($self -> {__dessin}), [$x, $y]); + push (@{$self -> {trace}},$x,$y); + + if (defined $self -> {__dessin}) + { + push (@{$self -> {__points}}, [$x, $y]); + my @pts = @{$self -> {__points}}; + $zinc -> coords ($self -> {__fleche}, 0, \@pts); + } +} + +sub __released { + my ($self, $x, $y) = @_; + + my ($gesture,$explanation) = AnalyzeGesture(@{$self -> {trace}}); + $self -> {trace} = (); + $self -> notify ('RECONIZED', $gesture, $explanation); + + if (defined $self -> {__dessin}) + { + $self -> {__anim__disparition} -> start (); + } +} + +1; + diff --git a/src/MTools/Comp/MTremor.pm b/src/MTools/Comp/MTremor.pm new file mode 100644 index 0000000..25b5023 --- /dev/null +++ b/src/MTools/Comp/MTremor.pm @@ -0,0 +1,121 @@ +package MTools::Comp::MTremor; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Le composant permet d'ajouter un comportement de tremblement ? un objet cible +# +# Parametres : +# * target : objet cible du tremblement +# * %options : table de hash permettant la configuration initiale des proprietes +# Propriete : +# * timeout : periode / 2 du tremblement +# * target : cible +# * amplitude_x, amplitude_y : amplitude du deplacement +# * -visible : visibilite versus activation du comportement + +use strict; +use MTools; +#use MTools::MSwitch; +use MTools::MTimer; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class, $target, %options) = @_; + + $self -> {__timer} = my $timer = new MTools::MTimer (200, 1, \&tremble); + my $self = new MTools::MObjet (); +# $self -> {__sw} = new MTools::MSwitch ( +# $parent, +# tremble => [$timer], +# fixe => [], +# ); +# $self -> {__sw} -> mconfigure (state => 'fixe'); + $timer -> mconfigure ( callback => [$self, '__tremble']); + bless $self, $class; + + $self -> recordProperty ('timeout', 200); + $self -> recordProperty ('target', $target); + $self -> recordProperty ('amplitude_x', 2); + $self -> recordProperty ('amplitude_y', 2); + $self -> recordProperty ('-visible', 0); + $self -> plisten ('-visible', sub { + my ($src, $key, $val) = @_; + if ($val == 0) + { + $self -> __stop (); + } + else + { + $self -> __start (); + } + }); + + $self -> mconfigure (%options); + + plink ([$self, 'timeout'], [$timer, 'timeout']); + $self -> {__timer} = $timer; + $self -> {__x} = 0; + $self -> {__y} = 0; + $self -> {__started} = 0; + return $self; +} + +sub __tremble { + my ($self) = @_; + my $target = $self -> mget ('target'); + my $dx = -2 * $self -> {__x}; + my $dy = -2 * $self -> {__y}; + $self -> {__x} = -$self -> {__x}; + $self -> {__y} = -$self -> {__y}; + $target -> translate ($dx, $dy); +} + +sub __start { + my ($self) = @_; + if ($self -> {__started}) {return;} + $self -> {__started} = 1; + my $target = $self -> mget ('target'); + my $amplitudex = $self -> mget ('amplitude_x'); + my $amplitudey = $self -> mget ('amplitude_y'); + $self -> {__x} = $amplitudex; + $self -> {__y} = $amplitudey; + $target -> translate ($amplitudex, $amplitudey); +# $self -> {__sw} -> mconfigure ('state' => 'tremble'); + $self -> {__timer} -> start (); +} + +sub __stop { + my ($self) = @_; + if (!$self -> {__started}) {return;} + $self -> {__started} = 0; + my $target = $self -> mget ('target'); + $target -> translate (-$self -> {__x}, -$self -> {__y}); + $self -> {__x} = 0; + $self -> {__y} = 0; + $self -> {__sw} -> mconfigure ('state' => 'fixe'); + $self -> {__timer} -> stop (); +} + +1; diff --git a/src/MTools/Comp/MWritable.pm b/src/MTools/Comp/MWritable.pm new file mode 100644 index 0000000..8a2a2d5 --- /dev/null +++ b/src/MTools/Comp/MWritable.pm @@ -0,0 +1,276 @@ +package MTools::Comp::MWritable; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Le composant MWritable permet d'associer un comportement scritptible a un objet zinc +# Le composant peut alors etre ecrit et l'ecriture effacee +# +# Parametres : +# * parent : objet parent des curves qui vont etre dessinee au cours de l'ecriture +# * src : objet source des evenements qui vont generer le dessin +# * button : bouton de la souris utilise pour genere la reco de geste +# * %options : table de hash permettant la configuration initiale des proprietes et de definir un objet clip ($options {clip}) +# l'objet clip permet de contenir l'ecriture libre dans une zone. +# Proprietes : +# * color : couleur d'ecriture +# * writing_mode : ('write' ou 'erase') permet de specifier le resultat de l'interaction sur l'objet source (ecriture ou effacement) +# Evenements : +# * BEGIN_WRITE : Message emis lors d'un debut d'ecriture +# * WRITE : Message emis lors de l'ecriture +# * END_WRITE :Message emis lors d'une fin d'ecriture +# * ERASE : Message emis lors de l'effacement +# Fonctions : +# * begin_write : force un debut d'ecriture +# * write : force l'ecriture +# * end_write : force une fin d'ecriture +# * erase : force un effacement + + +use strict; +use MTools; +use MTools::MObjet; +use MTools::GUI::MClip; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MGroup/; +} + +use Tk; + +sub new { + my ($class, $parent, $src, $button, %options) = @_; + my $self = new MTools::MGroup ($parent); + bless $self, $class; + if (defined $options {clip}) + { + $self -> {__clip} = new MTools::GUI::MClip ( + $self, + $options {clip}, + ); + } + delete $options {clip}; + $self -> mconfigure (-atomic => 1); + $self -> recordProperty ('color', '#000000'); + $self -> recordProperty ('writing_mode', 'write'); + $self -> recordEvent ('BEGIN_WRITE'); + $self -> recordEvent ('END_WRITE'); + $self -> recordEvent ('WRITE'); + $self -> recordEvent ('ERASE'); + $button = 1 if ! defined $button; + binding ($src, "<Button-$button>", [\&__beginWrite, $self, Ev('x'), Ev('y'), Ev('t')]); + binding ($src, "<Button$button-Motion>", [\&__writing, $self, Ev('x'), Ev('y'), Ev('t')]); + binding ($src, "<ButtonRelease-$button>", [\&__endWrite, $self, Ev('x'), Ev('y'), Ev('t')]); + binding ($self, "<Button-$button>", [\&__beginWrite, $self, Ev('x'), Ev('y'), Ev('t')]); + binding ($self, "<Button$button-Motion>", [\&__writing, $self, Ev('x'), Ev('y'), Ev('t')]); + binding ($self, "<ButtonRelease-$button>", [\&__endWrite, $self, Ev('x'), Ev('y'), Ev('t')]); + $self -> {__curves} = (); + $self -> {__points} = (); + $self -> {__current_curves} = (); + $self -> {__tmp_curves} = new MTools::MGroup ($self); + return $self; +} + +sub __beginWrite { + my ($self, $x, $y) = @_; + ($x, $y) = $zinc -> transform ('device', minstance ($self), [$x, $y]); + $self -> beginWrite ($x, $y); + $self -> notify ('BEGIN_WRITE', $x, $y) +} + +sub beginWrite { + my ($self, $x, $y) = @_; + push (@{$self -> {__old_coords}}, ($x, $y)); +} + +sub __endWrite { + my ($self, $x, $y) = @_; + if ($self -> mget ('writing_mode') eq 'write') + { + ($x, $y) = $zinc -> transform ('device', minstance ($self), [$x, $y]); + $self -> writing ($x, $y); + $self -> notify ('WRITE', $x, $y); + $self -> notify ('END_WRITE'); + $self -> endWrite (); + } + else + { + $self -> {__old_coords} = (); + } +} + +sub endWrite { + my ($self) = @_; + if (defined $self -> {__points} && @{$self -> {__points}}) + { + my @points = @{$self -> {__points}}; + push (@{$self -> {__curves}}, $zinc -> add ( + 'curve', + minstance ($self), + [@points], + -linecolor => $self -> mget ('color'), + -linewidth => 1, + -priority => 2, + -visible => 1, + -sensitive => 0 + ) + ); + $self -> {__points} = (); + $self -> {__tmp_curves} -> mdelete (); + $self -> {__tmp_curves} = new MTools::MGroup ($self); + } + $self -> {__old_coords} = (); +} + +sub __writing { + my ($self, $x, $y) = @_; + if ($self -> mget ('writing_mode') eq 'write') + { + ($x, $y) = $zinc -> transform ('device', minstance ($self), [$x, $y]); + $self -> writing ($x, $y); + $self -> notify ('WRITE', $x, $y) + } + else + { + erase ($self, $x, $y); + } +} + + +sub writing { + my ($self, $x, $y) = @_; + $self -> write ($x, $y); +} + +sub write { + my ($self, $x, $y) = @_; + my @coords; + push (@{$self -> {__old_coords}}, ($x, $y)); + my $list_size = @{$self -> {__old_coords}}; + if ($list_size >= 6) + { + my $x1 = $self -> {__old_coords} -> [$list_size - 6]; + my $y1 = $self -> {__old_coords} -> [$list_size - 5]; + my $x2 = $self -> {__old_coords} -> [$list_size - 4]; + my $y2 = $self -> {__old_coords} -> [$list_size - 3]; + my $x3 = $self -> {__old_coords} -> [$list_size - 2]; + my $y3 = $self -> {__old_coords} -> [$list_size - 1]; + my $cx2 = ($x1 - $x3) * 0.2 + $x2; + my $cy2 = ($y1 - $y3) * 0.2 + $y2; + if ($list_size == 6) + { + @coords = ([$x1,$y1],[$cx2,$cy2,'c'],[$x2,$y2]); + } + else + { + my $cx1 = ($x2 - $self -> {__old_coords} -> [$list_size - 8]) * 0.2 + $x1; + my $cy1 = ($y2 - $self -> {__old_coords} -> [$list_size - 7]) * 0.2 + $y1; + @coords = ([$x1, $y1], [$cx1, $cy1, 'c'], [$cx2, $cy2, 'c'], [$x2, $y2]); + } + push (@{$self -> {__points}}, @coords); + push (@{$self -> {__current_curves}}, $zinc -> add ( + 'curve', + minstance ($self -> {__tmp_curves}), + [@coords], + -linecolor => $self -> mget ('color'), + -linewidth => 1, + -priority => 2, + -visible => 1, + -sensitive => 0 + ) + ); + } +} + +my $k = 5; +sub erase { + my ($self, $x, $y) = @_; + ($x, $y) = $zinc -> transform ('device', minstance ($self), [$x, $y]); + if (defined $self -> {__curves}) + { + my @curves = @{$self -> {__curves}}; + for (my $i = @curves - 1; $i >= 0 ; $i --) + { + my @points = $zinc -> coords ($curves [$i], 0); + for (my $j = 0; $j < @points - 1; $j ++) + { + my $pt1 = $points [$j]; + my $pt2 = $points [$j + 1]; + + if ($pt1 -> [0] == $pt2 -> [0]) + { + if (in ($y, $pt1 -> [1], $pt2 -> [1]) && ( abs ($pt1 -> [0] - $x) <= $k)) + { + $self -> __deleteCurve ($i); + last; + } + } + else + { + my $a = ($pt1 -> [1] - $pt2 -> [1]) / ($pt1 -> [0] - $pt2 -> [0]); + my $b = $pt2 -> [1] - $a * $pt2 -> [0]; + my $ar = ($a ** 2 + 1); + my $br = (2 * $a * ($b - $y) - 2 * $x); + my $cr = ($x ** 2 + ($b - $y) ** 2 - $k ** 2); + my $d = $br ** 2 - 4 * $ar * $cr; + if ($d >= 0) + { + if (mdist ($pt1 -> [0], $pt1 -> [1], $x ,$y) || mdist ($pt2 -> [0], $pt2 -> [1], $x ,$y)) + { + $self -> __deleteCurve ($i); + last; + } + my $x1 = (-$br + sqrt ($d)) / (2 * $ar); + my $x2 = (-$br - sqrt ($d)) / (2 * $ar); + if (in ($x1, $pt1 -> [0], $pt2 -> [0]) || in ($x2, $pt1 -> [0], $pt2 -> [0])) + { + $self -> __deleteCurve ($i); + last; + } + } + } + } + } + } +} + +sub __deleteCurve { + my ($self, $index) = @_; + $self -> notify ('ERASE', $index); + $self -> deleteCurve ($index); +} + +sub deleteCurve { + my ($self, $index) = @_; + $self -> {__old_coords} = (); + mdelete ($self -> {__curves} [$index]); + splice (@{$self -> {__curves}}, $index, 1); +} + +sub in { + my ($x, $x0, $x1) = @_; + return (($x0 <= $x) && ($x <= $x1) || ($x1 <= $x) && ($x <= $x0)); +} + +sub mdist { + my ($x1, $y1, $x2, $y2) = @_; + return (($x1 - $x2) ** 2 + ($y1 - $y2) ** 2 <= ($k) ** 2); +} + +1; diff --git a/src/MTools/GUI/MAntiRecouvrementGroup.pm b/src/MTools/GUI/MAntiRecouvrementGroup.pm new file mode 100644 index 0000000..4e8dbc7 --- /dev/null +++ b/src/MTools/GUI/MAntiRecouvrementGroup.pm @@ -0,0 +1,191 @@ +package MTools::GUI::MAntiRecouvrementGroup; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + + +# Les objets heritant de MAntiRecouvrementGroup peuvent etre geres par un objet MAntiRecouvrement et ainsi pris en charge +# par un algorithme d'anti-recouvrement. +# +# parametres : +# * $parent : parent de l'objet... +# * %options : table de hash permettant d'initialiser les proprietes +# Les ?v?nements : +# * TRANSLATED : notifie lorsque l'objet est translate... +# attibuts : +# followed_by : MAntiRecouvrementGroup permet aux objets contenus dans ce tableau de suivre ses deplacements +# (permet un chainage des objets) +# Les propietes : +# * xmin, ymin, xmax, ymax : definissent les caract?risiques de l'espace dans lequel l'objet est contraint. +# * height, width : definissent la base rectangulaire de l'objet +# * auto_sizing : si width ou height ne sont pas pass?s en param?tre, les caracteristiques +# sont auto-determinees en fonction de la bbox de l'objet. On peut bien evidemment choisir cette definition automatique, cependant +# attention, la bbox de l'objet ne correspond par toujours a la bbox visible de l'objet. +# * x, y : determinent la position de l'objet et sont mis a jour automatiquement au cours des deplacement de l'objet. +# * anchors : permet d'active ou ne le suivi des objets contenus dans 'followed_by' +# Les fonctions : +# * update_bbox : permet de demander une remise ? jour du calcul automatique des dimensions de l'objet (util uniquement si auto_sizing == 1) + +use MTools; + +use vars qw /@ISA/; + + +use MTools::MGroup; +require Exporter; + +BEGIN +{ + @ISA = qw /MTools::MGroup Exporter/; + @EXPORT = qw / translate scale rotate /; +} + +use strict; +use Tk; + +sub new { + my ($class, $parent, %options) = @_; + my $self = new MTools::MGroup ($parent); + bless $self, $class; + + $self -> recordEvent ('TRANSLATED'); + $self -> recordProperty ('auto_sizing', (!defined $options{width}) || (!defined $options{height})); + $self -> recordProperty ('height', 0); + $self -> recordProperty ('width', 0); + $self -> recordProperty ('x', 0); + $self -> recordProperty ('y', 0); + $self -> recordProperty ('xmin', 0); + $self -> recordProperty ('ymin', 0); + $self -> recordProperty ('xmax', 1500); + $self -> recordProperty ('ymax', 1500); + $self -> recordProperty ('anchors', 1); + + $self -> recordEvent ('__HANDLE_MOVING'); + $self -> recordEvent ('__PUSH_BACK'); + $self -> recordEvent ('__ENQUEUE_MOVING'); + + $self -> mconfigure (%options); + return $self; +} + +sub translate { + my ($self, $delta_x, $delta_y) = @_; + if ($self -> {__added}) + { + if ((abs ($delta_x) >= $self -> mget ('width') / 2) or (abs ($delta_y) >= $self -> mget ('height') / 2)) + { + my ($mini_dx, $mini_dy) = (int ($delta_x / 2), int ($delta_y / 2)); + $self -> translate ($mini_dx, $mini_dy); + $self -> translate ($delta_x - $mini_dx, $delta_y - $mini_dy); + } + else + { + $self -> __try_move ($delta_x, $delta_y, []); + $self -> notify ('__HANDLE_MOVING'); + } + } + else + { + $self -> __update_xy ($delta_x, $delta_y); + } +} + +sub __search { + my ($val, @tab) = @_; + my $result = 0; + if (($#tab != -1) and (defined $val)) + { + foreach (@tab) + { + if (($_ eq $val) or ($_ =~ m/$val/)) + { + $result = 1; + last; + } + } + } + return $result; +} + +sub __try_move { + my ($self, $delta_x, $delta_y, $path) = @_; + return if __search ($self, @{$path}); + push (@{$path}, $self); + $self -> __update_xy ($delta_x, $delta_y); + + my $label_coords_x = $self -> mget ('x'); + my $label_coords_y = $self -> mget ('y'); + my $x_min = $self -> mget ('xmin'); + my $x_max = $self -> mget ('xmax'); + my $y_min = $self -> mget ('ymin'); + my $y_max = $self -> mget ('ymax'); + + my ($push_x, $push_y) = (0, 0); + $push_x = $x_min - $label_coords_x if $label_coords_x < $x_min; + $push_x = $x_max - $label_coords_x if $label_coords_x > $x_max; + $push_y = $y_min - $label_coords_y if $label_coords_y < $y_min; + $push_y = $y_max - $label_coords_y if $label_coords_y > $y_max; + $self -> notify ('__PUSH_BACK', $self, $push_x, $push_y, $path) if (($push_x != 0) or ($push_y != 0)); + + if ($self -> mget ('anchors')) + { + if (defined $self -> {followed_by}) + { + foreach (@{$self -> {followed_by}}) + { + $_ -> __try_move($delta_x + $push_x, $delta_y + $push_y, $path); + } + } + } + + my @other_path = @{$path}; + $self -> notify ('__ENQUEUE_MOVING', $self, $delta_x + $push_x, $delta_y + $push_y, [@other_path]); + pop @{$path}; +} + +sub __update_xy { + my ($self, $delta_x, $delta_y) = @_; + MTools::translate ($self, $delta_x, $delta_y); + $self -> mconfigure ('x' => $self -> mget ('x') + $delta_x); + $self -> mconfigure ('y' => $self -> mget ('y') + $delta_y); + $self -> notify ('TRANSLATED', $delta_x, $delta_y); +} + +sub scale { + my ($self, @params) = @_; + MTools::scale ($self, @params); + $self -> update_bbox (); + $self -> translate (0, 0); +} + +sub rotate { + my ($self, @params) = @_; + MTools::rotate ($self, @params); + $self -> update_bbox (); + $self -> translate (0, 0); +} + +sub update_bbox { + my ($self) = @_; + if ($self -> mget ('auto_sizing')) + { + my @rect = $self -> bbox (); + $self -> mconfigure (width => $rect [2] - $rect [0]); + $self -> mconfigure (height => $rect [3] - $rect [1]); + } +} + +1; diff --git a/src/MTools/GUI/MCircle.pm b/src/MTools/GUI/MCircle.pm new file mode 100644 index 0000000..35463ef --- /dev/null +++ b/src/MTools/GUI/MCircle.pm @@ -0,0 +1,51 @@ +package MTools::GUI::MCircle; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Encapsule la creation d'un cercle +# Parametres : +# * parent : pere de l'objet. +# * x, y : coordonnees du centre du cercle +# * r : rayon du cercle +# * %options : table de hash pass?e en parametre de la cr?ation de l'objet zinc arc + +use strict; + +use MTools; +use MTools::MObjet; +use vars qw / @ISA /; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +sub new { + my ($class, $parent, $x, $y, $r, %options) = @_; + my $self = {}; + bless $self, $class; + $self -> {instance} = $zinc -> add('arc', + ref ($parent) eq '' ? $parent : $parent -> {instance}, + [$x - $r, $y - $r, $x + $r, $y + $r], + -pieslice => 0, + -priority => 10, + %options, + ); + return $self; +} + +1; diff --git a/src/MTools/GUI/MClip.pm b/src/MTools/GUI/MClip.pm new file mode 100644 index 0000000..248e395 --- /dev/null +++ b/src/MTools/GUI/MClip.pm @@ -0,0 +1,90 @@ +package MTools::GUI::MClip; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Encapsule le clipping d'un objet +# Parametres : +# * clipped : group zinc clippe +# * path : description de l'objet clippant +# - soit une descrition sous forme [_type, _coords] creant un objet zinc de type _type et de coordonnees _coords +# - soit un objet existant qui prendra pour p?re le group $clipped. + +use strict; + +use MTools; +use MTools::MObjet; +use vars qw / @ISA /; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +sub new { + my ($class, $clipped, $path, $debug) = @_; + my $self = {}; + bless $self, $class; + + if (!defined $debug) {$debug = 0} + + my $clip = $path; + if(ref ($path) eq 'ARRAY') + { + my $type = shift @{$path}; + $clip = $zinc -> add ($type, $clipped -> {instance}, $path, + -filled => 1, + -priority => 10, + -linewidth => 0, + -fillcolor => "#000000", + -visible => $debug, + -sensitive => 0, + ); + } + elsif(ref ($path) eq '') + { + $clip = minstance ($clip, $clipped); + MTools::chggroup ($clip, $clipped); + MTools::mconfigure ($clip, -visible => $debug, -sensitive => 0); + } + else + { + MTools::chggroup ($clip, $clipped); + MTools::mconfigure (-visible => $debug, -sensitive => 0); + $clip = minstance ($clip); + } + $self -> {__clipped} = $clipped; + $self -> {__clip} = $clip; + mconfigure ($clipped, -clip => $clip); + return $self; +} + +sub translate { + my ($self, @args) = @_; + MTools::translate ($self -> {__clip}, @args); +} + +sub scale { + my ($self, @args) = @_; + MTools::scale ($self -> {__clip}, @args); +} + +sub rotate { + my ($self, @args) = @_; + MTools::rotate ($self -> {__clip}, @args); +} + +1; diff --git a/src/MTools/GUI/MCurve.pm b/src/MTools/GUI/MCurve.pm new file mode 100644 index 0000000..3458e49 --- /dev/null +++ b/src/MTools/GUI/MCurve.pm @@ -0,0 +1,54 @@ +package MTools::GUI::MCurve; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Encapsule la creation d'une curve +# Parametres : +# * parent : pere de l'objet. +# * coords : coordonnees de la curve (cf. format zinc) +# * %options : table de hash pass?e en param?tre de la creation de l'objet zinc curve + + +use strict; + +use MTools; +use MTools::MObjet; +use vars qw / @ISA /; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +sub new { + my ($class, $parent, $coords, %options) = @_; + my $self = {}; + bless $self, $class; + $self -> {instance} = $zinc -> add('curve', + ref ($parent) eq '' ? $parent : $parent -> {instance}, + $coords, + -priority => 10, + -visible => 1, + -filled => 0, + -linecolor => 'black', + -linewidth => 1, + %options, + ); + return $self; +} + +1; diff --git a/src/MTools/GUI/MImage.pm b/src/MTools/GUI/MImage.pm new file mode 100644 index 0000000..94a20b6 --- /dev/null +++ b/src/MTools/GUI/MImage.pm @@ -0,0 +1,69 @@ +package MTools::GUI::MImage; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Encapsule la creation d'une image +# Parametres : +# * parent : pere de l'objet. +# * image : nom de l'image +# * %options : table de hash passee en parametre de la creation de l'objet zinc icon + + +use strict; + +use MTools; +use MTools::MObjet; +use vars qw / @ISA /; + +use Tk::PNG; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +sub new { + my ($class, $parent, $image, %options) = @_; + my $self = new MTools::MObjet (); + bless $self, $class; + + my $image = __getImage ($zinc, $image); + $self -> {instance} = $zinc -> add('icon', minstance ($parent), + -priority => 10, + -image => $image, + -composealpha => 1, + %options + ); + return $self; +} + + +sub __getImage { + my ($widget, $imagefile) = @_; + my $image; + if (index ($imagefile, '.png') != -1) + { + $image = $widget -> Photo(-file => Tk::findINC($imagefile), -format => 'png'); + } + else + { + $image = $widget -> Photo(-file => Tk::findINC($imagefile)); + } + return $image; +} + +1; diff --git a/src/MTools/GUI/MRect.pm b/src/MTools/GUI/MRect.pm new file mode 100644 index 0000000..e28b044 --- /dev/null +++ b/src/MTools/GUI/MRect.pm @@ -0,0 +1,54 @@ +package MTools::GUI::MRect; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Encapsule la creation d'un rectangle +# Parametres : +# * parent : pere de l'objet. +# * x, y : de l'angle en haut a gauche du rectangle +# * w, h : largeur et hauteur du rectangle +# * %options : table de hash passee en parametre de la creation de l'objet zinc rectangle + + +use strict; + +use MTools; +use MTools::MObjet; +use vars qw / @ISA /; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +sub new { + my ($class, $parent, $x, $y, $w, $h, %options) = @_; + my $self = new MTools::MObjet (); + bless $self, $class; + if ((defined $options {-fillcolor}) && (!defined $options {-filled})) + { + $options{-filled} = 1; + } + $self -> {instance} = $zinc -> add ('rectangle', + minstance ($parent), + [$x, $y, $x + $w, $y + $h], + %options, + ); + return $self; +} + +1; diff --git a/src/MTools/GUI/MText.pm b/src/MTools/GUI/MText.pm new file mode 100644 index 0000000..71d99ec --- /dev/null +++ b/src/MTools/GUI/MText.pm @@ -0,0 +1,54 @@ +package MTools::GUI::MText; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Encapsule la creation d'un text +# Parametres : +# * parent : pere de l'objet. +# * text : text ! +# * x, y : coordonnees de l'emplacement de l'objet +# * %options : table de hash passee en parametre de la creation de l'objet zinc text + + +use strict; + +use MTools; +use MTools::MObjet; +use vars qw / @ISA /; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +sub new { + my ($class, $parent, $text, $x, $y, %options) = @_; + my $self = new MTools::MObjet (); + bless $self, $class; + if (!defined $x) {$x = 0;} + if (!defined $y) {$y = 0;} + if (!defined $text) {$text = "";} + $self -> {instance} = $zinc -> add ('text', + minstance ($parent), + -text => $text, + %options, + ); + $self -> translate ($x, $y); + return $self; +} + +1; diff --git a/src/MTools/GUI/MTexture.pm b/src/MTools/GUI/MTexture.pm new file mode 100644 index 0000000..f3dff9e --- /dev/null +++ b/src/MTools/GUI/MTexture.pm @@ -0,0 +1,75 @@ +package MTools::GUI::MTexture; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Permet d'appliquer un texture a un objet +# Parametres : +# * parent : pere de l'objet. +# * target : group zinc destine a contenir les images de texture +# * image_name : nom de l'image texture + +use strict; + +use MTools; +use MTools::MGroup; +use MTools::GUI::MImage; + +use vars qw / @ISA /; + + +BEGIN +{ + @ISA = qw /MTools::MGroup/; +} + +sub new { + my ($class, $parent, $target, $image_name) = @_; + my $self = new MTools::MGroup ($parent); + bless $self, $class; + + chggroup ($target, $self); + + my $image = new MTools::GUI::MImage ($self, $image_name); + + my @bb = bbox ($image); + my $img_w = $bb [2] - $bb [0]; + my $img_h = $bb [3] - $bb [1]; + + my @bb = bbox ($target); + my $w = $bb [2] - $bb [0]; + my $h = $bb [3] - $bb [1]; + + mdelete ($image); + + for (my $x = 0; $x < $w; $x += $img_w) + { + for (my $y = 0; $y < $h; $y += $img_h) + { + $image = new MTools::GUI::MImage ($self, $image_name); + $image -> translate ($x + $bb [0], $y + $bb [1]); + } + } + + my $clip = $zinc -> clone ($target); + mconfigure ($clip, -visible => 0); + new MTools::GUI::MClip ($self, $clip); + return $self; +} + + + +1; diff --git a/src/MTools/MGroup.pm b/src/MTools/MGroup.pm new file mode 100644 index 0000000..fb00925 --- /dev/null +++ b/src/MTools/MGroup.pm @@ -0,0 +1,41 @@ +package MTools::MGroup; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# L'objet MTools::MGroup encapsule la cr?ation d'un objet group zinc en toute rigueur il aurait d? ?tre plac? dans MTools::GUI + +use strict; + +use MTools; +use MTools::MObjet; +use vars qw / @ISA /; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +sub new { + my ($class, $parent, %options) = @_; + my $self = {}; + bless $self, $class; + $parent = ref($parent) eq ''?$parent:$parent -> {instance}; + $self -> {instance} = $zinc -> add ('group', $parent, -priority => 10, %options); + return $self; +} + +1; diff --git a/src/MTools/MIvy.pm b/src/MTools/MIvy.pm new file mode 100644 index 0000000..9ade88f --- /dev/null +++ b/src/MTools/MIvy.pm @@ -0,0 +1,75 @@ +package MTools::MIvy; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + + +# Le composant MIvy encapsule la declaration et l'utilisation d'un bus ivy. + +use strict; +use MTools; +use MTools::MObjet; + +use vars qw /@ISA/; + +our $ivy_instance = undef; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class, $adresse, $ivy_name) = @_; + my $self = new MTools::MObjet (); + bless $self, $class; + if (!defined $ivy_instance) + { + Ivy -> init( + -ivyBus => $adresse, + -appName => $ivy_name, + -loopMode => 'TK', + -messWhenReady => 'READY', + ); + $self -> {__ivy} = Ivy -> new (); + $self -> {__ivy} -> start (); + $ivy_instance = $self -> {__ivy}; + } + else + { + $self -> {__ivy} = $ivy_instance; + } + return $self; +} + + +sub binding { + my ($self, $reg, $cb) = @_; + if (ref ($cb) ne 'ARRAY') + { + $cb = [$cb]; + } + $self -> {__ivy} -> bindRegexp ($reg, $cb); +} + +sub sendMsgs { + my ($self, $msgs) = @_; + $self -> {__ivy} -> sendMsgs ($msgs); +} + +1; diff --git a/src/MTools/MObjet.pm b/src/MTools/MObjet.pm new file mode 100644 index 0000000..b35c07f --- /dev/null +++ b/src/MTools/MObjet.pm @@ -0,0 +1,128 @@ +package MTools::MObjet; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Le composant MObject est l'objet racine des composants MTools. +# Il defini les fonctions applicables uniquement aux objets MTools. +# +# IMPORTANT : Une autre partie des fonctions applicables aux objets MTools est definie dans la classe MTools. +# La difference entre ces deux classes de fonctions est que les fonctions definies dans MTools sont egalement +# applicables ? des objets zinc tandis que les fonctions definies ici ne peuvent etre appliquees que a des objets heritant de MTools::MObjet. +# +# Concepts : +# * Objet MTools : objet heritant de MObjet +# * Les PROPERTY : Les proprietes sont des attributs particuliers et modifiables +# par un appel a "mconfigure". Elles peuvent etre ecoutees et synchronisees avec d'autres proprietes +# MTools ou meme zinc ! (cf MTools::plink et MTools::plisten). En consequence elles sont la pour engendrer un comportement +# consecutif ? leur modification et doivent etre distinguees des attibuts qui peuvent se contenter d'etre ds clef de hash de l'objet. +# * Les EVENT : les evenements peuvent etre emis par n'importe quel objet MTools et capter par un binding. +# +# Les fonctions public : +# * recordEvent : permet de permettre a un objet MObjet d'emettre un evenement. +# * recordProperty : permet de declarer et initialiser une propriete. +# NOTA : Il pourrait manquer une declaration collective des proprietes. Initialement, +# celle-ci n'a pas ete effectuee pour essayer de limiter l'usage des proprietes +# et ne pas les utiliser comme des attributs. +# * notify : permet a un objet MTools de notifier un evenement prealablement enregistre par recordEvent +# * propagate : permet a un objet de propager un evenement emis par un autre objet +# (correspond a un recordEvent puis un binding sur un evenement d'un objet effectuant le notify du meme evt +# depuis l'objet declarant la propagation) + +use strict; +use MTools; +use vars qw /@ISA @EXPORT @EXPORT_OK/; + +BEGIN +{ + @ISA = qw //; +} + +sub new { + my ($class) = @_; + my $self = {}; + $self -> {instance} = -1; + bless $self, $class; + return $self; +} + +sub recordEvent { + my ($self, $event) = @_; + if (!(defined $self -> {__events} -> {$event})) + { + $self -> {__events} -> {$event} = []; + } +} + +sub recordProperty { + my ($self, $prop, $val) = @_; + $self -> {__properties} -> {$prop} -> {val} = $val; +} + +sub notify { + my ($self, $event, @params) = @_; + if (!defined $self -> {__events} -> {$event}) + { + print "ERREUR $self : Vous essayer de notifier l'evenement $event qui n'est pas declare\n"; + return; + } + my @tb = @{$self -> {__events} -> {$event}}; + for (my $i = 0; $i < @tb; $i++) + { + executer ($tb[$i], @params); + } +} + +sub propagate { + my ($self, $from, $event, @nargs) = @_; + $self -> recordEvent ($event); + $from -> __addListener ($event, + sub { + my (@args) = @_; + $self -> notify ($event, @args, @nargs); + } + ); +} + +sub __addListener { + my ($self, $event, $methode) = @_; + if (defined $self -> {__events} -> {$event}) + { + push (@{$self -> {__events} -> {$event}}, $methode); + return $methode; + } + else + { + print "ERREUR : l'objet $self n'?met jamais l'evt $event... L'abonnement est donc inutile\n"; + } +} + +sub __removeListener { + my ($self, $event, $methode) = @_; + if (defined $self -> {__events} -> {$event}) + { + my @events = @{$self -> {__events} -> {$event}}; + for (my $i = @events - 1; $i >= 0; $i--) + { + if ($events [$i] == $methode) + { + splice (@{$self -> {__events} -> {$event}}, $i, 1); + } + } + } +} + +1; diff --git a/src/MTools/MState.pm b/src/MTools/MState.pm new file mode 100644 index 0000000..bf7b9d4 --- /dev/null +++ b/src/MTools/MState.pm @@ -0,0 +1,149 @@ +package MTools::MState; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +use strict; +use MTools; +use MTools::MObjet; +use MTools::SVG::SVGLoader; + + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +sub new { + my ($class, %options) = @_; + my $self = {}; + bless $self, $class; + $self -> {instance} = -1; + my %events = %{$options {events}}; + $self -> {__transitions} = $options {transitions}; + my %transitions = %{$self -> {__transitions}}; + + $self -> recordProperty ('state', $options {current_state}); + + $self -> recordEvent('SET_STATE'); + + # Cr?er les bind soit aupr?s de zinc, soit au niveau des objets MObjet + while ( my ($evt, $desc) = each (%events) ) + { + my ($src, $spec) = @{$desc}; + if ($spec =~ /<(.*)>/) + { + binding ($src, $spec, sub {$self -> evt ($evt, @_); }); + } + else + { + $src -> binding ($spec, sub {$self -> evt ($evt, @_); }); + } + } + + # Abonne les switchs ecoutant les changements d'etat + my $sws = $options {switchs}; + if (defined $sws) + { + my @abonnes; + if (ref ($sws) eq 'ARRAY') + { + @abonnes = @{$sws}; + } + else + { + $abonnes [0] = $sws; + } + for (my $i = 0; $i < @abonnes; $i++) + { + $self -> binding ('SET_STATE', [$abonnes [$i], 'setState']); + } + $self -> notify ('SET_STATE', $self -> mget ('state')); + } + + # Enregistre les outputs + while ( my ($src, $trans) = each (%transitions) ) + { + my %trs = %{$trans}; + while ( my ($evt, $desc) = each (%trs) ) + { + if (defined $desc -> {notify}) + { + my @evts; + if (ref ($desc -> {notify}) eq 'ARRAY') + { + @evts = @{$desc -> {notify}}; + } + else + { + $evts [0] = $desc -> {notify}; + } + for (my $i = 0; $i < @evts; $i++) + { + $self -> recordEvent($evts [$i]); + } + } + } + } + + return $self; +} + +sub evt { + my ($self, $evt, @args) = @_; + if (defined $self -> {__transitions} -> {$self -> mget ('state')} -> {$evt}) + { + my $trans = $self -> {__transitions} -> {$self -> mget ('state')} -> {$evt}; + if( defined $trans -> {do_before} ) + { + executer ($trans -> {do_before}, @args); + } + if( defined $trans -> {to} ) + { + $self -> mconfigure ('state', $self -> {__transitions} -> {$self -> mget ('state')} -> {$evt} -> {to}); + $self -> notify ('SET_STATE', $self -> mget ('state')); + } + if( defined $trans -> {do_after} ) + { + executer ($trans -> {do_after}, @args); + } + if( defined $trans -> {notify} ) + { + my @evts; + if (ref ($trans -> {notify}) eq 'ARRAY') + { + @evts = @{$trans -> {notify}}; + } + else + { + $evts [0] = $trans -> {notify}; + } + for (my $i = 0; $i < @evts; $i++) + { + $self -> notify ($evts [$i], @args); + } + } + } +} + +sub setState { + print "################## MTools::MState TODO\n"; +} + +1; + diff --git a/src/MTools/MSwitch.pm b/src/MTools/MSwitch.pm new file mode 100644 index 0000000..8933ca3 --- /dev/null +++ b/src/MTools/MSwitch.pm @@ -0,0 +1,201 @@ +package MTools::MSwitch; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Le composant MSwitch permet de mat?rialiser et contr?ler des "?tat" actif de l'application. +# Le principe est d'associer des composants (graphiques, abstraits, comportements, objets complexes) ? un ?tat. +# Le composant MSwitch contr?le un ?tat actif de l'application et g?re l'option "-visible" des composants associ?s ? l'?tat. +# +# Les param?tres : +# * $parent : parent de l'objet MSwitch +# * %etats : table de hash d?finissant les ?tats de l'application +# Ex : +# etat1 => [], # ?tat ne comportant aucun composant +# etat2 => 'fichier_svg.svg#tag_svg', # l'?tat va instancier un objet issu d'un fichier svg +# etat3 => ['fichier_svg.svg#tag_svg', $obj], # l'?tat va contenir deux objets: l'un instancier par le MSwitch l'autre d?j? cr?? pr?alablement +# Les propi?t?s : +# * state : contr?le l'?tat actif du MSwitch +# * -visible : permettre de rendre le MSwitch visible ou invisible et en cons?quence de rendre +# "visible ou invisible" les composants de l'?tat actif du switch +# Les fonctions public : +# * setState : $switch -> setState ('etat') ?quivalent ? $swicth -> mconfigure (state => 'etat') + +use strict; +use MTools; +use MTools::MGroup; +use MTools::SVG::SVGLoader; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MGroup/; +} + +sub new { + my ($class, $parent, %etats) = @_; + my $self = new MTools::MGroup ($parent); + bless $self, $class; + + $self -> recordProperty ('state', ''); + $self -> recordProperty ('-visible', 1); + $self -> {__last} = ''; + $self -> plisten ('state', [$self, '__setState']); + + my $first = ''; + + while ( my ($etat, $val) = each (%etats) ) + { + if ($first eq '') + { + $first = $etat; + } + my @tb; + if (ref ($val) eq 'ARRAY') + { + @tb = @{$val}; + } + else + { + $tb[0] = $val; + } + + for (my $i = 0; $i < @tb; $i ++) + { + if ( !defined $self -> {"__instance_".$tb [$i]}) + { + if ( ref ($tb [$i]) eq '') + { + $self -> {"__instance_".$tb [$i]} = minstance ($tb [$i], $self); + MTools::mconfigure ($self -> {"__instance_".$tb [$i]}, -visible => 0, -sensitive => 0); + } + else + { + $self -> {"__instance_".$tb [$i]} = $tb [$i]; + $self -> {"__instance_".$tb [$i]} -> mconfigure ( -visible => 0, -sensitive => 0); + } + + } + } + + $self -> {"__etat_$etat"} = \@tb; + } + if ($first ne '') + { + $self -> mconfigure ('state' => $first); + } + return $self; +} + +sub setState { + my ($self, $etat) = @_; + $self -> mconfigure ('state', $etat); +} + +sub __setState { + my ($self, $src, $key, $etat) = @_; + my $curr = $self -> {__last}; + $self -> {__last} = $etat; + if(!$self -> mget ('-visible')) + { + return; + } + if ($curr ne '') + { + if (defined $self -> {"__etat_".$curr}) + { + my @tb = @{$self -> {"__etat_".$curr}}; + for (my $i = 0; $i < @tb; $i ++) + { + if ( ref ($tb [$i]) eq '') + { + MTools::mconfigure ($self -> {"__instance_".$tb [$i]}, -visible => 0, -sensitive => 0); + } + else + { + $self -> {"__instance_".$tb [$i]} -> mconfigure (-visible => 0, -sensitive => 0); + } + } + } + else + { + die "MTools::MSwitch::__setState : you are trying to set a unknown state \"$curr\"\n"; + } + } + if (defined $self -> {"__etat_$etat"}) + { + my @tb = @{$self -> {"__etat_$etat"}}; + for (my $i = 0; $i < @tb; $i ++) + { + if ( ref ($tb [$i]) eq '') + { + MTools::mconfigure ($self -> {"__instance_".$tb [$i]}, -visible => 1, -sensitive => 1); + } + else + { + $self -> {"__instance_".$tb [$i]} -> mconfigure (-visible => 1, -sensitive => 1); + } + raise ($self -> {"__instance_".$tb [$i]}); + } + } + else + { + if ($etat ne '') + { + die "MTools::MSwitch::__setState : you are trying to set a unknown state \"$etat\"\n"; + } + } +} + +sub mconfigure { + my ($self, %options) = @_; + if (defined $options {-visible}) + { + my $curr = ::mget ($self, 'state'); + if ($curr ne '') + { + if (defined $self -> {"__etat_".$curr}) + { + my @tb = @{$self -> {"__etat_".$curr}}; + my $v = $options {-visible}; + for (my $i = 0; $i < @tb; $i ++) + { + if ( ref ($tb [$i]) eq '') + { + MTools::mconfigure ($self -> {"__instance_".$tb [$i]}, -visible => $v, -sensitive => $v); + } + else + { + $self -> {"__instance_".$tb [$i]} -> mconfigure (-visible => $v, -sensitive => $v); + } + if ($v) + { + raise ($self -> {"__instance_".$tb [$i]}); + } + } + } + else + { + die "MTools::MSwitch::mconfigure : you are trying to set a unknown state \"$curr\"\n"; + } + } + } + MTools::mconfigure ($self, %options); +} + + +1; diff --git a/src/MTools/MTimer.pm b/src/MTools/MTimer.pm new file mode 100644 index 0000000..68d1a00 --- /dev/null +++ b/src/MTools/MTimer.pm @@ -0,0 +1,104 @@ +package MTools::MTimer; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +# Le composant MTimer encapsule la d?claration et l'utilisation d'un timer. +# Les param?tres : +# * $timeout : repr?sente timeout en ms du timer (totologique ? non...) +# * $repeat : active ou non le caract?re r?p?titif du timer (valeur 0 ou 1) +# * $callback : est optionnel et permet d'appeler une callback au timeout. +# Les ?v?nements : +# * TIME_OUT : ?mis au timeout en plus de l'appel ? une ?ventuelle callback +# * TIMER_STOPPED : ?mis si le timer est interrompu avant un timeout +# Les propi?t?s : +# * timeout : ... +# * repeat : ... +# * callback : ... +# * -visible : d?finie pour assurer la compatibilit? avec les autres objets MTools. +# Si la valeur est 0 le composant est d?sactiv? (appel ? la fonction stop), +# si la valeur est 1 (appel ? la fonction start), le composant est activ?. +# Cette propri?t? permet notamment d'activer un timer dans un ?tat d'un MSwitch. +# Les fonctions public : +# * start permet de d?marrer le timer +# * stop permet de stopper le timer +# Nota : cf. ci-dessus, ces fonctions peuvent ?tre contr?l?es par la propri?t? -visible + +use strict; +use MTools; +use MTools::MObjet; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + + +sub new { + my ($class, $timeout, $repeat, $callback, %options) = @_; + my $self = {}; + bless $self, $class; + + $repeat = 0 if !defined $repeat; + $repeat = 0 if !defined $callback; + + $self -> recordEvent ('TIME_OUT'); + $self -> recordEvent ('TIMER_STOPPED'); + $self -> recordProperty ('timeout', $timeout); + $self -> recordProperty ('repeat', $repeat); + $self -> recordProperty ('callback', $callback); + $self -> recordProperty ('-visible', 0); + $self -> plisten ('-visible', sub { + my ($src, $key, $val) = @_; + if ($val == 0) + { + $self -> stop (); + } + else + { + $self -> start (); + } + }); + $self -> mconfigure (%options); + + return $self; +} + +sub start { + my ($self) = @_; + my $repeat = $self -> mget ('repeat'); + my $timeout = $self -> mget ('timeout'); + my $callback = $self -> mget ('callback'); + my $function = $repeat ? 'repeat' : 'after'; + $self -> {__timer} = $zinc -> $function ($timeout, sub { + $self -> notify ('TIME_OUT'); + if ($callback) + { + executer ($callback); + } + }); +} + +sub stop { + my ($self) = @_; + $zinc -> afterCancel ($self -> {__timer}); + $self -> notify ('TIMER_STOPPED'); +} +1; diff --git a/src/MTools/SVG/SVGLoader.pm b/src/MTools/SVG/SVGLoader.pm new file mode 100644 index 0000000..1aeafc7 --- /dev/null +++ b/src/MTools/SVG/SVGLoader.pm @@ -0,0 +1,87 @@ +#!/usr/bin/perl +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +package MTools::SVG::SVGLoader; + +use strict; +use Carp; + +use MTools; +use SVG::SVG2zinc; + +sub load { + my ($path, $topgroup) = @_; + $topgroup = ref($topgroup) eq ''?$topgroup:$topgroup -> {instance}; + my $svgfile = $path; + my $tag; + my $ftag; + if (index($svgfile, '#') == -1) + { + $tag = ''; + $ftag = ''; + } + else + { + $svgfile = substr ($path, 0, index ($path, '#')); + $tag = substr ($path, index ($path, '#') + 1, length ($path)); + $ftag = "::$tag"; + } + + if($svgfile =~ /(.*)\.svg/) + { + my $filename = $1; + my $svgfile = Tk::findINC ("$filename.svg"); + if (!defined $svgfile) + { + print STDERR "##### Error undefined file $filename.svg\n"; + } + my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat($svgfile); + my ($dev2,$ino2,$mode2,$nlink2,$uid2,$gid2,$rdev2,$size2,$atime2,$mtime2,$ctime2,$blksize2,$blocks2) = (0,0,0,0,0,0,0,0,0,0,0,0,0); + my $filepath = 'AUTOGEN::'.$filename; + $filepath = "$filepath$ftag.pm"; + $filepath =~ s/::/\//g; + $filename =~ s/\//::/g; + if(-e $filepath) + { + ($dev2,$ino2,$mode2,$nlink2,$uid2,$gid2,$rdev2,$size2,$atime2,$mtime2,$ctime2,$blksize2,$blocks2) = stat($filepath); + } + if( $mtime2 < $mtime ) + { + print "Regenarate SVG modified\n"; + my $pack = $filename; + SVG::SVG2zinc::parsefile( + $svgfile, + "PerlClass", + -out => "AUTOGEN::$filename$ftag.pm", + -verbose => 0, + -render => 1, + -namespace => 0, + -target => $tag + ); + } + require "$filepath"; + my $packagename = "AUTOGEN::$filename$ftag"; + return new $packagename ( + -zinc => $zinc, + -topgroup => $topgroup, + ); + } + +} + +1; diff --git a/src/MTools/Transform/MRotation.pm b/src/MTools/Transform/MRotation.pm new file mode 100644 index 0000000..16b405a --- /dev/null +++ b/src/MTools/Transform/MRotation.pm @@ -0,0 +1,76 @@ +package MTools::Transform::MRotation; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +use strict; +use MTools; +use MTools::MObjet; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +use Tk; + +sub new { + my ($class, $target, $angle, $x, $y) = @_; + my $self = new MTools::MObjet (); + bless $self, $class; + + if (!defined $x) {$x = 0;} + if (!defined $y) {$y = 0;} + if (!defined $angle) {$angle = 0;} + + $self -> recordProperty ('-visible', 0); + $self -> recordProperty ('target', $target); + $self -> recordProperty ('angle', $angle); + $self -> recordProperty ('x', $x); + $self -> recordProperty ('y', $y); + $self -> plisten ('-visible', sub { + my ($src, $key, $val) = @_; + if ($val == 0) + { + $self -> __rotate (0); + } + else + { + $self -> __rotate ($self -> mget ('angle')); + } + }); + $self -> plisten ('angle', sub { + my ($src, $key, $val) = @_; + $self -> __rotate ($val); + }); + $self -> {__current_angle} = 0; + $self -> __rotate ($angle); + return $self; +} + +sub __rotate { + my ($self, $angle) = @_; + my $new_angle = $angle - $self -> {__current_angle}; + $self -> {__current_angle} = $angle; + my $target = $self -> mget ('target'); + my $x = $self -> mget ('x'); + my $y = $self -> mget ('y'); + $target -> rotate ($new_angle, 1, $x, $y); +} + +1; diff --git a/src/MTools/Widget/MBouton.pm b/src/MTools/Widget/MBouton.pm new file mode 100644 index 0000000..73c0fc0 --- /dev/null +++ b/src/MTools/Widget/MBouton.pm @@ -0,0 +1,180 @@ +package MTools::Widget::MBouton; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +use strict; +use MTools; +use MTools::MGroup; +use MTools::MSwitch; +use MTools::MState; +use MTools::MTimer; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MGroup/; +} + +sub new { + my ($class, %options) = @_; + my $self = new MTools::MGroup ($options {parent}); + + bless $self, $class; + + my $on = minstance ($options {g_on}, $self); + my $off = minstance ($options {g_off}, $self); + my $over = defined $options {g_over} ? minstance ($options {g_over}, $self) : $on; + my $eventOn = defined $options {e_press} ? $options {e_press} : 'PRESS'; + my $eventOff = defined $options {e_release} ? $options {e_release} : 'RELEASED'; + my $cb = $options {call} if (defined $options {call}); + + + $self -> recordEvent ('MAINTAIN_DOWN'); + $self -> recordEvent ('PRESS'); + $self -> recordEvent ('RELEASE'); + $self -> mconfigure (-atomic => 1); + + my @gon; + push (@gon, $on); + my @goff; + push (@goff, $off); + my @gover; + push (@gover, $over); + + if (defined $options {g_text}) + { + $self -> recordProperty ('text', $options {text}); + my $txt = minstance ($options {g_text}, $self); + push (@gon, $txt); + push (@goff, $txt); + push (@gover, $txt); + plink ([$self, 'text'], [$txt, '-text']); + } + + $self -> {gp_over} = new MTools::MGroup ($self); + push (@gon, $self -> {gp_over}); + push (@goff, $self -> {gp_over}); + push (@gover, $self -> {gp_over}); + + my $timer = new MTools::MTimer (5, 1); + my @gon_tmp = @gon; + push (@gon_tmp, $timer); + + my $sw = new MTools::MSwitch ( + $self, + 'up' => \@gon, + 'up_tmp' => \@gon_tmp, + 'down' => \@goff, + 'over' => \@gover, + 'maintain_down' => \@goff, + ); + + my $st = new MTools::MState ( + current_state => 'up', + events => { + press => [$self, '<Button-1>'], + force_press => [$self, 'PRESS'], + maintain => [$self, 'MAINTAIN_DOWN'], + release => [$self, '<ButtonRelease-1>'], + force_release => [$self, 'RELEASE'], + enter => [$self, '<Enter>'], + leave => [$self, '<Leave>'], + timeout => [$timer, 'TIME_OUT'] + }, + transitions => { + 'up' => { + 'press' => { + to => 'down', + notify => $eventOn, + }, + 'force_press' => { + to => 'down', + notify => $eventOn, + }, + 'enter' => { + to => 'over', + }, + }, + 'up_tmp' => { + 'press' => { + to => 'down', + notify => $eventOn, + }, + 'force_press' => { + to => 'down', + notify => $eventOn, + }, + 'timeout' => { + to => 'up', + }, + }, + 'over' => { + 'press' => { + to => 'down', + notify => $eventOn, + }, + 'force_press' => { + to => 'down', + notify => $eventOn, + }, + 'leave' => { + to => 'up_tmp', + } + }, + 'down' => { + 'release' => { + to => 'up', + notify => $eventOff, + }, + 'force_release' => { + to => 'up', + notify => $eventOff, + }, + 'maintain' => { + to => 'maintain_down', + }, + }, + 'maintain_down' => { + 'press' => { + to => 'down', + }, + 'force_release' => { + to => 'up', + notify => $eventOff, + }, + }, + }, + switchs => [$sw], + ); + + if (defined $cb) + { + $st -> binding ($eventOn, sub { + executer ($cb); + }); + } + + $self -> propagate ($st, $eventOn); + $self -> propagate ($st, $eventOff); + + return $self; +} + + +1; + diff --git a/src/MTools/Widget/MRadioBouton.pm b/src/MTools/Widget/MRadioBouton.pm new file mode 100644 index 0000000..630f0f6 --- /dev/null +++ b/src/MTools/Widget/MRadioBouton.pm @@ -0,0 +1,108 @@ +package MTools::Widget::MRadioBouton; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +use strict; +use MTools; +use MTools::MGroup; +use MTools::MSwitch; +use MTools::MState; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MGroup/; +} + +sub new { + my ($class, %options) = @_; + my $self = new MTools::MGroup ($options {parent}); + + bless $self, $class; + + my $on = $options {g_on}; + my $off = $options {g_off}; + + $self -> recordEvent ('RELEASE'); + $self -> recordEvent ('PRESS'); + $self -> recordProperty ('selected', 0); + + my @gon; + push (@gon, $on); + my @goff; + push (@goff, $off); + + if (defined $options {g_text}) + { + $self -> recordProperty ('text', $options {text}); + my $txt = minstance ($options {g_text}, $self); + push (@gon, $txt); + push (@goff, $txt); + plink ([$self, 'text'], [$txt, '-text']); + } + $self -> mconfigure (-atomic => 1); + my $sw = new MTools::MSwitch ( + $self, + on => \@gon, + off => \@goff, + ); + my $st = new MTools::MState ( + current_state => 'on', + events => { + press => [$self, '<Button-1>'], + press2 => [$self, 'PRESS'], + release => [$self, 'RELEASE'], + }, + transitions => { + on => { + press => { + to => 'off', + notify => 'PRESSED', + }, + press2 => { + to => 'off', + notify => 'PRESSED', + }, + }, + off => { + release => { + to => 'on', + notify => 'RELEASED', + }, + }, + }, + switchs => [$sw], + ); + + $st -> binding ('PRESSED', sub { + $self -> mconfigure ('selected', 1); + }); + + $st -> binding ('RELEASED', sub { + $self -> mconfigure ('selected', 0); + }); + + $self -> propagate ($st, 'PRESSED'); + + + return $self; +} + + +1; + diff --git a/src/MTools/Widget/MRadioGroup.pm b/src/MTools/Widget/MRadioGroup.pm new file mode 100644 index 0000000..13a38d8 --- /dev/null +++ b/src/MTools/Widget/MRadioGroup.pm @@ -0,0 +1,86 @@ +package MTools::Widget::MRadioGroup; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +use strict; + +use MTools; +use MTools::MObjet; +use vars qw / @ISA /; + +BEGIN +{ + @ISA = qw /MTools::MObjet/; +} + +sub new { + my ($class, @buttons) = @_; + my $self = new MTools::MObjet (); + bless $self, $class; + + $self -> recordEvent ('BUTTON_SELECTED'); + $self -> {buttons} = (); + + for (my $i = 0; $i < @buttons; $i ++) + { + $self -> addButton ($buttons [$i]); + } + + return $self; +} + +sub addButton { + my ($self, $button) = @_; + push (@{$self -> {buttons}}, $button); + $button -> binding ('PRESSED', sub { + my @buttons = @{$self -> {buttons}}; + for (my $i = 0; $i < @buttons; $i ++) + { + if ($buttons [$i] != $button) + { + $buttons [$i] -> notify ('RELEASE'); + } + } + $self -> notify ('BUTTON_SELECTED', $button); + }); +} + +sub getSelected { + my ($self) = @_; + my @buttons = @{$self -> {buttons}}; + for (my $i = 0; $i < @buttons; $i ++) + { + if ($buttons [$i] -> mget ('selected')) + { + return $buttons [$i]; + } + } +} + +sub setSelected { + my ($self, $button) = @_; + my @buttons = @{$self -> {buttons}}; + for (my $i = 0; $i < @buttons; $i ++) + { + if ($buttons [$i] == $button) + { + $buttons [$i] -> notify ('PRESS'); + } + } +} + +1; diff --git a/src/MTools/Widget/MSplitPane.pm b/src/MTools/Widget/MSplitPane.pm new file mode 100644 index 0000000..dd593bf --- /dev/null +++ b/src/MTools/Widget/MSplitPane.pm @@ -0,0 +1,224 @@ +package MTools::Widget::MSplitPane; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +use strict; + +use MTools; +use MTools::SVG::SVGLoader; + +use vars qw /@ISA/; + +use MTools::MGroup; +use MTools::Widget::MBouton; +use MTools::Comp::MMover; +use MTools::Anim::MTranslator; +use MTools::GUI::MClip; + +BEGIN +{ + @ISA = qw /MTools::MGroup/; +} + +sub new { + my ($class, $parent, %options) = @_; + my $self = new MTools::MGroup ($parent); + bless $self, $class; + + $self -> recordProperty ('percentage', 0.00001); + my $size = $options {size}; + $self -> recordProperty ('size', $size); + + $self -> {__firstgp} = my $gp_first = $options {first_group}; + $self -> {__secondgp} = my $gp_second = $options {second_group}; + my $orientation = $options {orientation}? $options {orientation}:'vertical'; + $self -> {__vertical} = my $vertical = $orientation eq 'vertical'; + $self -> {__cursor_size} = $options {cursor_size}? $options {cursor_size}:'10'; + + if ($vertical) + { + new MTools::GUI::MClip ($gp_first, ['rectangle', -2, -1000, $size, 1000]); + new MTools::GUI::MClip ($gp_second, ['rectangle', -2, -1000, $size, 1000]); + } + else + { + new MTools::GUI::MClip ($gp_first, ['rectangle', -1000, -2, 1000, $size]); + new MTools::GUI::MClip ($gp_second, ['rectangle',-1000, -2, 1000, $size]); + } + + $self -> {__curseur} = new MTools::MSwitch ( + $self, + on => [$options {cursor_on}], + off => [$options {cursor_off}], + ); + + $self -> {__mover} = my $mover = new MTools::Comp::MMover($self -> {__curseur}, $self, 1, + x_min => 0, + y_min => 0, + x_max => $vertical ? $options {size} : 0, + y_max => !$vertical ? $options {size} : 0, + ); + + $self -> propagate ($mover, 'MOVED'); + + if ($options {with_buttons}) + { + my $bouton_open = new MTools::Widget::MBouton ( + parent => $self, + g_on => $options {button_open_on}, + g_off => $options {button_open_off}, + e_press => 'PRESS', + e_release => 'OPEN', + ); + my $bouton_close = new MTools::Widget::MBouton ( + parent => $self, + g_on => $options {button_close_on}, + g_off => $options {button_close_off}, + e_press => 'PRESS', + e_release => 'CLOSE', + ); + $self -> {__boutons} = new MTools::MSwitch ( + $self, + open => $bouton_open, + close => $bouton_close, + ); + $self -> {__boutons} -> mconfigure ('state' => 'open'); + $self -> {__anim_open} = new MTools::Anim::MTranslator ( + from_x => 0, + from_y => 0, + to_x => $vertical * $options {size}, + to_y => (!$vertical) * $options {size}, + targets => $mover, + duration => 0.5, + ); + $bouton_open -> binding ('OPEN', [$self, \&opening]); + $bouton_close -> binding ('CLOSE', [$self, \&closing]); + } + + $gp_first -> scale ( $vertical? 0.00001:1, !$vertical? 0.00001:1); + $self -> {__old_val} = 0; + $gp_second -> translate ($vertical * $self -> {__cursor_size}, (!$vertical) * $self -> {__cursor_size}); + + $mover -> binding ('MOVED', [$self, \&moved]); + + new MTools::MState ( + current_state => 'on', + events => { + press => [$mover, 'PRESSED'], + release => [$mover, 'RELEASED'], + }, + transitions => { + on => { + press => { + to => 'off', + }, + }, + off => { + release => { + to => 'on', + }, + }, + }, + switchs => [$self -> {__curseur}], + ); + + return $self; +} + +sub moved { + my ($self, $x, $y) = @_; + + my $gp_first = $self -> {__firstgp}; + my $gp_second = $self -> {__secondgp}; + + my $vertical = $self -> {__vertical}; + my $val = $vertical ? $x : $y; + + my $size = $self -> mget ('size'); + my $oldperc = $self -> mget ('percentage'); + my $perc = $val / $size; + my $operc = 1 - $perc; + my $oldoperc = 1 - $oldperc; + if ($perc < 0.00001) + { + $perc = 0.00001; + } + if ($operc < 0.00001) + { + $operc = 0.00001; + } + if ($oldoperc < 0.00001) + { + $oldoperc = 0.00001; + } + + $gp_first -> scale ($vertical ? $perc / $oldperc : 1, !$vertical ? $perc / $oldperc : 1); + my $trans = $val - $self -> {__old_val}; + $gp_second -> translate ($vertical * $trans, (!$vertical) * $trans); + my $pos = $val + $self -> {__cursor_size}; + $gp_second -> scale ($vertical ? $operc / $oldoperc : 1, !$vertical ? $operc / $oldoperc : 1, $vertical * $pos, (!$vertical) * $pos); + + $self -> mconfigure ('percentage', $perc); + $self -> {__old_val} = $val; + if ($val > $size / 2) + { + $self -> {__boutons} -> mconfigure ('state' => 'close'); + } + else + { + $self -> {__boutons} -> mconfigure ('state' => 'open'); + } +} + +sub opening { + my ($self) = @_; + if ($self -> {__vertical}) + { + $self -> {__anim_open} -> mconfigure ( + from_x => $self -> {__old_val}, + to_x => $self -> mget ('size'), + ); + } + else + { + $self -> {__anim_open} -> mconfigure ( + from_y => $self -> {__old_val}, + to_y => $self -> mget ('size'), + ); + } + $self -> {__anim_open} -> start (); +} + +sub closing { + my ($self) = @_; + if ($self -> {__vertical}) + { + $self -> {__anim_open} -> mconfigure ( + from_x => $self -> {__old_val}, + to_x => 0, + ); + } + else + { + $self -> {__anim_open} -> mconfigure ( + from_y => $self -> {__old_val}, + to_y => 0, + ); + } + $self -> {__anim_open} -> start (); +} +1; diff --git a/src/MTools/Widget/MToggleBouton.pm b/src/MTools/Widget/MToggleBouton.pm new file mode 100644 index 0000000..56c976c --- /dev/null +++ b/src/MTools/Widget/MToggleBouton.pm @@ -0,0 +1,81 @@ +package MTools::Widget::MToggleBouton; +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +use strict; +use MTools; +use MTools::MGroup; +use MTools::MSwitch; +use MTools::MState; + +use vars qw /@ISA/; + +BEGIN +{ + @ISA = qw /MTools::MGroup/; +} + +sub new { + my ($class, %options) = @_; + my $self = new MTools::MGroup ($options {parent}); + + bless $self, $class; + + my $on = $options {g_on}; + my $off = $options {g_off}; + my $eventOn = $options {e_press}; + my $eventOff = $options {e_release}; + + my $sw = new MTools::MSwitch ( + $self, + on => [$on], + off => [$off], + ); + my $st = new MTools::MState ( + current_state => 'on', + events => { + press => [$sw, '<Button-1>'], + }, + transitions => { + on => { + press => { + to => 'off', + notify => $eventOn, + }, + }, + off => { + press => { + to => 'on', + notify => $eventOff, + }, + }, + }, + switchs => [$sw], + ); + + $self -> propagate ($st, $eventOn); + $self -> propagate ($st, $eventOff); + + return $self; +} + + +1; + + + + diff --git a/src/MTools/ptkdb.pm b/src/MTools/ptkdb.pm new file mode 100644 index 0000000..5962e63 --- /dev/null +++ b/src/MTools/ptkdb.pm @@ -0,0 +1,4229 @@ +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU LGPL Libray General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, 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 Library General Public License for more details. +# +# You should have received a copy of the GNU Library 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, +# or refer to http://www.gnu.org/copyleft/lgpl.html +# +################################################################## + +package DB ; + +## +## Expedient fix for perl 5.8.0. True DB::DB is further down. +## +## +sub DB {} + +use Tk ; + +# +# If you've loaded this file via a browser +# select "Save As..." from your file menu +# +# ptkdb Perl Tk perl Debugger +# +# Copyright 1998, Andrew E. Page +# All rights reserved. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of either: +# +# a) the GNU General Public License as published by the Free +# Software Foundation; either version 1, or (at your option) any +# later version, or +# +# b) the "Artistic License" which comes with this Kit. +# +# 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 either +# the GNU General Public License or the Artistic License for more details. +# + + +#################################### +### Sample .Xresources for ptkdb ### +#################################### +# /* +# * Perl Tk Debugger XResources. +# * Note... These resources are subject to change. +# * +# * Use 'xfontsel' to select different fonts. +# * +# * Append these resource to ~/.Xdefaults | ~/.Xresources +# * and use xrdb -override ~/.Xdefaults | ~/.Xresources +# * to activate them. +# */ +# /* Set Value to se to place scrollbars on the right side of windows +# CAUTION: extra whitespace at the end of the line is causing +# failures with Tk800.011. +# */ +# ptkdb*scrollbars: sw +# +# /* controls where the code pane is oriented, down the left side, or across the top */ +# /* values can be set to left, right, top, bottom */ +# ptkdb*codeside: left +# /* +# * Background color for the balloon +# * CAUTION: For certain versions of Tk trailing +# * characters after the color produces an error +# */ +# ptkdb.frame2.frame1.rotext.balloon.background: green +# ptkdb.frame2.frame1.rotext.balloon.font: fixed /* Hot Variable Balloon Font */ +# +# +# ptkdb.frame*font: fixed /* Menu Bar */ +# ptkdb.frame.menubutton.font: fixed /* File menu */ +# ptkdb.frame2.frame1.rotext.font: fixed /* Code Pane */ +# ptkdb.notebook.datapage.frame1.hlist.font: fixed /* Expression Notebook Page */ +# +# ptkdb.notebook.subspage*font: fixed /* Subroutine Notebook Page */ +# ptkdb.notebook.brkptspage*entry.font: fixed /* Delete Breakpoint Buttons */ +# ptkdb.notebook.brkptspage*button.font: fixed /* Breakpoint Expression Entries */ +# ptkdb.notebook.brkptspage*button1.font: fixed /* Breakpoint Expression Entries */ +# ptkdb.notebook.brkptspage*checkbutton.font: fixed /* Breakpoint Checkbuttons */ +# ptkdb.notebook.brkptspage*label.font: fixed /* Breakpoint "Cond" label */ +# +# ptkdb.toplevel.frame.textundo.font: fixed /* Eval Expression Entry Window */ +# ptkdb.toplevel.frame1.text.font: fixed /* Eval Expression Results Window */ +# ptkdb.toplevel.button.font: fixed /* "Eval..." Button */ +# ptkdb.toplevel.button1.font: fixed /* "Clear Eval" Button */ +# ptkdb.toplevel.button2.font: fixed /* "Clear Results" Button */ +# ptkdb.toplevel.button3.font: fixed /* "Clear Dismiss" Button */ +# +# +# /* +# * Background color for where the debugger has stopped +# */ +# ptkdb*stopcolor: blue +# +# /* +# * Background color for set breakpoints +# */ +# ptkdb*breaktagcolor: red +# +# /* +# * Font for where the debugger has stopped +# */ +# ptkdb*stopfont: -*-fixed-bold-*-*-*-*-*-*-*-*-*-*-* +# +# /* +# * Background color for the search tag +# */ +# ptkdb*searchtagcolor: green + +use strict ; +use vars qw($VERSION @dbline %dbline); + +# +# This package is the main_window object +# for the debugger. We start with the Devel:: +# prefix because we want to install it with +# the DB:: package that is required to be in a Devel/ +# subdir of a directory in the @INC set. +# +package Devel::ptkdb ; + +=head1 NAME + +Devel::ptkdb - Perl debugger using a Tk GUI + +=head1 DESCRIPTION + + ptkdb is a debugger for perl that uses perlTk for a user interface. + Features include: + + Hot Variable Inspection + Breakpoint Control Panel + Expression List + Subroutine Tree + + +=begin html + + <body bgcolor=white> + +=end html + +=head1 SYNOPSIS + +To debug a script using ptkdb invoke perl like this: + + perl -d:ptkdb myscript.pl + +=head1 Usage + + perl -d:ptkdb myscript.pl + +=head1 Code Pane + +=over 4 + +=item Line Numbers + + Line numbers are presented on the left side of the window. Lines that + have lines through them are not breakable. Lines that are plain text + are breakable. Clicking on these line numbers will insert a + breakpoint on that line and change the line number color to + $ENV{'PTKDB_BRKPT_COLOR'} (Defaults to Red). Clicking on the number + again will remove the breakpoint. If you disable the breakpoint with + the controls on the BrkPt notebook page the color will change to + $ENV{'PTKDB_DISABLEDBRKPT_COLOR'}(Defaults to Green). + +=item Cursor Motion + +If you place the cursor over a variable (i.e. $myVar, @myVar, or +%myVar) and pause for a second the debugger will evaluate the current +value of the variable and pop a balloon up with the evaluated +result. I<This feature is not available with Tk400.> + +If Data::Dumper(standard with perl5.00502)is available it will be used +to format the result. If there is an active selection, the text of +that selection will be evaluated. + +=back + +=head1 Notebook Pane + +=over 2 + +=item Exprs + + This is a list of expressions that are evaluated each time the + debugger stops. The results of the expresssion are presented + heirarchically for expression that result in hashes or lists. Double + clicking on such an expression will cause it to collapse; double + clicking again will cause the expression to expand. Expressions are + entered through B<Enter Expr> entry, or by Alt-E when text is + selected in the code pane. + + The B<Quick Expr> entry, will take an expression, evaluate it, and + replace the entries contents with the result. The result is also + transfered to the 'clipboard' for pasting. + +=item Subs + + Displays a list of all the packages invoked with the script + heirarchially. At the bottom of the heirarchy are the subroutines + within the packages. Double click on a package to expand + it. Subroutines are listed by their full package names. + +=item BrkPts + + Presents a list of the breakpoints current in use. The pushbutton + allows a breakpoint to be 'disabled' without removing it. Expressions + can be applied to the breakpoint. If the expression evaluates to be + 'true'(results in a defined value that is not 0) the debugger will + stop the script. Pressing the 'Goto' button will set the text pane + to that file and line where the breakpoint is set. Pressing the + 'Delete' button will delete the breakpoint. + +=back + +=head1 Menus + +=head2 File Menu + +=over + +=item About... + +Presents a dialog box telling you about the version of ptkdb. It +recovers your OS name, version of perl, version of Tk, and some other +information + +=item Open + +Presents a list of files that are part of the invoked perl +script. Selecting a file from this list will present this file in the +text window. + +=item Save Config... + +Requires Data::Dumper. Prompts for a filename to save the +configuration to. Saves the breakpoints, expressions, eval text and +window geometry. If the name given as the default is used and the +script is reinvoked, this configuration will be reloaded +automatically. + + B<NOTE:> You may find this preferable to using + +=item Restore Config... + +Requires Data::Dumper. Prompts for a filename to restore a configuration saved with +the "Save Config..." menu item. + +=item Goto Line... + +Prompts for a line number. Pressing the "Okay" button sends the window to the line number entered. +item Find Text... + +Prompts for text to search for. Options include forward search, +backwards search, and regular expression searching. + +=item Quit + + Causes the debugger and the target script to exit. + +=back + +=head2 Control Menu + +=over + +=item Run + +The debugger allows the script to run to the next breakpoint or until the script exits. +item Run To Here + +Runs the debugger until it comes to wherever the insertion cursor +in text window is placed. + +=item Set Breakpoint + +Sets a breakpoint on the line at the insertion cursor. +item Clear Breakpoint + +Remove a breakpoint on the at the insertion cursor. + +=item Clear All Breakpoints + +Removes all current breakpoints + +=item Step Over + +Causes the debugger to step over the next line. If the line is a +subroutine call it steps over the call, stopping when the subroutine +returns. + +=item Step In + +Causes the debugger to step into the next line. If the line is a +subroutine call it steps into the subroutine, stopping at the first +executable line within the subroutine. + +=item Return + +Runs the script until it returns from the currently executing +subroutine. + +=item Restart + +Saves the breakpoints and expressions in a temporary file and restarts +the script from the beginning. CAUTION: This feature will not work +properly with debugging of CGI Scripts. + +=item Stop On Warning + +When C<-w> is enabled the debugger will stop when warnings such as, "Use +of uninitialized value at undef_warn.pl line N" are encountered. The debugger +will stop on the NEXT line of execution since the error can't be detected +until the current line has executed. + +This feature can be turned on at startup by adding: + +$DB::ptkdb::stop_on_warning = 1 ; + +to a .ptkdbrc file + +=back + +=head2 Data Menu + +=over + +=item Enter Expression + +When an expression is entered in the "Enter Expression:" text box, +selecting this item will enter the expression into the expression +list. Each time the debugger stops this expression will be evaluated +and its result updated in the list window. + +=item Delete Expression + + Deletes the highlighted expression in the expression window. + +=item Delete All Expressions + + Delete all expressions in the expression window. + +=item Expression Eval Window + +Pops up a two pane window. Expressions of virtually unlimitted length +can be entered in the top pane. Pressing the 'Eval' button will cause +the expression to be evaluated and its placed in the lower pane. If +Data::Dumper is available it will be used to format the resulting +text. Undo is enabled for the text in the upper pane. + +HINT: You can enter multiple expressions by separating them with commas. + +=item Use Data::Dumper for Eval Window + +Enables or disables the use of Data::Dumper for formatting the results +of expressions in the Eval window. + +=back + +=head2 Stack Menu + +Maintains a list of the current subroutine stack each time the +debugger stops. Selecting an item from this menu will set the text in +the code window to that particular subourtine entry point. + +=head2 Bookmarks Menu + +Maintains a list of bookmarks. The booksmarks are saved in ~/.ptkdb_bookmarks + +=over + +=item Add Bookmark + +Adds a bookmark to the bookmark list. + +=back + +=head1 Options + +Here is a list of the current active XResources options. Several of +these can be overridden with environmental variables. Resources can be +added to .Xresources or .Xdefaults depending on your X configuration. +To enable these resources you must either restart your X server or use +the xrdb -override resFile command. xfontsel can be used to select +fonts. + + /* + * Perl Tk Debugger XResources. + * Note... These resources are subject to change. + * + * Use 'xfontsel' to select different fonts. + * + * Append these resource to ~/.Xdefaults | ~/.Xresources + * and use xrdb -override ~/.Xdefaults | ~/.Xresources + * to activate them. + */ + /* Set Value to se to place scrollbars on the right side of windows + CAUTION: extra whitespace at the end of the line is causing + failures with Tk800.011. + + sw -> puts scrollbars on left, se puts scrollars on the right + + */ + ptkdb*scrollbars: sw + /* controls where the code pane is oriented, down the left side, or across the top */ + /* values can be set to left, right, top, bottom */ + ptkdb*codeside: left + + /* + * Background color for the balloon + * CAUTION: For certain versions of Tk trailing + * characters after the color produces an error + */ + ptkdb.frame2.frame1.rotext.balloon.background: green + ptkdb.frame2.frame1.rotext.balloon.font: fixed /* Hot Variable Balloon Font */ + + + ptkdb.frame*font: fixed /* Menu Bar */ + ptkdb.frame.menubutton.font: fixed /* File menu */ + ptkdb.frame2.frame1.rotext.font: fixed /* Code Pane */ + ptkdb.notebook.datapage.frame1.hlist.font: fixed /* Expression Notebook Page */ + + ptkdb.notebook.subspage*font: fixed /* Subroutine Notebook Page */ + ptkdb.notebook.brkptspage*entry.font: fixed /* Delete Breakpoint Buttons */ + ptkdb.notebook.brkptspage*button.font: fixed /* Breakpoint Expression Entries */ + ptkdb.notebook.brkptspage*button1.font: fixed /* Breakpoint Expression Entries */ + ptkdb.notebook.brkptspage*checkbutton.font: fixed /* Breakpoint Checkbuttons */ + ptkdb.notebook.brkptspage*label.font: fixed /* Breakpoint Checkbuttons */ + + ptkdb.toplevel.frame.textundo.font: fixed /* Eval Expression Entry Window */ + ptkdb.toplevel.frame1.text.font: fixed /* Eval Expression Results Window */ + ptkdb.toplevel.button.font: fixed /* "Eval..." Button */ + ptkdb.toplevel.button1.font: fixed /* "Clear Eval" Button */ + ptkdb.toplevel.button2.font: fixed /* "Clear Results" Button */ + ptkdb.toplevel.button3.font: fixed /* "Clear Dismiss" Button */ + + /* + * Background color for where the debugger has stopped + */ + ptkdb*stopcolor: blue + + /* + * Background color for set breakpoints + */ + ptkdb*breaktagcolor*background: yellow + ptkdb*disabledbreaktagcolor*background: white + /* + * Font for where the debugger has stopped + */ + ptkdb*stopfont: -*-fixed-bold-*-*-*-*-*-*-*-*-*-*-* + + /* + * Background color for the search tag + */ + ptkdb*searchtagcolor: green + +=head1 Environmental Variables + +=over 4 + +=item PTKDB_BRKPT_COLOR + +Sets the background color of a set breakpoint + +=item PTKDB_DISABLEDBRKPT_COLOR + +Sets the background color of a disabled breakpoint + +=item PTKDB_CODE_FONT + +Sets the font of the Text in the code pane. + +=item PTKDB_CODE_SIDE + +Sets which side the code pane is packed onto. Defaults to 'left'. +Can be set to 'left', 'right', 'top', 'bottom'. + +Overrides the Xresource ptkdb*codeside: I<side>. + +=item PTKDB_EXPRESSION_FONT + + Sets the font used in the expression notebook page. + +=item PTKDB_EVAL_FONT + + Sets the font used in the Expression Eval Window + +=item PTKDB_EVAL_DUMP_INDENT + + Sets the value used for Data::Dumper 'indent' setting. See man Data::Dumper + +=item PTKDB_SCROLLBARS_ONRIGHT + + A non-zero value Sets the scrollbars of all windows to be on the + right side of the window. Useful for Windows users using ptkdb in an + XWindows environment. + +=item PTKDB_LINENUMBER_FORMAT + +Sets the format of line numbers on the left side of the window. Default value is %05d. useful +if you have a script that contains more than 99999 lines. + +=item PTKDB_DISPLAY + +Sets the X display that the ptkdb window will appear on when invoked. Useful for debugging CGI +scripts on remote systems. + +=item PTKDB_BOOKMARKS_PATH + +Sets the path of the bookmarks file. Default is $ENV{'HOME'}/.ptkdb_bookmarks + +=item PTKDB_STOP_TAG_COLOR + +Sets the color that highlights the line where the debugger is stopped + +=back + +=head1 FILES + +=head2 .ptkdbrc + +If this file is present in ~/ or in the directory where perl is +invoked the file will be read and executed as a perl script before the +debugger makes its initial stop at startup. There are several 'api' +calls that can be used with such scripts. There is an internal +variable $DB::no_stop_at_start that may be set to non-zero to prevent +the debugger from stopping at the first line of the script. This is +useful for debugging CGI scripts. + +There is a system ptkdbrc file in $PREFIX/lib/perl5/$VERS/Devel/ptkdbrc + +=over 4 + +=item brkpt($fname, @lines) + +Sets breakspoints on the list of lines in $fname. A warning message +is generated if a line is not breakable. + +=item condbrkpt($fname, @($line, $expr) ) + +Sets conditional breakpoints in $fname on pairs of $line and $expr. A +warning message is generated if a line is not breakable. NOTE: the +validity of the expression will not be determined until execution of +that particular line. + +=item brkonsub(@names) + +Sets a breakpoint on each subroutine name listed. A warning message is +generated if a subroutine does not exist. NOTE: for a script with no +other packages the default package is "main::" and the subroutines +would be "main::mySubs". + +=item brkonsub_regex(@regExprs) + +Uses the list of @regExprs as a list of regular expressions to set breakpoints. Sets breakpoints +on every subroutine that matches any of the listed regular expressions. + +=item textTagConfigure(tag, ?option?, ?value?) + +Allows the user to format the text in the code window. The option +value pairs are the same values as the option for the tagConfigure +method documented in Tk::Text. Currently the following tags are in +effect: + + + 'code' Format for code in the text pane + 'stoppt' Format applied to the line where the debugger is currently stopped + 'breakableLine' Format applied to line numbers where the code is 'breakable' + 'nonbreakableLine' Format applied to line numbers where the code is no breakable + 'breaksetLine' Format applied to line numbers were a breakpoint is set + 'breakdisabledLine' Format applied to line numbers were a disabled breakpoint is set + 'search_tag' Format applied to text when located by a search. + + Example: + + # + # Turns off the overstrike on lines that you can't set a breakpoint on + # and makes the text color yellow. + # + textTagConfigure('nonbreakableLine', -overstrike => 0, -foreground => "yellow") ; + +=item add_exprs(@exprList) + +Add a list of expressions to the 'Exprs' window. NOTE: use the single +quote character \' to prevent the expression from being "evaluated" in +the string context. + + + Example: + + # + # Adds the $_ and @_ expressions to the active list + # + + add_exprs('$_', '@_') ; + +=back + +=head1 NOTES + +=head2 Debugging Other perlTk Applications + +ptkdb can be used to debug other perlTk applications if some cautions +are observed. Basically, do not click the mouse in the application's +window(s) when you've entered the debugger and do not click in the +debugger's window(s) while the application is running. Doing either +one is not necessarily fatal, but it can confuse things that are going +on and produce unexpected results. + +Be aware that most perlTk applications have a central event loop. +User actions, such as mouse clicks, key presses, window exposures, etc +will generate 'events' that the script will process. When a perlTk +application is running, its 'MainLoop' call will accept these events +and then dispatch them to appropriate callbacks associated with the +appropriate widgets. + +Ptkdb has its own event loop that runs whenever you've stopped at a +breakpoint and entered the debugger. However, it can accept events +that are generated by other perlTk windows and dispatch their +callbacks. The problem here is that the application is supposed to be +'stopped', and logically the application should not be able to process +events. + +A future version of ptkdb will have an extension that will 'filter' +events so that application events are not processed while the debugger +is active, and debugger events will not be processed while the target +script is active. + +=head2 Debugging CGI Scripts + +One advantage of ptkdb over the builtin debugger(-d) is that it can be +used to debug CGI perl scripts as they run on a web server. Be sure +that that your web server's perl instalation includes Tk. + +Change your + + #! /usr/local/bin/perl + +to + + #! /usr/local/bin/perl -d:ptkdb + +TIP: You can debug scripts remotely if you're using a unix based +Xserver and where you are authoring the script has an Xserver. The +Xserver can be another unix workstation, a Macintosh or Win32 platform +with an appropriate XWindows package. In your script insert the +following BEGIN subroutine: + + sub BEGIN { + $ENV{'DISPLAY'} = "myHostname:0.0" ; + } + +Be sure that your web server has permission to open windows on your +Xserver (see the xhost manpage). + +Access your web page with your browswer and 'submit' the script as +normal. The ptkdb window should appear on myHostname's monitor. At +this point you can start debugging your script. Be aware that your +browser may timeout waiting for the script to run. + +To expedite debugging you may want to setup your breakpoints in +advance with a .ptkdbrc file and use the $DB::no_stop_at_start +variable. NOTE: for debugging web scripts you may have to have the +.ptkdbrc file installed in the server account's home directory (~www) +or whatever username your webserver is running under. Also try +installing a .ptkdbrc file in the same directory as the target script. + +=head1 KNOWN PROBLEMS + +=over + +=item I<Breakpoint Controls> + +If the size of the right hand pane is too small the breakpoint controls +are not visible. The breakpoints are still there, the window may have +to be enlarged in order for them to be visible. + +=item Balloons and Tk400 + +The Balloons in Tk400 will not work with ptkdb. All other functions +are supported, but the Balloons require Tk800 or higher. + +=back + +=head1 AUTHOR + +Andrew E. Page, aep@world.std.com + +=head1 ACKNOWLEDGEMENTS + +Matthew Persico For suggestions, and beta testing. + +=cut + + +require 5.004 ; + + +## +## Perform a check to see if we have the Tk library, if not, attempt +## to load it for the user +## + +sub BEGIN { + +eval { +require Tk ; +} ; +if( $@ ) { +print << "__PTKDBTK_INSTALL__" ; +*** +*** The PerlTk library could not be found. Ptkdb requires the PerlTk library. +*** +Preferably Tk800.015 or better: + +In order to install this the following conditions must be met: + +1. You have to have access to a C compiler. +2. You must have sufficient permissions to install the libraries on your system. + +To install PerlTk: + +a Download the Tk library source from http://www.perl.com/CPAN/modules/by-category/08_User_Interfaces/Tk +b Uncompress the archive and run "perl Makefile.PL" +c run "make install" + + If this process completes successfully ptkdb should be operational now. + +We can attempt to run the CPAN module for you. This will, after some questions, download +and install the Tk library automatically. + +Would you like to run the CPAN module? (y/n) +__PTKDBTK_INSTALL__ + +my $answer = <STDIN> ; +chomp $answer ; +if( $answer =~ /y|yes/i) { + require CPAN ; + CPAN::install Tk ; +} # if + +} # if $@ + + +} # end of sub BEGIN + +use Tk 800 ; +use Data::Dumper ; + +require Tk::Dialog; +require Tk::TextUndo ; +require Tk::ROText; +require Tk::NoteBook ; +require Tk::HList ; +require Tk::Table ; + +use vars qw(@dbline) ; + +use Config ; +# +# Check to see if the package actually +# exists. If it does import the routines +# and return a true value ; +# +# NOTE: this needs to be above the 'BEGIN' subroutine, +# otherwise it will not have been compiled by the time +# that it is called by sub BEGIN. +# +sub check_avail { + my ($mod, @list) = @_ ; + + eval { + require $mod ; import $mod @list ; + } ; + + return 0 if $@ ; + return 1 ; + +} # end of check_avail + +sub BEGIN { + + $DB::on = 0 ; + + $DB::subroutine_depth = 0 ; # our subroutine depth counter + $DB::step_over_depth = -1 ; + + # + # the bindings and font specs for these operations have been placed here + # to make them accessible to people who might want to customize the + # operations. REF The 'bind.html' file, included in the perlTk FAQ has + # a fairly good explanation of the binding syntax. + # + + # + # These lists of key bindings will be applied + # to the "Step In", "Step Out", "Return" Commands + # + $Devel::ptkdb::pathSep = '\x00' ; + $Devel::ptkdb::pathSepReplacement = "\0x01" ; + + @Devel::ptkdb::step_in_keys = ( '<Shift-F9>', '<Alt-s>', '<Button-3>' ) ; # step into a subroutine + @Devel::ptkdb::step_over_keys = ( '<F9>', '<Alt-n>', '<Shift-Button-3>' ) ; # step over a subroutine + @Devel::ptkdb::return_keys = ( '<Alt-u>', '<Control-Button-3>' ) ; # return from a subroutine + @Devel::ptkdb::toggle_breakpt_keys = ( '<Alt-b>' ) ; # set or unset a breakpoint + + # Fonts used in the displays + + # + # NOTE: The environmental variable syntax here works like this: + # $ENV{'NAME'} accesses the environmental variable "NAME" + # + # $ENV{'NAME'} || 'string' results in $ENV{'NAME'} or 'string' if $ENV{'NAME'} is not defined. + # + # + + @Devel::ptkdb::button_font = $ENV{'PTKDB_BUTTON_FONT'} ? ( "-font" => $ENV{'PTKDB_CODE_FONT'} ) : () ; # font for buttons + @Devel::ptkdb::code_text_font = $ENV{'PTKDB_CODE_FONT'} ? ( "-font" => $ENV{'PTKDB_CODE_FONT'} ) : () ; + + @Devel::ptkdb::expression_text_font = $ENV{'PTKDB_EXPRESSION_FONT'} ? ( "-font" => $ENV{'PTKDB_EXPRESSION_FONT'} ) : () ; + @Devel::ptkdb::eval_text_font = $ENV{'PTKDB_EVAL_FONT'} ? ( -font => $ENV{'PTKDB_EVAL_FONT'} ) : () ; # text for the expression eval window + + $Devel::ptkdb::eval_dump_indent = $ENV{'PTKDB_EVAL_DUMP_INDENT'} || 1 ; + + # + # Windows users are more used to having scroll bars on the right. + # If they've set PTKDB_SCROLLBARS_ONRIGHT to a non-zero value + # this will configure our scrolled windows with scrollbars on the right + # + # this can also be done by setting: + # + # ptkdb*scrollbars: se + # + # in the .Xdefaults/.Xresources file on X based systems + # + if( exists $ENV{'PTKDB_SCROLLBARS_ONRIGHT'} && $ENV{'PTKDB_SCROLLBARS_ONRIGHT'} ) { + @Devel::ptkdb::scrollbar_cfg = ('-scrollbars' => 'se') ; + } + else { + @Devel::ptkdb::scrollbar_cfg = ( ) ; + } + + # + # Controls how far an expression result will be 'decomposed'. Setting it + # to 0 will take it down only one level, setting it to -1 will make it + # decompose it all the way down. However, if you have a situation where + # an element is a ref back to the array or a root of the array + # you could hang the debugger by making it recursively evaluate an expression + # + $Devel::ptkdb::expr_depth = -1 ; + $Devel::ptkdb::add_expr_depth = 1 ; # how much further to expand an expression when clicked + + $Devel::ptkdb::linenumber_format = $ENV{'PTKDB_LINENUMBER_FORMAT'} || "%05d " ; + $Devel::ptkdb::linenumber_length = 5 ; + + $Devel::ptkdb::linenumber_offset = length sprintf($Devel::ptkdb::linenumber_format, 0) ; + $Devel::ptkdb::linenumber_offset -= 1 ; + + # + # Check to see if "Data Dumper" is available + # if it is we can save breakpoints and other + # various "functions". This call will also + # load the subroutines needed. + # + $Devel::ptkdb::DataDumperAvailable = 1 ; # assuming that it is now + $Devel::ptkdb::useDataDumperForEval = $Devel::ptkdb::DataDumperAvailable ; + + # + # DB Options (things not directly involving the window) + # + + # Flag to disable us from intercepting $SIG{'INT'} + + $DB::sigint_disable = defined $ENV{'PTKDB_SIGINT_DISABLE'} && $ENV{'PTKDB_SIGINT_DISABLE'} ; +# +# Possibly for debugging perl CGI Web scripts on +# remote machines. +# + $ENV{'DISPLAY'} = $ENV{'PTKDB_DISPLAY'} if exists $ENV{'PTKDB_DISPLAY'} ; + + } # end of BEGIN + +sub DESTROY { + my ($self) = @_ ; + + $self->save_bookmarks($self->{BookMarksPath}) if $Devel::ptkdb::DataDumperAvailable && $self->{'bookmarks_changed'}; + + +} # end of ptkdb::DESTROY + +## +## subroutine provided to the user for initializing +## files in .ptkdbrc +## +sub brkpt { + my ($fName, @idx) = @_ ; + my($offset) ; + local(*dbline) = $main::{'_<' . $fName} ; + + $offset = $dbline[1] =~ /use\s+.*Devel::_?ptkdb/ ? 1 : 0 ; + + for( @idx ) { + if( !&DB::checkdbline($fName, $_ + $offset) ) { + my ($package, $filename, $line) = caller ; + print "$filename:$line: $fName line $_ is not breakable\n" ; + next ; + } + $DB::window->insertBreakpoint($fName, $_, 1) ; # insert a simple breakpoint + } +} # end of brkpt + +# +# Set conditional breakpoint(s) +# +sub condbrkpt { + my ($fname) = shift ; + my($offset) ; + local(*dbline) = $main::{'_<' . $fname} ; + + $offset = $dbline[1] =~ /use\s+.*Devel::_?ptkdb/ ? 1 : 0 ; + + while( @_ ) { # arg loop + my($index, $expr) = splice @_, 0, 2 ; # take args 2 at a time + + if( !&DB::checkdbline($fname, $index + $offset) ) { + my ($package, $filename, $line) = caller ; + print "$filename:$line: $fname line $index is not breakable\n" ; + next ; + } + $DB::window->insertBreakpoint($fname, $index, 1, $expr) ; # insert a simple breakpoint + } # end of arg loop + +} # end of conditionalbrkpt + +sub brkonsub { + my(@names) = @_ ; + + for( @names ) { + + # get the filename and line number range of the target subroutine + + if( !exists $DB::sub{$_} ) { + print "No subroutine $_. Try main::$_\n" ; + next ; + } + + $DB::sub{$_} =~ /(.*):([0-9]+)-([0-9]+)$/o ; # file name will be in $1, start line $2, end line $3 + + for( $2..$3 ) { + next unless &DB::checkdbline($1, $_) ; + $DB::window->insertBreakpoint($1, $_, 1) ; + last ; # only need the one breakpoint + } + } # end of name loop + +} # end of brkonsub + +# +# set breakpoints on subroutines matching a regular +# expression +# +sub brkonsub_regex { + my(@regexps) = @_ ; + my($regexp, @subList) ; + + # + # accumulate matching subroutines + # + foreach $regexp ( @regexps ) { + study $regexp ; + push @subList, grep /$regexp/, keys %DB::sub ; + } # end of brkonsub_regex + + brkonsub(@subList) ; # set breakpoints on matching subroutines + +} # end of brkonsub_regex + +# +# Allow the user Access to our tag configurations +# +sub textTagConfigure { + my ($tag, @config) = @_ ; + + $DB::window->{'text'}->tagConfigure($tag, @config) ; + +} # end of textTagConfigure + +## +## Change the tabs in the text field +## +sub setTabs { + + $DB::window->{'text'}->configure(-tabs => [ @_ ]) ; + +} + +# +# User .ptkdbrc API +# allows the user to add expressions to +# the expression list window. +# +sub add_exprs { + push @{$DB::window->{'expr_list'}}, map { 'expr' => $_, 'depth' => $Devel::ptkdb::expr_depth }, @_ ; +} # end of add_exprs + + +## +## register a subroutine reference that will be called whenever +## ptkdb sets up it's windows +## +sub register_user_window_init { + push @{$DB::window->{'user_window_init_list'}}, @_ ; +} # end of register_user_window_init + +## +## register a subroutine reference that will be called whenever +## ptkdb enters from code +## +sub register_user_DB_entry { + push @{$DB::window->{'user_window_DB_entry_list'}}, @_ ; +} # end of register_user_DB_entry + +sub get_notebook_widget { + return $DB::window->{'notebook'} ; +} # end of get_notebook_widget + + +# +# Run files provided by the user +# +sub do_user_init_files { + use vars qw($dbg_window) ; + local $dbg_window = shift ; + + eval { + do "$Config{'installprivlib'}/Devel/ptkdbrc" ; + } if -e "$Config{'installprivlib'}/Devel/ptkdbrc" ; + + if( $@ ) { + print "System init file $Config{'installprivlib'}/ptkdbrc failed: $@\n" ; + } + + eval { + do "$ENV{'HOME'}/.ptkdbrc" ; + } if exists $ENV{'HOME'} && -e "$ENV{'HOME'}/.ptkdbrc" ; + + if( $@ ) { + print "User init file $ENV{'HOME'}/.ptkdbrc failed: $@\n" ; + } + + eval { + do ".ptkdbrc" ; + } if -e ".ptkdbrc" ; + + if( $@ ) { + print "User init file .ptkdbrc failed: $@\n" ; + } + + &set_stop_on_warning() ; +} + +# +# Constructor for our Devel::ptkdb +# +sub new { + my($type) = @_ ; + my($self) = {} ; + + bless $self, $type ; + + # Current position of the executing program + + $self->{DisableOnLeave} = [] ; # List o' Widgets to disable when leaving the debugger + + $self->{current_file} = "" ; + $self->{current_line} = -1 ; # initial value indicating we haven't set our line/tag + $self->{window_pos_offset} = 10 ; # when we enter how far from the top of the text are we positioned down + $self->{search_start} = "0.0" ; + $self->{fwdOrBack} = 1 ; + $self->{BookMarksPath} = $ENV{'PTKDB_BOOKMARKS_PATH'} || "$ENV{'HOME'}/.ptkdb_bookmarks" || '.ptkdb_bookmarks' ; + + $self->{'expr_list'} = [] ; # list of expressions to eval in our window fields: {'expr'} The expr itself {'depth'} expansion depth + + + $self->{'brkPtCnt'} = 0 ; + $self->{'brkPtSlots'} = [] ; # open slots for adding breakpoints to the table + + $self->{'main_window'} = undef ; + + $self->{'user_window_init_list'} = [] ; + $self->{'user_window_DB_entry_list'} = [] ; + + $self->setup_main_window() ; + + return $self ; + +} # end of new + +sub setup_main_window { + my($self) = @_ ; + + # Main Window + + $self->{main_window} = MainWindow->new() ; + $self->{main_window}->geometry($ENV{'PTKDB_GEOMETRY'} || "800x600") ; + + $self->setup_options() ; # must be done after MainWindow and before other frames are setup + + $self->{main_window}->bind('<Control-c>', \&DB::dbint_handler) ; + + # + # Bind our 'quit' routine to a close command from the window manager (Alt-F4) + # + $self->{main_window}->protocol('WM_DELETE_WINDOW', sub { $self->close_ptkdb_window() ; } ) ; + + # Menu bar + + $self->setup_menu_bar() ; + + # + # setup Frames + # + # Setup our Code, Data, and breakpoints + + $self->setup_frames() ; + +} + + +# +# This supports the File -> Open menu item +# We create a new window and list all of the files +# that are contained in the program. We also +# pick up all of the perlTk files that are supporting +# the debugger. +# +sub DoOpen { + my $self = shift ; + my ($topLevel, $listBox, $frame, $selectedFile, @fList) ; + + # + # subroutine we call when we've selected a file + # + + my $chooseSub = sub { $selectedFile = $listBox->get('active') ; + print "attempting to open $selectedFile\n" ; + $DB::window->set_file($selectedFile, 0) ; + destroy $topLevel ; + } ; + + # + # Take the list the files and resort it. + # we put all of the local files first, and + # then list all of the system libraries. + # + @fList = sort { + # sort comparison function block + my $fa = substr($a, 0, 1) ; + my $fb = substr($b, 0, 1) ; + + return $a cmp $b if ($fa eq '/') && ($fb eq '/') ; + + return -1 if ($fb eq '/') && ($fa ne '/') ; + return 1 if ($fa eq '/' ) && ($fb ne '/') ; + + return $a cmp $b ; + + } grep s/^_<//, keys %main:: ; + + # + # Create a list box with all of our files + # to select from + # + $topLevel = $self->{main_window}->Toplevel(-title => "File Select", -overanchor => 'cursor') ; + + $listBox = $topLevel->Scrolled('Listbox', + @Devel::ptkdb::scrollbar_cfg, + @Devel::ptkdb::expression_text_font, + 'width' => 30)->pack(side => 'top', fill => 'both', -expand => 1) ; + + + # Bind a double click on the mouse button to the same action + # as pressing the Okay button + + $listBox->bind('<Double-Button-1>' => $chooseSub) ; + + $listBox->insert('end', @fList) ; + + $topLevel->Button( text => "Okay", -command => $chooseSub, @Devel::ptkdb::button_font, + )->pack(side => 'left', fill => 'both', -expand => 1) ; + + $topLevel->Button( text => "Cancel", @Devel::ptkdb::button_font, + -command => sub { destroy $topLevel ; } )->pack(side => 'left', fill => 'both', -expand => 1) ; +} # end of DoOpen + +sub do_tabs { + my($tabs_str) ; + my($w, $result, $tabs_cfg) ; + require Tk::Dialog ; + + $w = $DB::window->{'main_window'}->DialogBox(-title => "Tabs", -buttons => [qw/Okay Cancel/]) ; + + $tabs_cfg = $DB::window->{'text'}->cget(-tabs) ; + + $tabs_str = join " ", @$tabs_cfg if $tabs_cfg ; + + $w->add('Label', -text => 'Tabs:')->pack(-side => 'left') ; + + $w->add('Entry', -textvariable => \$tabs_str)->pack(-side => 'left')->selectionRange(0,'end') ; + + $result = $w->Show() ; + + return unless $result eq 'Okay' ; + + $DB::window->{'text'}->configure(-tabs => [ split /\s/, $tabs_str ]) ; +} + +sub close_ptkdb_window { + my($self) = @_ ; + + $DB::window->{'event'} = 'run' ; + $self->{current_file} = "" ; # force a file reset + $self->{'main_window'}->destroy ; + $self->{'main_window'} = undef ; +} + +sub setup_menu_bar { + my ($self) = @_ ; + my $mw = $self->{main_window} ; + my ($mb, $items) ; + + # + # We have menu items/features that are not available if the Data::DataDumper module + # isn't present. For any feature that requires it we add this option list. + # + my @dataDumperEnableOpt = ( state => 'disabled' ) unless $Devel::ptkdb::DataDumperAvailable ; + + + $self->{menu_bar} = $mw->Frame(-relief => 'raised', -borderwidth => '1')->pack(side => 'top', -fill => 'x') ; + + $mb = $self->{menu_bar} ; + + # file menu in menu bar + + $items = [ [ 'command' => 'About...', -command => sub { $self->DoAbout() ; } ], + "-", + + [ 'command' => 'Open', -accelerator => 'Alt+O', + -underline => 0, + -command => sub { $self->DoOpen() ; } ], + + [ 'command' => 'Save Config...', + -underline => 0, + -command => \&DB::SaveState, + @dataDumperEnableOpt ], + + [ 'command' => 'Restore Config...', + -underline => 0, + -command => \&DB::RestoreState, + @dataDumperEnableOpt ], + + [ 'command' => 'Goto Line...', + -underline => 0, + -accelerator => 'Alt-g', + -command => \&DB::RestoreState, + @dataDumperEnableOpt ] , + + [ 'command' => 'Find Text...', + -accelerator => 'Ctrl-f', + -underline => 0, + -command => sub { $self->FindText() ; } ], + + [ 'command' => "Tabs...", -command => \&do_tabs ], + + "-", + + [ 'command' => 'Close Window and Run', -accelerator => 'Alt+W', + -underline => 6, -command => sub { $self->close_ptkdb_window ; } ], + + [ 'command' => 'Quit...', -accelerator => 'Alt+Q', + -underline => 0, + -command => sub { exit } ] + ] ; + + + $mw->bind('<Alt-g>' => sub { $self->GotoLine() ; }) ; + $mw->bind('<Control-f>' => sub { $self->FindText() ; }) ; + $mw->bind('<Control-r>' => \&Devel::ptkdb::DoRestart) ; + $mw->bind('<Alt-q>' => sub { $self->{'event'} = 'quit' } ) ; + $mw->bind('<Alt-w>' => sub { $self->close_ptkdb_window ; }) ; + + $self->{file_menu_button} = $mb->Menubutton(text => 'File', + underline => 0, + -menuitems => $items + )->pack(side =>, 'left', + anchor => 'nw', + 'padx' => 2) ; + + # Control Menu + + my $runSub = sub { $DB::step_over_depth = -1 ; $self->{'event'} = 'run' } ; + + my $runToSub = sub { $DB::window->{'event'} = 'run' if $DB::window->SetBreakPoint(1) ; } ; + + my $stepOverSub = sub { &DB::SetStepOverBreakPoint(0) ; + $DB::single = 1 ; + $DB::window->{'event'} = 'step' ; + } ; + + + my $stepInSub = sub { + $DB::step_over_depth = -1 ; + $DB::single = 1 ; + $DB::window->{'event'} = 'step' ; } ; + + + my $returnSub = sub { + &DB::SetStepOverBreakPoint(-1) ; + $self->{'event'} = 'run' ; + } ; + + + $items = [ [ 'command' => 'Run', -accelerator => 'Alt+r', underline => 0, -command => $runSub ], + [ 'command' => 'Run To Here', -accelerator => 'Alt+t', -underline => 5, -command => $runToSub ], + '-', + [ 'command' => 'Set Breakpoint', -underline => 4, -command => sub { $self->SetBreakPoint ; }, -accelerator => 'Ctrl-b' ], + [ 'command' => 'Clear Breakpoint', -command => sub { $self->UnsetBreakPoint } ], + [ 'command' => 'Clear All Breakpoints', -underline => 6, -command => sub { + $DB::window->removeAllBreakpoints($DB::window->{current_file}) ; + &DB::clearalldblines() ; + } ], + '-', + [ 'command' => 'Step Over', -accelerator => 'Alt+N', -underline => 0, -command => $stepOverSub ], + [ 'command' => 'Step In', -accelerator => 'Alt+S', -underline => 5, -command => $stepInSub ], + [ 'command' => 'Return', -accelerator => 'Alt+U', -underline => 3, -command => $returnSub ], + '-', + [ 'command' => 'Restart...', -accelerator => 'Ctrl-r', -underline => 0, -command => \&Devel::ptkdb::DoRestart ], + '-', + [ 'checkbutton' => 'Stop On Warning', -variable => \$DB::ptkdb::stop_on_warning, -command => \&set_stop_on_warning ] + + + ] ; # end of control menu items + + + $self->{control_menu_button} = $mb->Menubutton(text => 'Control', + -underline => 0, + -menuitems => $items, + )->pack(side =>, 'left', + 'padx' => 2) ; + + + $mw->bind('<Alt-r>' => $runSub) ; + $mw->bind('<Alt-t>', $runToSub) ; + $mw->bind('<Control-b>', sub { $self->SetBreakPoint ; }) ; + + for( @Devel::ptkdb::step_over_keys ) { + $mw->bind($_ => $stepOverSub ); + } + + for( @Devel::ptkdb::step_in_keys ) { + $mw->bind($_ => $stepInSub ); + } + + for( @Devel::ptkdb::return_keys ) { + $mw->bind($_ => $returnSub ); + } + + # Data Menu + + $items = [ [ 'command' => 'Enter Expression', -accelerator => 'Alt+E', -command => sub { $self->EnterExpr() } ], + [ 'command' => 'Delete Expression', -accelerator => 'Ctrl+D', -command => sub { $self->deleteExpr() } ], + [ 'command' => 'Delete All Expressions', -command => sub { + $self->deleteAllExprs() ; + $self->{'expr_list'} = [] ; # clears list by dropping ref to it, replacing it with a new one + } ], + '-', + [ 'command' => 'Expression Eval Window...', -accelerator => 'F8', -command => sub { $self->setupEvalWindow() ; } ], + [ 'checkbutton' => "Use DataDumper for Eval Window?", -variable => \$Devel::ptkdb::useDataDumperForEval, @dataDumperEnableOpt ] + ] ; + + + $self->{data_menu_button} = $mb->Menubutton(text => 'Data', -menuitems => $items, + underline => 0, + )->pack(side => 'left', + 'padx' => 2) ; + + $mw->bind('<Alt-e>' => sub { $self->EnterExpr() } ) ; + $mw->bind('<Control-d>' => sub { $self->deleteExpr() } ); + $mw->bind('<F8>', sub { $self->setupEvalWindow() ; }) ; + # + # Stack menu + # + $self->{stack_menu} = $mb->Menubutton(text => 'Stack', + underline => 2, + )->pack(side => 'left', + 'padx' => 2) ; + + # + # Bookmarks menu + # + $self->{bookmarks_menu} = $mb->Menubutton('text' => 'Bookmarks', + underline => 0, + @dataDumperEnableOpt + )->pack(-side => 'left', + 'padx' => 2) ; + $self->setup_bookmarks_menu() ; + + # + # Windows Menu + # + my($bsub) = sub { $self->{'text'}->focus() } ; + my($csub) = sub { $self->{'quick_entry'}->focus() } ; + my($dsub) = sub { $self->{'entry'}->focus() } ; + + $items = [ [ 'command' => 'Code Pane', -accelerator => 'Alt+0', -command => $bsub ], + [ 'command' => 'Quick Entry', -accelerator => 'F9', -command => $csub ], + [ 'command' => 'Expr Entry', -accelerator => 'F11', -command => $dsub ] + ] ; + + $mb->Menubutton('text' => 'Windows', -menuitems => $items + )->pack(-side => 'left', + -padx => 2) ; + + $mw->bind('<Alt-0>', $bsub) ; + $mw->bind('<F9>', $csub) ; + $mw->bind('<F11>', $dsub) ; + + # + # Bar for some popular controls + # + + $self->{button_bar} = $mw->Frame()->pack(side => 'top') ; + + $self->{stepin_button} = $self->{button_bar}->Button(-text, => "Step In", @Devel::ptkdb::button_font, + -command => $stepInSub) ; + $self->{stepin_button}->pack(-side => 'left') ; + + $self->{stepover_button} = $self->{button_bar}->Button(-text, => "Step Over", @Devel::ptkdb::button_font, + -command => $stepOverSub) ; + $self->{stepover_button}->pack(-side => 'left') ; + + $self->{return_button} = $self->{button_bar}->Button(-text, => "Return", @Devel::ptkdb::button_font, + -command => $returnSub) ; + $self->{return_button}->pack(-side => 'left') ; + + $self->{run_button} = $self->{button_bar}->Button(-background => 'green', -text, => "Run", @Devel::ptkdb::button_font, + -command => $runSub) ; + $self->{run_button}->pack(-side => 'left') ; + + $self->{run_to_button} = $self->{button_bar}->Button(-text, => "Run To", @Devel::ptkdb::button_font, + -command => $runToSub) ; + $self->{run_to_button}->pack(-side => 'left') ; + + $self->{breakpt_button} = $self->{button_bar}->Button(-text, => "Break", @Devel::ptkdb::button_font, + -command => sub { $self->SetBreakPoint ; } ) ; + $self->{breakpt_button}->pack(-side => 'left') ; + + push @{$self->{DisableOnLeave}}, @$self{'stepin_button', 'stepover_button', 'return_button', 'run_button', 'run_to_button', 'breakpt_button'} ; + +} # end of setup_menu_bar + +sub edit_bookmarks { + my ($self) = @_ ; + + my ($top) = $self->{main_window}->Toplevel(-title => "Edit Bookmarks") ; + + my $list = $top->Scrolled('Listbox', -selectmode => 'multiple')->pack(-side => 'top', -fill => 'both', -expand => 1) ; + + my $deleteSub = sub { + my $cnt = 0 ; + for( $list->curselection ) { + $list->delete($_ - $cnt++) ; + } + } ; + + my $okaySub = sub { + $self->{'bookmarks'} = [ $list->get(0, 'end') ] ; # replace the bookmarks + } ; + + my $frm = $top->Frame()->pack(-side => 'top', -fill => 'x', -expand => 1 ) ; + + my $deleteBtn = $frm->Button(-text => 'Delete', -command => $deleteSub)->pack(-side => 'left', -fill => 'x', -expand => 1 ) ; + my $cancelBtn = $frm->Button(-text => 'Cancel', -command => sub { destroy $top ; })->pack(-side =>'left', -fill => 'x', -expand => 1 ) ; + my $dismissBtn = $frm->Button(-text => 'Okay', -command => $okaySub)->pack(-side => 'left', -fill => 'x', -expand => 1 ) ; + + $list->insert('end', @{$self->{'bookmarks'}}) ; + +} # end of edit_bookmarks + +sub setup_bookmarks_menu { + my ($self) = @_ ; + + # + # "Add bookmark" item + # + my $bkMarkSub = sub { $self->add_bookmark() ; } ; + + $self->{'bookmarks_menu'}->command(-label => "Add Bookmark", + -accelerator => 'Alt+k', + -command => $bkMarkSub + ) ; + + $self->{'main_window'}->bind('<Alt-k>', $bkMarkSub) ; + + $self->{'bookmarks_menu'}->command(-label => "Edit Bookmarks", + -command => sub { $self->edit_bookmarks() } ) ; + + $self->{'bookmarks_menu'}->separator() ; + + # + # Check to see if there is a bookmarks file + # + return unless -e $self->{BookMarksPath} && -r $self->{BookMarksPath} ; + + use vars qw($ptkdb_bookmarks) ; + local($ptkdb_bookmarks) ; # ref to hash of bookmark entries + + do $self->{BookMarksPath} ; # eval the file + + $self->add_bookmark_items(@$ptkdb_bookmarks) ; + +} # end of setup_bookmarks_menu + +# +# $item = "$fname:$lineno" +# +sub add_bookmark_items { + my($self, @items) = @_ ; + my($menu) = ( $self->{'bookmarks_menu'} ) ; + + $self->{'bookmarks_changed'} = 1 ; + + for( @items ) { + my $item = $_ ; + $menu->command( -label => $_, + -command => sub { $self->bookmark_cmd($item) }) ; + push @{$self->{'bookmarks'}}, $item ; + } +} # end of add_bookmark_item + +# +# Invoked from the "Add Bookmark" command +# +sub add_bookmark { + my($self) = @_ ; + + my $line = $self->get_lineno() ; + my $fname = $self->{'current_file'} ; + $self->add_bookmark_items("$fname:$line") ; + +} # end of add_bookmark + +# +# Command executed when someone selects +# a bookmark +# +sub bookmark_cmd { + my ($self, $item) = @_ ; + + $item =~ /(.*):([0-9]+)$/ ; + + $self->set_file($1,$2) ; + +} # end of bookmark_cmd + +sub save_bookmarks { + my($self, $pathName) = @_ ; + + return unless $Devel::ptkdb::DataDumperAvailable ; # we can't save without the data dumper + local(*F) ; + + eval { + open F, ">$pathName" || die "open failed" ; + my $d = Data::Dumper->new([ $self->{'bookmarks'} ], + [ 'ptkdb_bookmarks' ]) ; + + $d->Indent(2) ; # make it more editable for people + + my $str ; + if( $d->can('Dumpxs') ) { + $str = $d->Dumpxs() ; + } + else { + $str = $d->Dump() ; + } + + print F $str || die "outputing bookmarks failed" ; + close(F) ; + } ; + + if( $@ ) { + $self->DoAlert("Couldn't save bookmarks file $@") ; + return ; + } + +} # end of save_bookmarks + +# +# This is our callback from a double click in our +# HList. A click in an expanded item will delete +# the children beneath it, and the next time it +# updates, it will only update that entry to that +# depth. If an item is 'unexpanded' such as +# a hash or a list, it will expand it one more +# level. How much further an item is expanded is +# controled by package variable $Devel::ptkdb::add_expr_depth +# +sub expr_expand { + my ($path) = @_ ; + my $hl = $DB::window->{'data_list'} ; + my ($parent, $root, $index, @children, $depth) ; + + $parent = $path ; + $root = $path ; + $depth = 0 ; + + for( $root = $path ; defined $parent && $parent ne "" ; $parent = $hl->infoParent($root) ) { + $root = $parent ; + $depth += 1 ; + } #end of root search + + # + # Determine the index of the root of our expression + # + $index = 0 ; + for( @{$DB::window->{'expr_list'}} ) { + last if $_->{'expr'} eq $root ; + $index += 1 ; + } + + # + # if we have children we're going to delete them + # + + @children = $hl->infoChildren($path) ; + + if( scalar @children > 0 ) { + + $hl->deleteOffsprings($path) ; + + $DB::window->{'expr_list'}->[$index]->{'depth'} = $depth - 1 ; # adjust our depth + } + else { + # + # Delete the existing tree and insert a new one + # + $hl->deleteEntry($root) ; + $hl->add($root, -at => $index) ; + $DB::window->{'expr_list'}->[$index]->{'depth'} += $Devel::ptkdb::add_expr_depth ; + # + # Force an update on our expressions + # + $DB::window->{'event'} = 'update' ; + } +} # end of expr_expand + +sub line_number_from_coord { + my($txtWidget, $coord) = @_ ; + my($index) ; + + $index = $txtWidget->index($coord) ; + + # index is in the format of lineno.column + + $index =~ /([0-9]*)\.([0-9]*)/o ; + + # + # return a list of (col, line). Why + # backwards? + # + + return ($2 ,$1) ; + +} # end of line_number_from_coord + +# +# It may seem as if $txtWidget and $self are +# erroneously reversed, but this is a result +# of the calling syntax of the text-bind callback. +# +sub set_breakpoint_tag { + my($txtWidget, $self, $coord, $value) = @_ ; + my($idx) ; + + $idx = line_number_from_coord($txtWidget, $coord) ; + + $self->insertBreakpoint($self->{'current_file'}, $idx, $value) ; + +} # end of set_breakpoint_tag + +sub clear_breakpoint_tag { + my($txtWidget, $self, $coord) = @_ ; + my($idx) ; + + $idx = line_number_from_coord($txtWidget, $coord) ; + + $self->removeBreakpoint($self->{'current_file'}, $idx) ; + +} # end of clear_breakpoint_tag + +sub change_breakpoint_tag { + my($txtWidget, $self, $coord, $value) = @_ ; + my($idx, $brkPt, @tagSet) ; + + $idx = line_number_from_coord($txtWidget, $coord) ; + + # + # Change the value of the breakpoint + # + @tagSet = ( "$idx.0", "$idx.$Devel::ptkdb::linenumber_length" ) ; + + $brkPt = &DB::getdbline($self->{'current_file'}, $idx + $self->{'line_offset'}) ; + return unless $brkPt ; + + # + # Check the breakpoint tag + # + + if ( $txtWidget ) { + $txtWidget->tagRemove('breaksetLine', @tagSet ) ; + $txtWidget->tagRemove('breakdisabledLine', @tagSet ) ; + } + + $brkPt->{'value'} = $value ; + + if ( $txtWidget ) { + if ( $brkPt->{'value'} ) { + $txtWidget->tagAdd('breaksetLine', @tagSet ) ; + } + else { + $txtWidget->tagAdd('breakdisabledLine', @tagSet ) ; + } + } + +} # end of change_breakpoint_tag + +# +# God Forbid anyone comment something complex and tightly optimized. +# +# We can get a list of the subroutines from the interpreter +# by querrying the *DB::sub typeglob: keys %DB::sub +# +# The list appears broken down by module: +# +# main::BEGIN +# main::mySub +# main::otherSub +# Tk::Adjuster::Mapped +# Tk::Adjuster::Packed +# Tk::Button::BEGIN +# Tk::Button::Enter +# +# We would like to break this list down into a heirarchy. +# +# main Tk +# | | | | +# BEGIN mySub OtherSub | | +# Adjuster Button +# | | | | +# Mapped Packed BEGIN Enter +# +# +# We translate this list into a heirarchy of hashes(say three times fast). +# We take each entry and split it into elements. Each element is a leaf in the tree. +# We traverse the tree with the inner for loop. +# With each branch we check to see if it already exists or +# we create it. When we reach the last element, this becomes our entry. +# + +# +# An incoming list is potentially 'large' so we +# pass in the ref to it instead. +# +# New entries can be inserted by providing a $topH +# hash ref to an existing tree. +# +sub tree_split { + my ($listRef, $separator, $topH) = @_ ; + my ($h, $list_elem) ; + + $topH = {} unless $topH ; + + foreach $list_elem ( @$listRef ) { + $h = $topH ; + for( split /$separator/o, $list_elem ) { # Tk::Adjuster::Mapped -> ( Tk Adjuster Mapped ) + $h->{$_} or $h->{$_} = {} ; # either we have an entry for this OR we create one + $h = $h->{$_} ; + } + @$h{'name', 'path'} = ($_, $list_elem) ; # the last leaf is our entry + } # end of tree_split loop + + return $topH ; + +} # end of tree_split + +# +# callback executed when someone double clicks +# an entry in the 'Subs' Tk::Notebook page. +# +sub sub_list_cmd { + my ($self, $path) = @_ ; + my ($h) ; + my $sub_list = $self->{'sub_list'} ; + + if ( $sub_list->info('children', $path) ) { + # + # Delete the children + # + $sub_list->deleteOffsprings($path) ; + return ; + } + + # + # split the path up into elements + # end descend through the tree. + # + $h = $Devel::ptkdb::subs_tree ; + for ( split /\./o, $path ) { + $h = $h->{$_} ; # next level down + } + + # + # if we don't have a 'name' entry we + # still have levels to decend through. + # + if ( !exists $h->{'name'} ) { + # + # Add the next level paths + # + for ( sort keys %$h ) { + + if ( exists $h->{$_}->{'path'} ) { + $sub_list->add($path . '.' . $_, -text => $h->{$_}->{'path'}) ; + } + else { + $sub_list->add($path . '.' . $_, -text => $_) ; + } + } + return ; + } + + $DB::sub{$h->{'path'}} =~ /(.*):([0-9]+)-[0-9]+$/o ; # file name will be in $1, line number will be in $2 */ + + $self->set_file($1, $2) ; + +} # end of sub_list_cmd + +sub fill_subs_page { + my($self) = @_ ; + + $self->{'sub_list'}->delete('all') ; # clear existing entries + + my @list = keys %DB::sub ; + + $Devel::ptkdb::subs_tree = tree_split(\@list, "::") ; + + # setup to level of list + + for ( sort keys %$Devel::ptkdb::subs_tree ) { + $self->{'sub_list'}->add($_, -text => $_) ; + } # end of top level loop +} + +sub setup_subs_page { + my($self) = @_ ; + + $self->{'subs_page_activated'} = 1 ; + + $self->{'sub_list'} = $self->{'subs_page'}->Scrolled('HList', -command => sub { $self->sub_list_cmd(@_) ; } ) ; + + $self->fill_subs_page() ; + + $self->{'sub_list'}->pack(side => 'left', fill => 'both', expand => 1 + ) ; + + $self->{'subs_list_cnt'} = scalar keys %DB::sub ; + + +} # end of setup_subs_page + +sub setup_search_panel { + my ($self, $parent, @packArgs) = @_ ; + my ($frm, $srchBtn, $regexBtn, $entry) ; + + $frm = $parent->Frame() ; + + $frm->Button(-text => 'Goto', -command => sub { $self->DoGoto($entry) })->pack(side => 'left') ; + $srchBtn = $frm->Button(-text => 'Search', -command => sub { $self->FindSearch($entry, $srchBtn, 0) ; } + )->pack(side => 'left' ) ; + + $regexBtn = $frm->Button(-text => 'Regex', + -command => sub { $self->FindSearch($entry, $regexBtn, 1) ; } + )->pack(side => 'left', + ) ; + + + $entry = $frm->Entry(width => 50)->pack(side => 'left', fill => 'both', expand => 1) ; + + $frm->pack(@packArgs) ; + +} # end of setup search_panel + +sub setup_breakpts_page { + my ($self) = @_ ; + require Tk::Table ; + + $self->{'breakpts_page'} = $self->{'notebook'}->add("brkptspage", -label => "BrkPts") ; + + $self->{'breakpts_table'} = $self->{'breakpts_page'}->Table(-columns => 1, -scrollbars => 'se')-> + pack(side => 'top', fill => 'both', expand => 1 + ) ; + + $self->{'breakpts_table_data'} = { } ; # controls addressed by "fname:lineno" + +} # end of setup_breakpts_page + +sub setup_frames { + my ($self) = @_ ; + my $mw = $self->{'main_window'} ; + my ($txt, $place_holder, $frm) ; + require Tk::ROText ; + require Tk::NoteBook ; + require Tk::HList ; + require Tk::Balloon ; + require Tk::Adjuster ; + + # get the side that we want to put the code pane on + + my($codeSide) = $ENV{'PTKDB_CODE_SIDE'} || $mw->optionGet("codeside", "") || 'left' ; + + + + $mw->update ; # force geometry manager to map main_window + $frm = $mw->Frame(-width => $mw->reqwidth()) ; # frame for our code pane and search controls + + $self->setup_search_panel($frm, side => 'top', fill => 'x') ; + + # + # Text window for the code of our currently viewed file + # + $self->{'text'} = $frm->Scrolled('ROText', + -wrap => "none", + @Devel::ptkdb::scrollbar_cfg, + @Devel::ptkdb::code_text_font + ) ; + + + $txt = $self->{'text'} ; + for( $txt->children ) { + next unless (ref $_) =~ /ROText$/ ; + $self->{'text'} = $_ ; + last ; + } + + $frm->packPropagate(0) ; + $txt->packPropagate(0) ; + + $frm->packAdjust(side => $codeSide, fill => 'both', expand => 1) ; + $txt->pack(side => 'left', fill => 'both', expand => 1) ; + + # $txt->form(-top => [ $self->{'menu_bar'} ], -left => '%0', -right => '%50') ; + # $frm->form(-top => [ $self->{'menu_bar'} ], -left => '%50', -right => '%100') ; + + $self->configure_text() ; + + # + # Notebook + # + + $self->{'notebook'} = $mw->NoteBook() ; + $self->{'notebook'}->packPropagate(0) ; + $self->{'notebook'}->pack(side => $codeSide, fill => 'both', -expand => 1) ; + + # + # an hlist for the data entries + # + $self->{'data_page'} = $self->{'notebook'}->add("datapage", -label => "Exprs") ; + + # + # frame, entry and label for quick expressions + # + my $frame = $self->{'data_page'}->Frame()->pack(side => 'top', fill => 'x') ; + + my $label = $frame->Label('text' => "Quick Expr:")->pack(side => 'left') ; + + $self->{'quick_entry'} = $frame->Entry()->pack(side => 'left', fill => 'x', -expand => 1) ; + + $self->{'quick_entry'}->bind('<Return>', sub { $self->QuickExpr() ; } ) ; + + + # + # Entry widget for expressions and breakpoints + # + $frame = $self->{'data_page'}->Frame()->pack(side => 'top', fill => 'x') ; + + $label = $frame->Label('text' => "Enter Expr:")->pack(side => 'left') ; + + $self->{'entry'} = $frame->Entry()->pack(side => 'left', fill => 'x', -expand => 1) ; + + $self->{'entry'}->bind('<Return>', sub { $self->EnterExpr() }) ; + + # + # Hlist for data expressions + # + + + $self->{data_list} = $self->{'data_page'}->Scrolled('HList', + @Devel::ptkdb::scrollbar_cfg, + separator => $Devel::ptkdb::pathSep, + @Devel::ptkdb::expression_text_font, + -command => \&Devel::ptkdb::expr_expand, + -selectmode => 'multiple' + ) ; + + $self->{data_list}->pack(side => 'top', fill => 'both', expand => 1 + ) ; + + + $self->{'subs_page_activated'} = 0 ; + $self->{'subs_page'} = $self->{'notebook'}->add("subspage", -label => "Subs", -createcmd => sub { $self->setup_subs_page }) ; + + $self->setup_breakpts_page() ; + +} # end of setup_frames + + + +sub configure_text { + my($self) = @_ ; + my($txt, $mw) = ($self->{'text'}, $self->{'main_window'}) ; + my($place_holder) ; + + $self->{'expr_balloon'} = $txt->Balloon(); + $self->{'balloon_expr'} = ' ' ; # initial expression + + # If Data::Dumper is available setup a dumper for the balloon + + if ( $Devel::ptkdb::DataDumperAvailable ) { + $self->{'balloon_dumper'} = new Data::Dumper([$place_holder]) ; + $self->{'balloon_dumper'}->Terse(1) ; + $self->{'balloon_dumper'}->Indent($Devel::ptkdb::eval_dump_indent) ; + + $self->{'quick_dumper'} = new Data::Dumper([$place_holder]) ; + $self->{'quick_dumper'}->Terse(1) ; + $self->{'quick_dumper'}->Indent(0) ; + } + + $self->{'expr_ballon_msg'} = ' ' ; + + $self->{'expr_balloon'}->attach($txt, -initwait => 300, + -msg => \$self->{'expr_ballon_msg'}, + -balloonposition => 'mouse', + -postcommand => \&Devel::ptkdb::balloon_post, + -motioncommand => \&Devel::ptkdb::balloon_motion ) ; + + # tags for the text + + my @stopTagConfig = ( -foreground => 'white', -background => $mw->optionGet("stopcolor", "background") || $ENV{'PTKDB_STOP_TAG_COLOR'} || 'blue' ) ; + + my $stopFnt = $mw->optionGet("stopfont", "background") || $ENV{'PTKDB_STOP_TAG_FONT'} ; + push @stopTagConfig, ( -font => $stopFnt ) if $stopFnt ; # user may not have specified a font, if not, stay with the default + + $txt->tagConfigure('stoppt', @stopTagConfig) ; + $txt->tagConfigure('search_tag', "-background" => $mw->optionGet("searchtagcolor", "background") || "green") ; + + $txt->tagConfigure("breakableLine", -overstrike => 0) ; + $txt->tagConfigure("nonbreakableLine", -overstrike => 1) ; + $txt->tagConfigure("breaksetLine", -background => $mw->optionGet("breaktagcolor", "background") || $ENV{'PTKDB_BRKPT_COLOR'} || 'red') ; + $txt->tagConfigure("breakdisabledLine", -background => $mw->optionGet("disabledbreaktagcolor", "background") || $ENV{'PTKDB_DISABLEDBRKPT_COLOR'} || 'green') ; + + $txt->tagBind("breakableLine", '<Button-1>', [ \&Devel::ptkdb::set_breakpoint_tag, $self, Ev('@'), 1 ] ) ; + $txt->tagBind("breakableLine", '<Shift-Button-1>', [ \&Devel::ptkdb::set_breakpoint_tag, $self, Ev('@'), 0 ] ) ; + + $txt->tagBind("breaksetLine", '<Button-1>', [ \&Devel::ptkdb::clear_breakpoint_tag, $self, Ev('@') ] ) ; + $txt->tagBind("breaksetLine", '<Shift-Button-1>', [ \&Devel::ptkdb::change_breakpoint_tag, $self, Ev('@'), 0 ] ) ; + + $txt->tagBind("breakdisabledLine", '<Button-1>', [ \&Devel::ptkdb::clear_breakpoint_tag, $self, Ev('@') ] ) ; + $txt->tagBind("breakdisabledLine", '<Shift-Button-1>', [ \&Devel::ptkdb::change_breakpoint_tag, $self, Ev('@'), 1 ] ) ; + +} # end of configure_text + + +sub setup_options { + my ($self) = @_ ; + my $mw = $self->{main_window} ; + + return unless $mw->can('appname') ; + + $mw->appname("ptkdb") ; + $mw->optionAdd("stopcolor" => 'cyan', 60 ) ; + $mw->optionAdd("stopfont" => 'fixed', 60 ) ; + $mw->optionAdd("breaktag" => 'red', 60 ) ; + $mw->optionAdd("searchtagcolor" => 'green') ; + + $mw->optionClear ; # necessary to reload xresources + +} # end of setup_options + +sub DoAlert { + my($self, $msg, $title) = @_ ; + my($dlg) ; + my $okaySub = sub { + destroy $dlg ; + } ; + + $dlg = $self->{main_window}->Toplevel(-title => $title || "Alert", -overanchor => 'cursor') ; + + $dlg->Label( 'text' => $msg )->pack( side => 'top' ) ; + + $dlg->Button( 'text' => "Okay", -command => $okaySub )->pack( side => 'top' )->focus ; + $dlg->bind('<Return>', $okaySub) ; + +} # end of DoAlert + +sub simplePromptBox { + my ($self, $title, $defaultText, $okaySub, $cancelSub) = @_ ; + my ($top, $entry, $okayBtn) ; + + $top = $self->{main_window}->Toplevel(-title => $title, -overanchor => 'cursor' ) ; + + $Devel::ptkdb::promptString = $defaultText ; + + $entry = $top->Entry('-textvariable' => 'Devel::ptkdb::promptString')->pack('side' => 'top', fill => 'both', -expand => 1) ; + + + $okayBtn = $top->Button( text => "Okay", @Devel::ptkdb::button_font, -command => sub { &$okaySub() ; $top->destroy ;} + )->pack(side => 'left', fill => 'both', -expand => 1) ; + + $top->Button( text => "Cancel", -command => sub { &$cancelSub() if $cancelSub ; $top->destroy() }, @Devel::ptkdb::button_font, + )->pack(side => 'left', fill => 'both', -expand => 1) ; + + $entry->icursor('end') ; + + $entry->selectionRange(0, 'end') if $entry->can('selectionRange') ; # some win32 Tk installations can't do this + + $entry->focus() ; + + return $top ; + +} # end of simplePromptBox + +sub get_entry_text { + my($self) = @_ ; + + return $self->{entry}->get() ; # get the text in the entry +} # end of get_entry_text + + +# +# Clear any text that is in the entry field. If there +# was any text in that field return it. If there +# was no text then return any selection that may be active. +# +sub clear_entry_text { + my($self) = @_ ; + my $str = $self->{'entry'}->get() ; + $self->{'entry'}->delete(0, 'end') ; + + # + # No String + # Empty String + # Or a string that is only whitespace + # + if( !$str || $str eq "" || $str =~ /^\s+$/ ) { + # + # If there is no string or the string is just white text + # Get the text in the selction( if any) + # + if( $self->{'text'}->tagRanges('sel') ) { # check to see if 'sel' tag exists (return undef value) + $str = $self->{'text'}->get("sel.first", "sel.last") ; # get the text between the 'first' and 'last' point of the sel (selection) tag + } + # If still no text, bring the focus to the entry + elsif( !$str || $str eq "" || $str =~ /^\s+$/ ) { + $self->{'entry'}->focus() ; + $str = "" ; + } + } + # + # Erase existing text + # + return $str ; +} # end of clear_entry_text + +sub brkPtCheckbutton { + my ($self, $fname, $idx, $brkPt) = @_ ; + my ($widg) ; + + change_breakpoint_tag($self->{'text'}, $self, "$idx.0", $brkPt->{'value'}) if $fname eq $self->{'current_file'} ; + +} # end of brkPtCheckbutton + +# +# insert a breakpoint control into our breakpoint list. +# returns a handle to the control +# +# Expression, if defined, is to be evaluated at the breakpoint +# and execution stopped if it is non-zero/defined. +# +# If action is defined && True then it will be evalled +# before continuing. +# +sub insertBreakpoint { + my ($self, $fname, @brks) = @_ ; + my ($btn, $cnt, $item) ; + + my($offset) ; + local(*dbline) = $main::{'_<' . $fname} ; + + $offset = $dbline[1] =~ /use\s+.*Devel::_?ptkdb/ ? 1 : 0 ; + + while( @brks ) { + my($index, $value, $expression) = splice @brks, 0, 3 ; # take args 3 at a time + + my $brkPt = {} ; + my $txt = &DB::getdbtextline($fname, $index) ; + @$brkPt{'type', 'line', 'expr', 'value', 'fname', 'text'} = + ('user', $index, $expression, $value, $fname, "$txt") ; + + &DB::setdbline($fname, $index + $offset, $brkPt) ; + $self->add_brkpt_to_brkpt_page($brkPt) ; + + next unless $fname eq $self->{'current_file'} ; + + $self->{'text'}->tagRemove("breakableLine", "$index.0", "$index.$Devel::ptkdb::linenumber_length") ; + $self->{'text'}->tagAdd($value ? "breaksetLine" : "breakdisabledLine", "$index.0", "$index.$Devel::ptkdb::linenumber_length") ; + } # end of loop +} # end of insertBreakpoint + +sub add_brkpt_to_brkpt_page { + my($self, $brkPt) = @_ ; + my($btn, $fname, $index, $frm, $upperFrame, $lowerFrame) ; + my ($row, $btnName, $width) ; + # + # Add the breakpoint to the breakpoints page + # + ($fname, $index) = @$brkPt{'fname', 'line'} ; + return if exists $self->{'breakpts_table_data'}->{"$fname:$index"} ; + $self->{'brkPtCnt'} += 1 ; + + $btnName = $fname ; + $btnName =~ s/.*\/([^\/]*)$/$1/o ; + + # take the last leaf of the pathname + + $frm = $self->{'breakpts_table'}->Frame(-relief => 'raised') ; + $upperFrame = $frm->Frame()->pack('side' => 'top', '-fill' => 'x', 'expand' => 1) ; + + + $btn = $upperFrame->Checkbutton(-text => "$btnName:$index", + -variable => \$brkPt->{'value'}, # CAUTION value tracking + -command => sub { $self->brkPtCheckbutton($fname, $index, $brkPt) }) ; + + $btn->pack(side => 'left') ; + + $btn = $upperFrame->Button(-text => "Delete", -command => sub { $self->removeBreakpoint($fname, $index) ; } ) ; + $btn->pack('side' => 'left', -fill => 'x', -expand => 1) ; + + $btn = $upperFrame->Button(-text => "Goto", -command => sub { $self->set_file($fname, $index) ; } ) ; + $btn->pack('side' => 'left', -fill => 'x', -expand => 1) ; + + $lowerFrame = $frm->Frame()->pack('side' => 'top', '-fill' => 'x', 'expand' => 1) ; + + $lowerFrame->Label(-text => "Cond:")->pack('side' => 'left') ; + + $btn = $lowerFrame->Entry(-textvariable => \$brkPt->{'expr'}) ; + $btn->pack('side' => 'left', fill => 'x', -expand => 1) ; + + $frm->pack(side => 'top', fill => 'x', -expand => 1) ; + + $row = pop @{$self->{'brkPtSlots'}} or $row = $self->{'brkPtCnt'} ; + + $self->{'breakpts_table'}->put($row, 1, $frm) ; + + $self->{'breakpts_table_data'}->{"$fname:$index"}->{'frm'} = $frm ; + $self->{'breakpts_table_data'}->{"$fname:$index"}->{'row'} = $row ; + + $self->{'main_window'}->update ; + + $width = $frm->width ; + + if ( $width > $self->{'breakpts_table'}->width ) { + $self->{'notebook'}->configure(-width => $width) ; + } + +} # end of add_brkpt_to_brkpt_page + +sub remove_brkpt_from_brkpt_page { + my($self, $fname, $idx) = @_ ; + my($table) ; + + $table = $self->{'breakpts_table'} ; + + # Delete the breakpoint control in the breakpoints window + + $table->put($self->{'breakpts_table_data'}->{"$fname:$idx"}->{'row'}, 1) ; # delete? + + # + # Add this now empty slot to the list of ones we have open + # + + push @{$self->{'brkPtSlots'}}, $self->{'breakpts_table_data'}->{"$fname:$idx"}->{'row'} ; + + $self->{'brkPtSlots'} = [ sort { $b <=> $a } @{$self->{'brkPtSlots'}} ] ; + + delete $self->{'breakpts_table_data'}->{"$fname:$idx"} ; + + $self->{'brkPtCnt'} -= 1 ; + +} # end of remove_brkpt_from_brkpt_page + + +# +# Supporting the "Run To Here..." command +# +sub insertTempBreakpoint { + my ($self, $fname, $index) = @_ ; + my($offset) ; + local(*dbline) = $main::{'_<' . $fname} ; + + $offset = $dbline[1] =~ /use\s+.*Devel::_?ptkdb/ ? 1 : 0 ; + + return if( &DB::getdbline($fname, $index + $offset) ) ; # we already have a breakpoint here + + &DB::setdbline($fname, $index + $offset, {'type' => 'temp', 'line' => $index, 'value' => 1 } ) ; + +} # end of insertTempBreakpoint + +sub reinsertBreakpoints { + my ($self, $fname) = @_ ; + my ($brkPt) ; + + foreach $brkPt ( &DB::getbreakpoints($fname) ) { + # + # Our breakpoints are indexed by line + # therefore we can have 'gaps' where there + # lines, but not breaks set for them. + # + next unless defined $brkPt ; + + $self->insertBreakpoint($fname, @$brkPt{'line', 'value', 'expr'}) if( $brkPt->{'type'} eq 'user' ) ; + $self->insertTempBreakpoint($fname, $brkPt->{line}) if( $brkPt->{'type'} eq 'temp' ) ; + } # end of reinsert loop + +} # end of reinsertBreakpoints + +sub removeBreakpointTags { + my ($self, @brkPts) = @_ ; + my($idx, $brkPt) ; + + foreach $brkPt (@brkPts) { + + $idx = $brkPt->{'line'} ; + + if ( $brkPt->{'value'} ) { + $self->{'text'}->tagRemove("breaksetLine", "$idx.0", "$idx.$Devel::ptkdb::linenumber_length") ; + } + else { + $self->{'text'}->tagRemove("breakdisabledLine", "$idx.0", "$idx.$Devel::ptkdb::linenumber_length") ; + } + + $self->{'text'}->tagAdd("breakableLine", "$idx.0", "$idx.$Devel::ptkdb::linenumber_length") ; + } +} # end of removeBreakpointTags + +# +# Remove a breakpoint from the current window +# +sub removeBreakpoint { + my ($self, $fname, @idx) = @_ ; + my ($idx, $chkIdx, $i, $j, $info) ; + my($offset) ; + local(*dbline) = $main::{'_<' . $fname} ; + + $offset = $dbline[1] =~ /use\s+.*Devel::_?ptkdb/ ? 1 : 0 ; + + foreach $idx (@idx) { # end of removal loop + next unless defined $idx ; + my $brkPt = &DB::getdbline($fname, $idx + $offset) ; + next unless $brkPt ; # if we do not have an entry + &DB::cleardbline($fname, $idx + $offset) ; + + $self->remove_brkpt_from_brkpt_page($fname, $idx) ; + + next unless $brkPt->{fname} eq $self->{'current_file'} ; # if this isn't our current file there will be no controls + + # Delete the ext associated with the breakpoint expression (if any) + + $self->removeBreakpointTags($brkPt) ; + } # end of remove loop + + return ; +} # end of removeBreakpoint + +sub removeAllBreakpoints { + my ($self, $fname) = @_ ; + + $self->removeBreakpoint($fname, &DB::getdblineindexes($fname)) ; + +} # end of removeAllBreakpoints + +# +# Delete expressions prior to an update +# +sub deleteAllExprs { + my ($self) = @_ ; + $self->{'data_list'}->delete('all') ; +} # end of deleteAllExprs + +sub EnterExpr { + my ($self) = @_ ; + my $str = $self->clear_entry_text() ; + if( $str && $str ne "" && $str !~ /^\s+$/ ) { # if there is an expression and it's more than white space + $self->{'expr'} = $str ; + $self->{'event'} = 'expr' ; + } +} # end of EnterExpr + +# +# +# +sub QuickExpr { + my ($self) = @_ ; + + my $str = $self->{'quick_entry'}->get() ; + + if( $str && $str ne "" && $str !~ /^\s+$/ ) { # if there is an expression and it's more than white space + $self->{'qexpr'} = $str ; + $self->{'event'} = 'qexpr' ; + } +} # end of QuickExpr + +sub deleteExpr { + my ($self) = @_ ; + my ($entry, $i, @indexes) ; + my @sList = $self->{'data_list'}->info('select') ; + + # + # if we're deleteing a top level expression + # we have to take it out of the list of expressions + # + + foreach $entry ( @sList ) { + next if ($entry =~ /\//) ; # goto next expression if we're not a top level ( expr/entry) + $i = 0 ; + grep { push @indexes, $i if ($_->{'expr'} eq $entry) ; $i++ ; } @{$self->{'expr_list'}} ; + } # end of check loop + + # now take out our list of indexes ; + + for( 0..$#indexes ) { + splice @{$self->{'expr_list'}}, $indexes[$_] - $_, 1 ; + } + + for( @sList ) { + $self->{'data_list'}->delete('entry', $_) ; + } +} # end of deleteExpr + +sub fixExprPath { + my(@pathList) = @_ ; + + for (@pathList) { + s/$Devel::ptkdb::pathSep/$Devel::ptkdb::pathSepReplacement/go ; + } # end of path list + + return $pathList[0] unless wantarray ; + return @pathList ; + +} # end of fixExprPath + +## +## Inserts an expression($theRef) into an HList Widget($dl). If the expression +## is an array, blessed array, hash, or blessed hash(typical object), then this +## routine is called recursively, adding the members to the next level of heirarchy, +## prefixing array members with a [idx] and the hash members with the key name. +## This continues until the entire expression is decomposed to it's atomic constituents. +## Protection is given(with $reusedRefs) to ensure that 'circular' references within +## arrays or hashes(i.e. where a member of a array or hash contains a reference to a +## parent element within the heirarchy. +## +# +# Returns 1 if sucessfully added 0 if not +# +sub insertExpr { + my($self, $reusedRefs, $dl, $theRef, $name, $depth, $dirPath) = @_ ; + my($label, $type, $result, $selfCnt, @circRefs) ; + local($^W) = 0 ; # spare us uncessary warnings about comparing strings with == + + # + # Add data new data entries to the bottom + # + $dirPath = "" unless defined $dirPath ; + + $label = "" ; + $selfCnt = 0 ; + + while( ref $theRef eq 'SCALAR' ) { + $theRef = $$theRef ; + } + REF_CHECK: for( ; ; ) { + push @circRefs, $theRef ; + $type = ref $theRef ; + last unless ($type eq "REF") ; + $theRef = $$theRef ; # dref again + + $label .= "\\" ; # append a + if( grep $_ == $theRef, @circRefs ) { + $label .= "(circular)" ; + last ; + } + } + + if( !$type || $type eq "" || $type eq "GLOB" || $type eq "CODE") { + eval { + if( !defined $theRef ) { + $dl->add($dirPath . $name, -text => "$name = $label" . "undef") ; + } + else { + $dl->add($dirPath . $name, -text => "$name = $label$theRef") ; + } + } ; + $self->DoAlert($@), return 0 if $@ ; + return 1 ; + } + + if( $type eq 'ARRAY' or "$theRef" =~ /ARRAY/ ) { + my ($r, $idx) ; + $idx = 0 ; + eval { + $dl->add($dirPath . $name, -text => "$name = $theRef") ; + } ; + if( $@ ) { + $self->DoAlert($@) ; + return 0 ; + } + $result = 1 ; + foreach $r ( @{$theRef} ) { + + if( grep $_ == $r, @$reusedRefs ) { # check to make sure that we're not doing a single level self reference + eval { + $dl->add($dirPath . fixExprPath($name) . $Devel::ptkdb::pathSep . "__ptkdb_self_path" . $selfCnt++, -text => "[$idx] = $r REUSED ADDR") ; + } ; + $self->DoAlert($@) if( $@ ) ; + next ; + } + + $^W = 0 ; + + push @$reusedRefs, $r ; + $result = $self->insertExpr($reusedRefs, $dl, $r, "[$idx]", $depth-1, $dirPath . fixExprPath($name) . $Devel::ptkdb::pathSep) unless $depth == 0 ; + pop @$reusedRefs ; + + return 0 unless $result ; + $idx += 1 ; + } + return 1 ; + } # end of array case + + if( "$theRef" !~ /HASH\050\060x[0-9a-f]*\051/o ) { + eval { + $dl->add($dirPath . fixExprPath($name), -text => "$name = $theRef") ; + } ; + if( $@ ) { + $self->DoAlert($@) ; + return 0 ; + } + return 1 ; + } +# +# Anything else at this point is +# either a 'HASH' or an object +# of some kind. +# + my($r, @theKeys, $idx) ; + $idx = 0 ; + @theKeys = sort keys %{$theRef} ; + $dl->add($dirPath . $name, -text => "$name = $theRef") ; + $result = 1 ; + + foreach $r ( @$theRef{@theKeys} ) { # slice out the values with the sorted list + + if( grep $_ == $r, @$reusedRefs ) { # check to make sure that we're not doing a single level self reference + eval { + $dl->add($dirPath . fixExprPath($name) . $Devel::ptkdb::pathSep . "__ptkdb_self_path" . $selfCnt++, -text => "$theKeys[$idx++] = $r REUSED ADDR") ; + } ; + print "bad path $@\n" if( $@ ) ; + next ; + } + + $^W = 0 ; + + push @$reusedRefs, $r ; + + $result = $self->insertExpr($reusedRefs, # recursion protection + $dl, # data list widget + $r, # reference whose value is displayed + $theKeys[$idx], # name + $depth-1, # remaining expansion depth + $dirPath . $name . $Devel::ptkdb::pathSep # path to add to + ) unless $depth == 0 ; + + pop @$reusedRefs ; + + return 0 unless $result ; + $idx += 1 ; + } # end of ref add loop + + return 1 ; +} # end of insertExpr + +# +# We're setting the line where we are stopped. +# Create a tag for this and set it as bold. +# +sub set_line { + my ($self, $lineno) = @_ ; + my $text = $self->{'text'} ; + + return if( $lineno <= 0 ) ; + + if( $self->{current_line} > 0 ) { + $text->tagRemove('stoppt', "$self->{current_line}.0 linestart", "$self->{current_line}.0 lineend") ; + } + $self->{current_line} = $lineno - $self->{'line_offset'} ; + $text->tagAdd('stoppt', "$self->{current_line}.0 linestart", "$self->{current_line}.0 lineend") ; + + $self->{'text'}->see("$self->{current_line}.0 linestart") ; +} # end of set_line + +# +# Set the file that is in the code window. +# +# $fname the 'new' file to view +# $line the line number we're at +# $brkPts any breakpoints that may have been set in this file +# + +use Carp ; + +sub set_file { + my ($self, $fname, $line) = @_ ; + my ($lineStr, $offset, $text, $i, @text) ; + my (@breakableTagList, @nonBreakableTagList) ; + + return unless $fname ; # we're getting an undef here on 'Restart...' + + local(*dbline) = $main::{'_<' . $fname}; + + # + # with the #! /usr/bin/perl -d:ptkdb at the header of the file + # we've found that with various combinations of other options the + # files haven't come in at the right offsets + # + $offset = 0 ; + $offset = 1 if $dbline[1] =~ /use\s+.*Devel::_?ptkdb/ ; + $self->{'line_offset'} = $offset ; + + $text = $self->{'text'} ; + + if( $fname eq $self->{current_file} ) { + $self->set_line($line) ; + return ; + } ; + + $fname =~ s/^\-// ; # Tk does not like leadiing '-'s + $self->{main_window}->configure('-title' => $fname) ; + + # Erase any existing text + + $text->delete('0.0','end') ; + + my $len = $Devel::ptkdb::linenumber_length ; + + # + # This is the tightest loop we have in the ptkdb code. + # It is here where performance is the most critical. + # The map block formats perl code for display. Since + # the file could be potentially large, we will try + # to make this loop as thin as possible. + # + # NOTE: For a new perl individual this may appear as + # if it was intentionally obfuscated. This is not + # not the case. The following code is the result + # of an intensive effort to optimize this code. + # Prior versions of this code were quite easier + # to read, but took 3 times longer. + # + + $lineStr = " " x 200 ; # pre-allocate space for $lineStr + $i = 1 ; + + local($^W) = 0 ; # spares us useless warnings under -w when checking $dbline[$_] != 0 + # + # The 'map' call will build list of 'string', 'tag' pairs + # that will become arguments to the 'insert' call. Passing + # the text to insert "all at once" rather than one insert->('end', 'string', 'tag') + # call at time provides a MASSIVE savings in execution time. + # + + $text->insert('end', map { + + # + # build collections of tags representing + # the line numbers for breakable and + # non-breakable lines. We apply these + # tags after we've built the text + # + + ($_ != 0 && push @breakableTagList, "$i.0", "$i.$len") || push @nonBreakableTagList, "$i.0", "$i.$len" ; + + $lineStr = sprintf($Devel::ptkdb::linenumber_format, $i++) . $_ ; # line number + text of the line + $lineStr .= "\n" unless /\n$/o ; # append a \n if there isn't one already + + ($lineStr, 'code') ; # return value for block, a string,tag pair for text insert + + } @dbline[$offset+1 .. $#dbline] ) ; + + + # + # Apply the tags that we've collected + # NOTE: it was attempted to incorporate these + # operations into the 'map' block above, but that + # actually degraded performance. + # + $text->tagAdd("breakableLine", @breakableTagList) if @breakableTagList ; # apply tag to line numbers where the lines are breakable + $text->tagAdd("nonbreakableLine", @nonBreakableTagList) if @nonBreakableTagList ; # apply tag to line numbers where the lines are not breakable. + + # + # Reinsert breakpoints (if info provided) + # + + $self->set_line($line) ; + $self->{current_file} = $fname ; + return $self->reinsertBreakpoints($fname) ; + + } # end of set_file + +# +# Get the current line that the insert cursor is in +# + sub get_lineno { + my ($self) = @_ ; + my ($info) ; + + $info = $self->{'text'}->index('insert') ; # get the location for the insertion point + $info =~ s/\..*$/\.0/ ; + + return int $info ; + } # end of get_lineno + +sub DoGoto { + my ($self, $entry) = @_ ; + + my $txt = $entry->get() ; + + $txt =~ s/(\d*).*/$1/ ; # take the first blob of digits + if( $txt eq "" ) { + print "invalid text range\n" ; + return if $txt eq "" ; + } + + $self->{'text'}->see("$txt.0") ; + + $entry->selectionRange(0, 'end') if $entry->can('selectionRange') + + } # end of DoGoto + +sub GotoLine { + my ($self) = @_ ; + my ($topLevel) ; + + if( $self->{goto_window} ) { + $self->{goto_window}->raise() ; + $self->{goto_text}->focus() ; + return ; + } + + # + # Construct a dialog that has an + # entry field, okay and cancel buttons + # + my $okaySub = sub { $self->DoGoto($self->{'goto_text'}) } ; + + $topLevel = $self->{main_window}->Toplevel(-title => "Goto Line?", -overanchor => 'cursor') ; + + $self->{goto_text} = $topLevel->Entry()->pack(side => 'top', fill => 'both', -expand => 1) ; + + $self->{goto_text}->bind('<Return>', $okaySub) ; # make a CR do the same thing as pressing an okay + + $self->{goto_text}->focus() ; + + # Bind a double click on the mouse button to the same action + # as pressing the Okay button + + $topLevel->Button( text => "Okay", -command => $okaySub, @Devel::ptkdb::button_font, + )->pack(side => 'left', fill => 'both', -expand => 1) ; + + # + # Subroutone called when the 'Dismiss' + # button is pushed. + # + my $dismissSub = sub { + delete $self->{goto_text} ; + destroy {$self->{goto_window}} ; + delete $self->{goto_window} ; # remove the entry from our hash so we won't + } ; + + $topLevel->Button( text => "Dismiss", @Devel::ptkdb::button_font, + -command => $dismissSub )->pack(side => 'left', fill => 'both', -expand => 1) ; + + $topLevel->protocol('WM_DELETE_WINDOW', sub { destroy $topLevel ; } ) ; + + $self->{goto_window} = $topLevel ; + +} # end of GotoLine + + +# +# Subroutine called when the 'okay' button is pressed +# +sub FindSearch { + my ($self, $entry, $btn, $regExp) = @_ ; + my (@switches, $result) ; + my $txt = $entry->get() ; + + return if $txt eq "" ; + + push @switches, "-forward" if $self->{fwdOrBack} eq "forward" ; + push @switches, "-backward" if $self->{fwdOrBack} eq "backward" ; + + if( $regExp ) { + push @switches, "-regexp" ; + } + else { + push @switches, "-nocase" ; # if we're not doing regex we may as well do caseless search + } + + $result = $self->{'text'}->search(@switches, $txt, $self->{search_start}) ; + + # untag the previously found text + + $self->{'text'}->tagRemove('search_tag', @{$self->{search_tag}}) if defined $self->{search_tag} ; + + if( !$result || $result eq "" ) { + # No Text was found + $btn->flash() ; + $btn->bell() ; + + delete $self->{search_tag} ; + $self->{'search_start'} = "0.0" ; + } + else { # text found + $self->{'text'}->see($result) ; + # set the insertion of the text as well + $self->{'text'}->markSet('insert' => $result) ; + my $len = length $txt ; + + if( $self->{fwdOrBack} ) { + $self->{search_start} = "$result +$len chars" ; + $self->{search_tag} = [ $result, $self->{search_start} ] ; + } + else { + # backwards search + $self->{search_start} = "$result -$len chars" ; + $self->{search_tag} = [ $result, "$result +$len chars" ] ; + } + + # tag the newly found text + + $self->{'text'}->tagAdd('search_tag', @{$self->{search_tag}}) ; + } # end of text found + + $entry->selectionRange(0, 'end') if $entry->can('selectionRange') ; + +} # end of FindSearch + + +# +# Support for the Find Text... Menu command +# +sub FindText { + my ($self) = @_ ; + my ($top, $entry, $rad1, $rad2, $chk, $regExp, $frm, $okayBtn) ; + + # + # if we already have the Find Text Window + # open don't bother openning another, bring + # the existing one to the front. + # + if( $self->{find_window} ) { + $self->{find_window}->raise() ; + $self->{find_text}->focus() ; + return ; + } + + $self->{search_start} = $self->{'text'}->index('insert') if( $self->{search_start} eq "" ) ; + + # + # Subroutine called when the 'Dismiss' button + # is pushed. + # + my $dismissSub = sub { + $self->{'text'}->tagRemove('search_tag', @{$self->{search_tag}}) if defined $self->{search_tag} ; + $self->{search_start} = "" ; + destroy {$self->{find_window}} ; + delete $self->{search_tag} ; + delete $self->{find_window} ; + } ; + + # + # Construct a dialog that has an entry field, forward, backward, regex option, okay and cancel buttons + # + $top = $self->{main_window}->Toplevel(-title => "Find Text?") ; + + $self->{find_text} = $top->Entry()->pack('side' => 'top', fill => 'both', -expand => 1) ; + + + $frm = $top->Frame()->pack('side' => 'top', fill => 'both', -expand => 1) ; + + $self->{fwdOrBack} = 'forward' ; + $rad1 = $frm->Radiobutton('text' => "Forward", 'value' => 1, 'variable' => \$self->{fwdOrBack}) ; + $rad1->pack(side => 'left', fill => 'both', -expand => 1) ; + $rad2 = $frm->Radiobutton('text' => "Backward", 'value' => 0, 'variable' => \$self->{fwdOrBack}) ; + $rad2->pack(side => 'left', fill => 'both', -expand => 1) ; + + $regExp = 0 ; + $chk = $frm->Checkbutton('text' => "RegExp", 'variable' => \$regExp) ; + $chk->pack(side => 'left', fill => 'both', -expand => 1) ; + + # Okay and cancel buttons + + # Bind a double click on the mouse button to the same action + # as pressing the Okay button + + $okayBtn = $top->Button( text => "Okay", -command => sub { $self->FindSearch($self->{find_text}, $okayBtn, $regExp) ; }, + @Devel::ptkdb::button_font, + )->pack(side => 'left', fill => 'both', -expand => 1) ; + + $self->{find_text}->bind('<Return>', sub { $self->FindSearch($self->{find_text}, $okayBtn, $regExp) ; }) ; + + $top->Button( text => "Dismiss", @Devel::ptkdb::button_font, + -command => $dismissSub)->pack(side => 'left', fill => 'both', -expand => 1) ; + + $top->protocol('WM_DELETE_WINDOW', $dismissSub) ; + + $self->{find_text}->focus() ; + + $self->{find_window} = $top ; + +} # end of FindText + +sub main_loop { + my ($self) = @_ ; + my ($evt, $str, $result) ; + my $i = 0; + SWITCH: for ($self->{'event'} = 'null' ; ; $self->{'event'} = undef ) { + + Tk::DoOneEvent(0); + next unless $self->{'event'} ; + + $evt = $self->{'event'} ; + $evt =~ /step/o && do { last SWITCH ; } ; + $evt =~ /null/o && do { next SWITCH ; } ; + $evt =~ /run/o && do { last SWITCH ; } ; + $evt =~ /quit/o && do { $self->{main_window}->destroy if $self->{main_window} ; + $self->{main_window} = undef if defined $self->{main_window} ; exit ; } ; + $evt =~ /expr/o && do { return $evt ; } ; # adds an expression to our expression window + $evt =~ /qexpr/o && do { return $evt ; } ; # does a 'quick' expression + $evt =~ /update/o && do { return $evt ; } ; # forces an update on our expression window + $evt =~ /reeval/o && do { return $evt ; } ; # updated the open expression eval window + $evt =~ /balloon_eval/ && do { return $evt } ; + } # end of switch block + return $evt ; +} # end of main_loop + +# +# $subStackRef A reference to the current subroutine stack +# + +sub goto_sub_from_stack { + my ($self, $f, $lineno) = @_ ; + $self->set_file($f, $lineno) ; +} # end of goto_sub_from_stack ; + +sub refresh_stack_menu { + my ($self) = @_ ; + my ($str, $name, $i, $sub_offset, $subStack) ; + + # + # CAUTION: In the effort to 'rationalize' the code + # are moving some of this function down from DB::DB + # to here. $sub_offset represents how far 'down' + # we are from DB::DB. The $DB::subroutine_depth is + # tracked in such a way that while we are 'in' the debugger + # it will not be incremented, and thus represents the stack depth + # of the target program. + # + $sub_offset = 1 ; + $subStack = [] ; + + # clear existing entries + + for( $i = 0 ; $i <= $DB::subroutine_depth ; $i++ ) { + my ($package, $filename, $line, $subName) = caller $i+$sub_offset ; + last if !$subName ; + push @$subStack, { 'name' => $subName, 'pck' => $package, 'filename' => $filename, 'line' => $line } ; + } + + $self->{stack_menu}->menu->delete(0, 'last') ; # delete existing menu items + + for( $i = 0 ; $subStack->[$i] ; $i++ ) { + + $str = defined $subStack->[$i+1] ? "$subStack->[$i+1]->{name}" : "MAIN" ; + + my ($f, $line) = ($subStack->[$i]->{filename}, $subStack->[$i]->{line}) ; # make copies of the values for use in 'sub' + $self->{stack_menu}->command(-label => $str, -command => sub { $self->goto_sub_from_stack($f, $line) ; } ) ; + } +} # end of refresh_stack_menu + +no strict ; + +sub get_state { + my ($self, $fname) = @_ ; + my ($val) ; + local($files, $expr_list, $eval_saved_text, $main_win_geometry) ; + + do "$fname" ; + + if( $@ ) { + $self->DoAlert($@) ; + return ( undef ) x 4 ; # return a list of 4 undefined values + } + + return ($files, $expr_list, $eval_saved_text, $main_win_geometry) ; +} # end of get_state + +use strict ; + +sub restoreStateFile { + my ($self, $fname) = @_ ; + local(*F) ; + my ($saveCurFile, $s, @n, $n) ; + + if (!(-e $fname && -r $fname)) { + $self->DoAlert("$fname does not exist") ; + return ; + } + + my ($files, $expr_list, $eval_saved_text, $main_win_geometry) = $self->get_state($fname) ; + my ($f, $brks) ; + + return unless defined $files || defined $expr_list ; + + &DB::restore_breakpoints_from_save($files) ; + + # + # This should force the breakpoints to be restored + # + $saveCurFile = $self->{current_file} ; + + @$self{ 'current_file', 'expr_list', 'eval_saved_text' } = + ( "" , $expr_list, $eval_saved_text) ; + + $self->set_file($saveCurFile, $self->{current_line}) ; + + $self->{'event'} = 'update' ; + + if ( $main_win_geometry && $self->{'main_window'} ) { + # restore the height and width of the window + $self->{main_window}->geometry( $main_win_geometry ) ; + } +} # end of retstoreState + +sub updateEvalWindow { + my ($self, @result) = @_ ; + my ($leng, $str, $d) ; + + $leng = 0 ; + for( @result ) { + if( !$Devel::ptkdb::DataDumperAvailable || !$Devel::ptkdb::useDataDumperForEval ) { + $str = "$_\n" ; + } + else { + $d = Data::Dumper->new([ $_ ]) ; + $d->Indent($Devel::ptkdb::eval_dump_indent) ; + $d->Terse(1) ; + if( Data::Dumper->can('Dumpxs') ) { + $str = $d->Dumpxs( $_ ) ; + } + else { + $str = $d->Dump( $_ ) ; + } + } + $leng += length $str ; + $self->{eval_results}->insert('end', $str) ; + } +} # end of updateEvalWindow + +sub setupEvalWindow { + my($self) = @_ ; + my($top, $dismissSub) ; + my $f ; + $self->{eval_window}->focus(), return if exists $self->{eval_window} ; # already running this window? + + $top = $self->{main_window}->Toplevel(-title => "Evaluate Expressions...") ; + $self->{eval_window} = $top ; + $self->{eval_text} = $top->Scrolled('TextUndo', + @Devel::ptkdb::scrollbar_cfg, + @Devel::ptkdb::eval_text_font, + width => 50, + height => 10, + -wrap => "none", + )->packAdjust('side' => 'top', 'fill' => 'both', -expand => 1) ; + + $self->{eval_text}->insert('end', $self->{eval_saved_text}) if exists $self->{eval_saved_text} && defined $self->{eval_saved_text} ; + + $top->Label(-text, "Results:")->pack('side' => 'top', 'fill' => 'both', -expand => 'n') ; + + $self->{eval_results} = $top->Scrolled('Text', + @Devel::ptkdb::scrollbar_cfg, + width => 50, + height => 10, + -wrap => "none", + @Devel::ptkdb::eval_text_font + )->pack('side' => 'top', 'fill' => 'both', -expand => 1) ; + + my $btn = $top->Button(-text => 'Eval...', -command => sub { $DB::window->{event} = 'reeval' ; } + )->pack('side' => 'left', 'fill' => 'x', -expand => 1) ; + + $dismissSub = sub { + $self->{eval_saved_text} = $self->{eval_text}->get('0.0', 'end') ; + $self->{eval_window}->destroy ; + delete $self->{eval_window} ; + } ; + + $top->protocol('WM_DELETE_WINDOW', $dismissSub ) ; + + $top->Button(-text => 'Clear Eval', -command => sub { $self->{eval_text}->delete('0.0', 'end') } + )->pack('side' => 'left', 'fill' => 'x', -expand => 1) ; + + $top->Button(-text => 'Clear Results', -command => sub { $self->{eval_results}->delete('0.0', 'end') } + )->pack('side' => 'left', 'fill' => 'x', -expand => 1) ; + + $top->Button(-text => 'Dismiss', -command => $dismissSub)->pack('side' => 'left', 'fill' => 'x', -expand => 1) ; + +} # end of setupEvalWindow ; + +sub filterBreakPts { + my ($breakPtsListRef, $fname) = @_ ; + my $dbline = $main::{'_<' . $fname}; # breakable lines + local($^W) = 0 ; + # + # Go through the list of breaks and take out any that + # are no longer breakable + # + + for( @$breakPtsListRef ) { + next unless defined $_ ; + + next if $dbline->[$_->{'line'}] != 0 ; # still breakable + + $_ = undef ; + } +} # end of filterBreakPts + +sub DoAbout { + my $self = shift ; + my $str = "ptkdb $DB::VERSION\nCopyright 1998 by Andrew E. Page\nFeedback to aep\@world.std.com\n\n" ; + my $threadString = "" ; + + $threadString = "Threads Available" if $Config::Config{usethreads} ; + $threadString = " Thread Debugging Enabled" if $DB::usethreads ; + + $str .= <<"__STR__" ; + This program is free software; you can redistribute it and/or modify + it under the terms of either: + + a) the GNU General Public License as published by the Free + Software Foundation; either version 1, or (at your option) any + later version, or + + b) the "Artistic License" which comes with this Kit. + + 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 either + the GNU General Public License or the Artistic License for more details. + + OS $^O + Tk Version $Tk::VERSION + Perl Version $] +Data::Dumper Version $Data::Dumper::VERSION + $threadString +__STR__ + + $self->DoAlert($str, "About ptkdb") ; +} # end of DoAbout + +# +# return 1 if succesfully set, +# return 0 if otherwise +# +sub SetBreakPoint { + my ($self, $isTemp) = @_ ; + my $dbw = $DB::window ; + my $lineno = $dbw->get_lineno() ; + my $expr = $dbw->clear_entry_text() ; + local($^W) = 0 ; + + if( !&DB::checkdbline($DB::window->{current_file}, $lineno + $self->{'line_offset'}) ) { + $dbw->DoAlert("line $lineno in $DB::window->{current_file} is not breakable") ; + return 0 ; + } + + if( !$isTemp ) { + $dbw->insertBreakpoint($DB::window->{current_file}, $lineno, 1, $expr) ; + return 1 ; + } + else { + $dbw->insertTempBreakpoint($DB::window->{current_file}, $lineno) ; + return 1 ; + } + + return 0 ; +} # end of SetBreakPoint + +sub UnsetBreakPoint { + my ($self) = @_ ; + my $lineno = $self->get_lineno() ; + + $self->removeBreakpoint($DB::window->{current_file}, $lineno) ; +} # end of UnsetBreakPoint + +sub balloon_post { + my $self = $DB::window ; + my $txt = $DB::window->{'text'} ; + + return 0 if ($self->{'expr_ballon_msg'} eq "") || ($self->{'balloon_expr'} eq "") ; # don't post for an empty string + + return $self->{'balloon_coord'} ; +} + +sub balloon_motion { + my ($txt, $x, $y) = @_ ; + my ($offset_x, $offset_y) = ($x + 4, $y + 4) ; + my $self = $DB::window ; + my $txt2 = $self->{'text'} ; + my $data ; + + $self->{'balloon_coord'} = "$offset_x,$offset_y" ; + + $x -= $txt->rootx ; + $y -= $txt->rooty ; + # + # Post an event that will cause us to put up a popup + # + + if( $txt2->tagRanges('sel') ) { # check to see if 'sel' tag exists (return undef value) + $data = $txt2->get("sel.first", "sel.last") ; # get the text between the 'first' and 'last' point of the sel (selection) tag + } + else { + $data = $DB::window->retrieve_text_expr($x, $y) ; + } + + if( !$data ) { + $self->{'balloon_expr'} = "" ; + return 0 ; + } + + return 0 if ($data eq $self->{'balloon_expr'}) ; # nevermind if it's the same expression + + $self->{'event'} = 'balloon_eval' ; + $self->{'balloon_expr'} = $data ; + + return 1 ; # ballon will be canceled and a new one put up(maybe) +} # end of balloon_motion + +sub retrieve_text_expr { + my($self, $x, $y) = @_ ; + my $txt = $self->{'text'} ; + + my $coord = "\@$x,$y" ; + + my($idx, $col, $data, $offset) ; + + ($col, $idx) = line_number_from_coord($txt, $coord) ; + + $offset = $Devel::ptkdb::linenumber_length + 1 ; # line number text + 1 space + + return undef if $col < $offset ; # no posting + + $col -= $offset ; + + local(*dbline) = $main::{'_<' . $self->{current_file}} ; + + return undef if( !defined $dbline[$idx] || $dbline[$idx] == 0 ) ; # no executable text, no real variable(?) + + $data = $dbline[$idx] ; + + # if we're sitting over white space, leave + my $len = length $data ; + return unless $data && $col && $len > 0 ; + + return if substr($data, $col, 1) =~ /\s/ ; + + # walk backwards till we find some whitespace + + $col = $len if $len < $col ; + while( --$col >= 0 ) { + last if substr($data, $col, 1) =~ /[\s\$\@\%]/ ; + } + + substr($data, $col) =~ /^([\$\@\%][a-zA-Z0-9_]+)/ ; + + return $1 ; +} + +# +# after DB::eval get's us a result +# +sub code_motion_eval { + my ($self, @result) = @_ ; + my $str ; + + if( exists $self->{'balloon_dumper'} ) { + + my $d = $self->{'balloon_dumper'} ; + + $d->Reset() ; + $d->Values( [ $#result == 0 ? @result : \@result ] ) ; + + if( $d->can('Dumpxs') ) { + $str = $d->Dumpxs() ; + } + else { + $str = $d->Dump() ; + } + + chomp($str) ; + } + else { + $str = "@result" ; + } + + # + # Cut the string down to 1024 characters to keep from + # overloading the balloon window + # + + $self->{'expr_ballon_msg'} = "$self->{'balloon_expr'} = " . substr $str, 0, 1024 ; + } # end of code motion eval + +# +# Subroutine called when we enter DB::DB() +# In other words when the target script 'stops' +# in the Debugger +# +sub EnterActions { + my($self) = @_ ; + +# $self->{'main_window'}->Unbusy() ; + +} # end of EnterActions + +# +# Subroutine called when we return from DB::DB() +# When the target script resumes. +# +sub LeaveActions { + my($self) = @_ ; + + # $self->{'main_window'}->Busy() ; +} # end of LeaveActions + + +sub BEGIN { + $Devel::ptkdb::scriptName = $0 ; + @Devel::ptkdb::script_args = @ARGV ; # copy args + +} + +## +## Save the ptkdb state file and restart the debugger +## +sub DoRestart { + my($fname) ; + + $fname = $ENV{'TMP'} || $ENV{'TMPDIR'} || $ENV{'TMP_DIR'} || $ENV{'TEMP'} || $ENV{'HOME'} ; + $fname .= '/' if $fname ; + $fname = "" unless $fname ; + + $fname .= "ptkdb_restart_state$$" ; + + # print "saving temp state file $fname\n" ; + + &DB::save_state_file($fname) ; + + $ENV{'PTKDB_RESTART_STATE_FILE'} = $fname ; + + ## + ## build up the command to do the restart + ## + + $fname = "perl -w -d:ptkdb $Devel::ptkdb::scriptName @Devel::ptkdb::script_args" ; + + # print "$$ doing a restart with $fname\n" ; + + exec $fname ; + +} # end of DoRestart + +## +## Enables/Disables the feature where we stop +## if we've encountered a perl warning such as: +## "Use of uninitialized value at undef_warn.pl line N" +## + +sub stop_on_warning_cb { + &$DB::ptkdb::warn_sig_save() if $DB::ptkdb::warn_sig_save ; # call any previously registered warning + $DB::window->DoAlert(@_) ; + $DB::single = 1 ; # forces debugger to stop next time +} + +sub set_stop_on_warning { + + if( $DB::ptkdb::stop_on_warning ) { + + return if $DB::ptkdb::warn_sig_save == \&stop_on_warning_cb ; # prevents recursion + + $DB::ptkdb::warn_sig_save = $SIG{'__WARN__'} if $SIG{'__WARN__'} ; + $SIG{'__WARN__'} = \&stop_on_warning_cb ; + } + else { + ## + ## Restore any previous warning signal + ## + local($^W) = 0 ; + $SIG{'__WARN__'} = $DB::ptkdb::warn_sig_save ; + } +} # end of set_stop_on_warning + +1 ; # end of Devel::ptkdb + +package DB ; + +use vars '$VERSION', '$header' ; + +$VERSION = '1.108' ; +$header = "ptkdb.pm version $DB::VERSION"; +$DB::window->{current_file} = "" ; + +# +# Here's the clue... +# eval only seems to eval the context of +# the executing script while in the DB +# package. When we had updateExprs in the Devel::ptkdb +# package eval would turn up an undef result. +# + +sub updateExprs { + my ($package) = @_ ; + # + # Update expressions + # + $DB::window->deleteAllExprs() ; + my ($expr, @result); + + foreach $expr ( @{$DB::window->{'expr_list'}} ) { + next if length $expr == 0 ; + + @result = &DB::dbeval($package, $expr->{'expr'}) ; + + if( scalar @result == 1 ) { + $DB::window->insertExpr([ $result[0] ], $DB::window->{'data_list'}, $result[0], $expr->{'expr'}, $expr->{'depth'}) ; + } + else { + $DB::window->insertExpr([ \@result ], $DB::window->{'data_list'}, \@result, $expr->{'expr'}, $expr->{'depth'}) ; + } + } + +} # end of updateExprs + +no strict ; # turning strict off (shame shame) because we keep getting errrs for the local(*dbline) + +# +# returns true if line is breakable +# +use Carp ; +sub checkdbline($$) { + my ($fname, $lineno) = @_ ; + + return 0 unless $fname; # we're getting an undef here on 'Restart...' + + local(*dbline) = $main::{'_<' . $fname} ; + local($^W) = 0 ; # spares us warnings under -w + + my $flag = $dbline[$lineno] != 0 ; + + return $flag; + +} # end of checkdbline + +# +# sets a breakpoint 'through' a magic +# variable that perl is able to interpert +# +sub setdbline($$$) { + my ($fname, $lineno, $value) = @_ ; + local(*dbline) = $main::{'_<' . $fname}; + + $dbline{$lineno} = $value ; +} # end of setdbline + +sub getdbline($$) { + my ($fname, $lineno) = @_ ; + local(*dbline) = $main::{'_<' . $fname}; + return $dbline{$lineno} ; +} # end of getdbline + +sub getdbtextline { + my ($fname, $lineno) = @_ ; + local(*dbline) = $main::{'_<' . $fname}; + return $dbline[$lineno] ; +} # end of getdbline + + +sub cleardbline($$;&) { + my ($fname, $lineno, $clearsub) = @_ ; + local(*dbline) = $main::{'_<' . $fname}; + my $value ; # just in case we want it for something + + $value = $dbline{$lineno} ; + delete $dbline{$lineno} ; + &$clearsub($value) if $value && $clearsub ; + + return $value ; +} # end of cleardbline + +sub clearalldblines(;&) { + my ($clearsub) = @_ ; + my ($key, $value, $brkPt, $dbkey) ; + local(*dbline) ; + + while ( ($key, $value) = each %main:: ) { # key loop + next unless $key =~ /^_</ ; + *dbline = $value ; + + foreach $dbkey (keys %dbline) { + $brkPt = $dbline{$dbkey} ; + delete $dbline{$dbkey} ; + next unless $brkPt && $clearSub ; + &$clearsub($brkPt) ; # if specificed, call the sub routine to clear the breakpoint + } + + } # end of key loop + +} # end of clearalldblines + +sub getdblineindexes { + my ($fname) = @_ ; + local(*dbline) = $main::{'_<' . $fname} ; + return keys %dbline ; +} # end of getdblineindexes + +sub getbreakpoints { + my (@fnames) = @_ ; + my ($fname, @retList) ; + + foreach $fname (@fnames) { + next unless $main::{'_<' . $fname} ; + local(*dbline) = $main::{'_<' . $fname} ; + push @retList, values %dbline ; + } + return @retList ; +} # end of getbreakpoints + +# +# Construct a hash of the files +# that have breakpoints to save +# +sub breakpoints_to_save { + my ($file, @breaks, $brkPt, $svBrkPt, $list) ; + my ($brkList) ; + + $brkList = {} ; + + foreach $file ( keys %main:: ) { # file loop + next unless $file =~ /^_</ && exists $main::{$file} ; + local(*dbline) = $main::{$file} ; + + next unless @breaks = values %dbline ; + $list = [] ; + foreach $brkPt ( @breaks ) { + + $svBrkPt = { %$brkPt } ; # make a copy of it's data + + push @$list, $svBrkPt ; + + } # end of breakpoint loop + + $brkList->{$file} = $list ; + + } # end of file loop + + return $brkList ; + +} # end of breakpoints_to_save + +# +# When we restore breakpoints from a state file +# they've often 'moved' because the file +# has been editted. +# +# We search for the line starting with the original line number, +# then we walk it back 20 lines, then with line right after the +# orginal line number and walk forward 20 lines. +# +# NOTE: dbline is expected to be 'local' +# when called +# +sub fix_breakpoints { + my(@brkPts) = @_ ; + my($startLine, $endLine, $nLines, $brkPt) ; + my (@retList) ; + local($^W) = 0 ; + + $nLines = scalar @dbline ; + + foreach $brkPt (@brkPts) { + + $startLine = $brkPt->{'line'} > 20 ? $brkPt->{'line'} - 20 : 0 ; + $endLine = $brkPt->{'line'} < $nLines - 20 ? $brkPt->{'line'} + 20 : $nLines ; + + for( (reverse $startLine..$brkPt->{'line'}), $brkPt->{'line'} + 1 .. $endLine ) { + next unless $brkPt->{'text'} eq $dbline[$_] ; + $brkPt->{'line'} = $_ ; + push @retList, $brkPt ; + last ; + } + } # end of breakpoint list + + return @retList ; + +} # end of fix_breakpoints + +# +# Restore breakpoints saved above +# +sub restore_breakpoints_from_save { + my ($brkList) = @_ ; + my ($offset, $key, $list, $brkPt, @newList) ; + + while ( ($key, $list) = each %$brkList ) { # reinsert loop + next unless exists $main::{$key} ; + local(*dbline) = $main::{$key} ; + + $offset = 0 ; + $offset = 1 if $dbline[1] =~ /use\s+.*Devel::_?ptkdb/ ; + + @newList = fix_breakpoints(@$list) ; + + foreach $brkPt ( @newList ) { + if( !&DB::checkdbline($key, $brkPt->{'line'} + $offset) ) { + print "Breakpoint $key:$brkPt->{'line'} in config file is not breakable.\n" ; + next ; + } + $dbline{$brkPt->{'line'}} = { %$brkPt } ; # make a fresh copy + } + } # end of reinsert loop + +} # end of restore_breakpoints_from_save ; + +use strict ; + +sub dbint_handler { + my($sigName) = @_ ; + $DB::single = 1 ; + print "signalled\n" ; +} # end of dbint_handler + +# +# Do first time initialization at the startup +# of DB::DB +# +sub Initialize { + my ($fName) = @_ ; + + return if $DB::ptkdb::isInitialized ; + $DB::ptkdb::isInitialized = 1 ; + + $DB::window = new Devel::ptkdb ; + + $DB::window->do_user_init_files() ; + + + $DB::dbint_handler_save = $SIG{'INT'} unless $DB::sigint_disable ; # saves the old handler + $SIG{'INT'} = "DB::dbint_handler" unless $DB::sigint_disable ; + + # Save the file name we started up with + $DB::startupFname = $fName ; + + # Check for a 'restart' file + + if( $ENV{'PTKDB_RESTART_STATE_FILE'} && $Devel::ptkdb::DataDumperAvailable && -e $ENV{'PTKDB_RESTART_STATE_FILE'} ) { + ## + ## Restore expressions and breakpoints in state file + ## + $DB::window->restoreStateFile($ENV{'PTKDB_RESTART_STATE_FILE'}) ; + unlink $ENV{'PTKDB_RESTART_STATE_FILE'} ; # delete state file + + # print "restoring state from $ENV{'PTKDB_RESTART_STATE_FILE'}\n" ; + + $ENV{'PTKDB_RESTART_STATE_FILE'} = "" ; # clear entry + } + else { + &DB::restoreState($fName) if $Devel::ptkdb::DataDumperAvailable ; + } + +} # end of Initialize + +sub restoreState { + my($fName) = @_ ; + my ($stateFile, $files, $expr_list, $eval_saved_text, $main_win_geometry, $restoreName) ; + + $stateFile = makeFileSaveName($fName) ; + + if( -e $stateFile && -r $stateFile ) { + ($files, $expr_list, $eval_saved_text, $main_win_geometry) = $DB::window->get_state($stateFile) ; + &DB::restore_breakpoints_from_save($files) ; + $DB::window->{'expr_list'} = $expr_list if defined $expr_list ; + $DB::window->{eval_saved_text} = $eval_saved_text ; + + if ( $main_win_geometry ) { + # restore the height and width of the window + $DB::window->{main_window}->geometry($main_win_geometry) ; + } + } + +} # end of Restore State + +sub makeFileSaveName { + my ($fName) = @_ ; + my $saveName = $fName ; + + if( $saveName =~ /.p[lm]$/ ) { + $saveName =~ s/.pl$/.ptkdb/ ; + } + else { + $saveName .= ".ptkdb" ; + } + + return $saveName ; +} # end of makeFileSaveName + +sub save_state_file { + my($fname) = @_ ; + my($files, $d, $saveStr) ; + + $files = &DB::breakpoints_to_save() ; + + $d = Data::Dumper->new( [ $files, $DB::window->{'expr_list'}, "" ], + [ "files", "expr_list", "eval_saved_text" ] ) ; + + $d->Purity(1) ; + if( Data::Dumper->can('Dumpxs') ) { + $saveStr = $d->Dumpxs() ; + } else { + $saveStr = $d->Dump() ; + } + + local(*F) ; + open F, ">$fname" || die "Couldn't open file $fname" ; + + print F $saveStr || die "Couldn't write file" ; + + close F ; +} # end of save_state_file + +sub SaveState { + my($name_in) = @_ ; + my ($top, $entry, $okayBtn, $win) ; + my ($fname, $saveSub, $cancelSub, $saveName, $eval_saved_text, $d) ; + my ($files, $main_win_geometry); + # + # Create our default name + # + $win = $DB::window ; + + # + # Extract the height and width of our window + # + $main_win_geometry = $win->{main_window}->geometry ; + + if ( defined $win->{save_box} ) { + $win->{save_box}->raise ; + $win->{save_box}->focus ; + return ; + } + + $saveName = $name_in || makeFileSaveName($DB::startupFname) ; + + + + $saveSub = sub { + $win->{'event'} = 'null' ; + + my $saveStr ; + + delete $win->{save_box} ; + + if( exists $win->{eval_window} ) { + $eval_saved_text = $win->{eval_text}->get('0.0', 'end') ; + } + else { + $eval_saved_text = $win->{eval_saved_text} ; + } + + $files = &DB::breakpoints_to_save() ; + + $d = Data::Dumper->new( [ $files, $win->{'expr_list'}, $eval_saved_text, $main_win_geometry ], + [ "files", "expr_list", "eval_saved_text", "main_win_geometry"] ) ; + + $d->Purity(1) ; + if( Data::Dumper->can('Dumpxs') ) { + $saveStr = $d->Dumpxs() ; + } else { + $saveStr = $d->Dump() ; + } + + local(*F) ; + eval { + open F, ">$saveName" || die "Couldn't open file $saveName" ; + + print F $saveStr || die "Couldn't write file" ; + + close F ; + } ; + $win->DoAlert($@) if $@ ; + } ; # end of save sub + + $cancelSub = sub { + delete $win->{'save_box'} + } ; # end of cancel sub + + # + # Create a dialog + # + + $win->{'save_box'} = $win->simplePromptBox("Save Config?", $saveName, $saveSub, $cancelSub) ; + +} # end of SaveState + +sub RestoreState { + my ($top, $restoreSub) ; + + $restoreSub = sub { + $DB::window->restoreStateFile($Devel::ptkdb::promptString) ; + } ; + + $top = $DB::window->simplePromptBox("Restore Config?", makeFileSaveName($DB::startupFname), $restoreSub) ; + +} # end of RestoreState + +sub SetStepOverBreakPoint { + my ($offset) = @_ ; + $DB::step_over_depth = $DB::subroutine_depth + ($offset ? $offset : 0) ; +} # end of SetStepOverBreakPoint + +# +# NOTE: It may be logical and somewhat more economical +# lines of codewise to set $DB::step_over_depth_saved +# when we enter the subroutine, but this gets called +# for EVERY callable line of code in a program that +# is being debugged, so we try to save every line of +# execution that we can. +# +sub isBreakPoint { + my ($fname, $line, $package) = @_ ; + my ($brkPt) ; + + if ( $DB::single && ($DB::step_over_depth < $DB::subroutine_depth) && ($DB::step_over_depth > 0) && !$DB::on) { + $DB::single = 0 ; + return 0 ; + } + # + # doing a step over/in + # + + if( $DB::single || $DB::signal ) { + $DB::single = 0 ; + $DB::signal = 0 ; + $DB::subroutine_depth = $DB::subroutine_depth ; + return 1 ; + } + # + # 1st Check to see if there is even a breakpoint there. + # 2nd If there is a breakpoint check to see if it's check box control is 'on' + # 3rd If there is any kind of expression, evaluate it and see if it's true. + # + $brkPt = &DB::getdbline($fname, $line) ; + + return 0 if( !$brkPt || !$brkPt->{'value'} || !breakPointEvalExpr($brkPt, $package) ) ; + + &DB::cleardbline($fname, $line) if( $brkPt->{'type'} eq 'temp' ) ; + + $DB::subroutine_depth = $DB::subroutine_depth ; + + return 1 ; +} # end of isBreakPoint + +# +# Check the breakpoint expression to see if it +# is true. +# +sub breakPointEvalExpr { + my ($brkPt, $package) = @_ ; + my (@result) ; + + return 1 unless $brkPt->{expr} ; # return if there is no expression + + no strict ; + + @result = &DB::dbeval($package, $brkPt->{'expr'}) ; + + use strict ; + + $DB::window->DoAlert($@) if $@ ; + + return $result[0] or @result ; # we could have a case where the 1st element is undefined + # but subsequent elements are defined + +} # end of breakPointEvalExpr + +# +# Evaluate the given expression, return the result. +# MUST BE CALLED from within DB::DB in order for it +# to properly interpret the vars +# +sub dbeval { + my($ptkdb__package, $ptkdb__expr) = @_ ; + my(@ptkdb__result, $ptkdb__str, $ptkdb__saveW) ; + my(@ptkdb_args) ; + + no strict ; + $ptkdb__saveW = $^W ; # save the state of the "warning"(-w) flag + $^W = 0 ; + + # + # This substitution is done so that + # we return HASH, as opposed to an ARRAY. + # An expression of %hash results in a + # list of key/value pairs. + # + + $ptkdb__expr =~ s/^\s*%/\\%/o ; + + @_ = @DB::saved_args ; # replace @_ arg array with what we came in with + + @ptkdb__result = eval <<__EVAL__ ; + + + \$\@ = \$DB::save_err ; + + package $ptkdb__package ; + + $ptkdb__expr ; + +__EVAL__ + + @ptkdb__result = ("ERROR ($@)") if $@ ; + + $^W = $ptkdb__saveW ; # restore the state of the "warning"(-w) flag + + use strict ; + + return @ptkdb__result ; +} # end of dbeval + +# +# Call back we give to our 'quit' button +# and binding to the WM_DELETE_WINDOW protocol +# to quit the debugger. +# +sub dbexit { + exit ; +} # end of dbexit + +# +# This is the primary entry point for the debugger. When a perl program +# is parsed with the -d(in our case -d:ptkdb) option set the parser will +# insert a call to DB::DB in front of every excecutable statement. +# +# Refs: Progamming Perl 2nd Edition, Larry Wall, O'Reilly & Associates, Chapter 8 +# +sub DB { + @DB::saved_args = @_ ; # save arg context + $DB::save_err = $@ ; # save value of $@ + my ($package, $filename, $line) = caller ; + my ($stop, $cnt) ; + + unless( $DB::ptkdb::isInitialized ) { + return if( $filename ne $0 ) ; # not in our target file + + &DB::Initialize($filename) ; + } + + if (!isBreakPoint($filename, $line, $package) ) { + $DB::single = 0 ; + $@ = $DB::save_err ; + return ; + } + + + + if ( !$DB::window ) { # not setup yet + $@ = $DB::save_err ; + return ; + } + + $DB::window->setup_main_window() unless $DB::window->{'main_window'} ; + + $DB::window->EnterActions() ; + + my ($saveP) ; + $saveP = $^P ; + $^P = 0 ; + + $DB::on = 1 ; + +# +# The user can specify this variable in one of the startup files, +# this will make the debugger run right after startup without +# the user having to press the 'run' button. +# + if( $DB::no_stop_at_start ) { + $DB::no_stop_at_start = 0 ; + $DB::on = 0 ; + $@ = $DB::save_err ; + return ; + } + + if( !$DB::sigint_disable ) { + $SIG{'INT'} = $DB::dbint_handler_save if $DB::dbint_handler_save ; # restore original signal handler + $SIG{'INT'} = "DB::dbexit" unless $DB::dbint_handler_save ; + } + + #$DB::window->{main_window}->raise() ; # bring us to the top make sure OUR event loop runs + $DB::window->{main_window}->focus() ; + + $DB::window->set_file($filename, $line) ; + # + # Refresh the exprs to see if anything has changed + # + updateExprs($package) ; + + # + # Update subs Page if necessary + # + $cnt = scalar keys %DB::sub ; + if ( $cnt != $DB::window->{'subs_list_cnt'} && $DB::window->{'subs_page_activated'} ) { + $DB::window->fill_subs_page() ; + $DB::window->{'subs_list_cnt'} = $cnt ; + } + # + # Update the subroutine stack menu + # + $DB::window->refresh_stack_menu() ; + + $DB::window->{run_flag} = 1 ; + + my ($evt, @result, $r) ; + + for( ; ; ) { + # + # we wait here for something to do + # + $evt = $DB::window->main_loop() ; + + last if( $evt eq 'step' ) ; + + $DB::single = 0 if ($evt eq 'run' ) ; + + if ($evt eq 'balloon_eval' ) { + $DB::window->code_motion_eval(&DB::dbeval($package, $DB::window->{'balloon_expr'})) ; + next ; + } + + if ( $evt eq 'qexpr' ) { + my $str ; + @result = &DB::dbeval($package, $DB::window->{'qexpr'}) ; + $DB::window->{'quick_entry'}->delete(0, 'end') ; # clear old text + if (exists $DB::window->{'quick_dumper'}) { + $DB::window->{'quick_dumper'}->Reset() ; + $DB::window->{'quick_dumper'}->Values( [ $#result == 0 ? @result : \@result ] ) ; + if( $DB::window->{'quick_dumper'}->can('Dumpxs') ) { + $str = $DB::window->{'quick_dumper'}->Dumpxs() ; + } + else { + $str = $DB::window->{'quick_dumper'}->Dump() ; + } + } + else { + $str = "@result" ; + } + $DB::window->{'quick_entry'}->insert(0, $str) ; #enter the text + $DB::window->{'quick_entry'}->selectionRange(0, 'end') ; # select it + $evt = 'update' ; # force an update on the expressions + } + + if( $evt eq 'expr' ) { + # + # Append the new expression to the list + # but first check to make sure that we don't + # already have it. + # + + if ( grep $_->{'expr'} eq $DB::window->{'expr'}, @{$DB::window->{'expr_list'}} ) { + $DB::window->DoAlert("$DB::window->{'expr'} is already listed") ; + next ; + } + + @result = &DB::dbeval($package, $DB::window->{expr}) ; + + if( scalar @result == 1 ) { + $r = $DB::window->insertExpr([ $result[0] ], $DB::window->{'data_list'}, $result[0], $DB::window->{'expr'}, $Devel::ptkdb::expr_depth) ; + } + else { + $r = $DB::window->insertExpr([ \@result ], $DB::window->{'data_list'}, \@result, $DB::window->{'expr'}, $Devel::ptkdb::expr_depth) ; + } + + # + # $r will be 1 if the expression was added succesfully, 0 if not, + # and it if wasn't added sucessfully it won't be reevalled the + # next time through. + # + push @{$DB::window->{'expr_list'}}, { 'expr' => $DB::window->{'expr'}, 'depth' => $Devel::ptkdb::expr_depth } if $r ; + + next ; + } + if( $evt eq 'update' ) { + updateExprs($package) ; + next ; + } + if( $evt eq 'reeval' ) { + # + # Reevaluate the contents of the expression eval window + # + my $txt = $DB::window->{'eval_text'}->get('0.0', 'end') ; + my @result = &DB::dbeval($package, $txt) ; + + $DB::window->updateEvalWindow(@result) ; + + next ; + } + last ; + } + $^P = $saveP ; + $SIG{'INT'} = "DB::dbint_handler" unless $DB::sigint_disable ; # set our signal handler + + $DB::window->LeaveActions() ; + + $@ = $DB::save_err ; + $DB::on = 0 ; + } # end of DB + +# +# This is another place where we'll try and keep the +# code as 'lite' as possible to prevent the debugger +# from slowing down the user's application +# +# When a perl program is parsed with the -d(in our case a -d:ptkdb) option +# the parser will route all subroutine calls through here, setting $DB::sub +# to the name of the subroutine to be called, leaving it to the debugger to +# make the actual subroutine call and do any pre or post processing it may +# need to do. In our case we take the opportunity to track the depth of the call +# stack so that we can update our 'Stack' menu when we stop. +# +# Refs: Progamming Perl 2nd Edition, Larry Wall, O'Reilly & Associates, Chapter 8 +# +# + sub sub { + my ($result, @result) ; +# +# See NOTES(1) +# + if( wantarray ) { + $DB::subroutine_depth += 1 unless $DB::on ; + $DB::single = 0 if ( ($DB::step_over_depth < $DB::subroutine_depth) && ($DB::step_over_depth >= 0) && !$DB::on) ; + + no strict ; # otherwise perl gripes about calling the sub by the reference + @result = &$DB::sub ; # call the subroutine by name + use strict ; + + $DB::subroutine_depth -= 1 unless $DB::on ; + $DB::single = 1 if ($DB::step_over_depth >= $DB::subroutine_depth && !$DB::on) ; + return @result ; + } + else { + $DB::subroutine_depth += 1 unless $DB::on ; + $DB::single = 0 if ( ($DB::step_over_depth < $DB::subroutine_depth) && ($DB::step_over_depth >= 0) && !$DB::on) ; + + no strict ; # otherwise perl gripes about calling the sub by the reference + $result = &$DB::sub ; # call the subroutine by name + use strict ; + + $DB::subroutine_depth -= 1 unless $DB::on ; + $DB::single = 1 if ($DB::step_over_depth >= $DB::subroutine_depth && !$DB::on) ; + return $result ; + } + + } # end of sub + +1 ; # return true value |