| 1 | # Copyright 2009, 2010, 2011 Kevin Ryde | ||
| 2 | |||
| 3 | # This file is part of Chart. | ||
| 4 | # | ||
| 5 | # Chart is free software; you can redistribute it and/or modify it under the | ||
| 6 | # terms of the GNU General Public License as published by the Free Software | ||
| 7 | # Foundation; either version 3, or (at your option) any later version. | ||
| 8 | # | ||
| 9 | # Chart is distributed in the hope that it will be useful, but WITHOUT ANY | ||
| 10 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS | ||
| 11 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more | ||
| 12 | # details. | ||
| 13 | # | ||
| 14 | # You should have received a copy of the GNU General Public License along | ||
| 15 | # with Chart. If not, see <http://www.gnu.org/licenses/>. | ||
| 16 | |||
| 17 | |||
| 18 | # Doesn't work. | ||
| 19 | |||
| 20 | # TieWeakNotify | ||
| 21 | # TieWeakField | ||
| 22 | # TieWeakProperty->setup ($obj, $pname) | ||
| 23 | # TieWeakProperty->setup ($obj, $pname) | ||
| 24 | |||
| 25 | # TieWeakProperty->set ($obj, $pname, $value) | ||
| 26 | |||
| 27 | |||
| 28 | package App::Chart::Glib::Ex::TieWeakNotify; | ||
| 29 | use 5.008; | ||
| 30 | use strict; | ||
| 31 | use warnings; | ||
| 32 | use Carp; | ||
| 33 | use Scalar::Util; | ||
| 34 | |||
| 35 | # uncomment this to run the ### lines | ||
| 36 | #use Smart::Comments; | ||
| 37 | |||
| 38 | my %instances; | ||
| 39 | |||
| 40 | sub set { | ||
| 41 | my ($class, $obj, $pname, $value) = @_; | ||
| 42 | if ($value) { | ||
| 43 | Scalar::Util::weaken ($obj->{$pname} = $value); | ||
| 44 | Scalar::Util::weaken ($instances{__PACKAGE__.'.'.$pname} = $value); | ||
| 45 | tie $instances{__PACKAGE__.'.'.$pname}, $class, $obj, $pname; | ||
| 46 | } else { | ||
| 47 | delete $instances{__PACKAGE__.'.'.$pname}; | ||
| 48 | $obj->{$pname} = $value; | ||
| 49 | } | ||
| 50 | ### $obj | ||
| 51 | } | ||
| 52 | |||
| 53 | sub TIESCALAR { | ||
| 54 | my ($class, $obj, $pname) = @_; | ||
| 55 | ### TieWeakNotify TIESCALAR() | ||
| 56 | ### $obj | ||
| 57 | ### $pname | ||
| 58 | my $self = bless [ $obj, $pname ], $class; | ||
| 59 | Scalar::Util::weaken ($self->[0]); | ||
| 60 | return $self; | ||
| 61 | } | ||
| 62 | |||
| 63 | # Devel::FindBlessedRefs callback may end up fetching | ||
| 64 | sub FETCH { | ||
| 65 | my ($self) = @_; | ||
| 66 | return $self->[0]; | ||
| 67 | # croak __PACKAGE__.' no FETCH allowed'; | ||
| 68 | } | ||
| 69 | |||
| 70 | sub STORE { | ||
| 71 | my ($self, $value) = @_; | ||
| 72 | ### TieWeakNotify STORE(): $value | ||
| 73 | |||
| 74 | if (! $value && (my $obj = $self->[0])) { | ||
| 75 | ### weakened away | ||
| 76 | delete $instances{__PACKAGE__.'.'.$self->[1]}; | ||
| 77 | $obj->notify ($self->[1]); | ||
| 78 | } | ||
| 79 | } | ||
| 80 | |||
| 81 | 1; | ||
| 82 | __END__ |