<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;"># -*- perl -*-
#
# Copyright (C) 2004-2011 Daniel P. Berrange
#
# This program is free software; You can redistribute it and/or modify
# it under the same terms as Perl itself. Either:
#
# a) the GNU General Public License as published by the Free
#   Software Foundation; either version 2, or (at your option) any
#   later version,
#
# or
#
# b) the "Artistic License"
#
# The file "COPYING" distributed along with this file provides full
# details of the terms and conditions of the two licenses.

=pod

=head1 NAME

Net::DBus::BaseObject - base class for exporting objects to the bus

=head1 SYNOPSIS

  # We're going to be a DBus object
  use base qw(Net::DBus::BaseObject);

  # Export a 'Greeting' signal taking a stringl string parameter
  dbus_signal("Greeting", ["string"]);

  # Export 'Hello' as a method accepting a single string
  # parameter, and returning a single string value
  dbus_method("Hello", ["string"], ["string"]);

  sub new {
      my $class = shift;
      my $service = shift;
      my $self = $class-&gt;SUPER::new($service, "/org/demo/HelloWorld");

      bless $self, $class;

      return $self;
  }

  sub _dispatch_object {
      my $self = shift;
      my $connection = shift;
      my $message = shift;

      if (....$message refers to a object's method ... ) {
         ...dispatch this object's interfaces/methods...
         return $reply;
      }
  }

=head1 DESCRIPTION

This the base of all objects which are exported to the
message bus. It provides the core support for type introspection
required for objects exported to the message. When sub-classing
this object, the C&lt;_dispatch&gt; object should be implemented to
handle processing of incoming messages. The L&lt;Net::DBus::Exporter&gt;
module is used to declare which methods (and signals) are being
exported to the message bus.

All packages inheriting from this, will automatically have the
interface C&lt;org.freedesktop.DBus.Introspectable&gt; registered
with L&lt;Net::DBus::Exporter&gt;, and the C&lt;Introspect&gt; method within
this exported.

Application developers will rarely want to use this class directly,
instead either L&lt;Net::DBus::Object&gt; or C&lt;Net::DBus::ProxyObject&gt;
are the common choices. This class will only be used if wanting to
write a new approach to dispatching incoming method calls.

=head1 METHODS

=over 4

=cut

package Net::DBus::BaseObject;

use 5.006;
use strict;
use warnings;

our $ENABLE_INTROSPECT;

BEGIN {
    if ($ENV{DBUS_DISABLE_INTROSPECT}) {
	$ENABLE_INTROSPECT = 0;
    } else {
	$ENABLE_INTROSPECT = 1;
    }
}

use Net::DBus::Exporter "org.freedesktop.DBus.Introspectable";

dbus_method("Introspect", [], ["string"], {return_names =&gt; ["xml_data"]});

dbus_method("Get", ["string", "string"], [["variant"]], "org.freedesktop.DBus.Properties", {return_names =&gt; ["value"], param_names =&gt; ["interface_name", "property_name"]});
dbus_method("GetAll", ["string"], [["dict", "string", ["variant"]]], "org.freedesktop.DBus.Properties", {return_names =&gt; ["properties"], param_names =&gt; ["interface_name"]});
dbus_method("Set", ["string", "string", ["variant"]], [], "org.freedesktop.DBus.Properties", {param_names =&gt; ["interface_name", "property_name", "value"]});

=item my $object = Net::DBus::BaseObject-&gt;new($service, $path)

This creates a new DBus object with an path of C&lt;$path&gt;
registered within the service C&lt;$service&gt;. The C&lt;$path&gt;
parameter should be a string complying with the usual
DBus requirements for object paths, while the C&lt;$service&gt;
parameter should be an instance of L&lt;Net::DBus::Service&gt;.
The latter is typically obtained by calling the C&lt;export_service&gt;
method on the L&lt;Net::DBus&gt; object.

=item my $object = Net::DBus::BaseObject-&gt;new($parentobj, $subpath)

This creates a new DBus child object with an path of C&lt;$subpath&gt;
relative to its parent C&lt;$parentobj&gt;. The C&lt;$subpath&gt;
parameter should be a string complying with the usual
DBus requirements for object paths, while the C&lt;$parentobj&gt;
parameter should be an instance of L&lt;Net::DBus::BaseObject&gt;.

=cut

sub new {
    my $class = shift;
    my $self = {};

    my $parent = shift;
    my $path = shift;

    $path =~ s{/$}{} unless $path eq '/';

    $self-&gt;{parent} = $parent;
    if ($parent-&gt;isa(__PACKAGE__)) {
	$path =~ s{^/}{};
	$self-&gt;{service} = $parent-&gt;get_service;
	$self-&gt;{object_path} = $parent-&gt;get_object_path;
	$self-&gt;{object_path} .= '/' unless $self-&gt;{object_path} =~ m{/$};
	$self-&gt;{object_path} .= $path;
    } else {
	$path = "/$path" unless $path =~ m{^/};
	$self-&gt;{service} = $parent;
	$self-&gt;{object_path} = $path;
    }

    $self-&gt;{interface} = shift;
    $self-&gt;{introspector} = undef;
    $self-&gt;{introspected} = 0;
    $self-&gt;{callbacks} = {};
    $self-&gt;{children} = {};

    bless $self, $class;

    if ($self-&gt;{parent}-&gt;isa(__PACKAGE__)) {
	$self-&gt;{parent}-&gt;_register_child($self);
    } else {
	$self-&gt;get_service-&gt;_register_object($self);
    }

    return $self;
}


=item $object-&gt;disconnect();

This method disconnects the object from the bus, such that it
will no longer receive messages sent by other clients. Any
child objects will be recursively disconnected too. After an
object has been disconnected, it is possible for Perl to
garbage collect the object instance. It will also make it
possible to connect a newly created object to the same path.

=cut

sub disconnect {
    my $self = shift;

    return unless $self-&gt;{parent};

    foreach my $child (keys %{$self-&gt;{children}}) {
	$self-&gt;_unregister_child($self-&gt;{children}-&gt;{$child});
    }

    if ($self-&gt;{parent}-&gt;isa(__PACKAGE__)) {
	$self-&gt;{parent}-&gt;_unregister_child($self);
    } else {
	$self-&gt;get_service-&gt;_unregister_object($self);
    }
    $self-&gt;{parent} = undef;
}

=item my $bool = $object-&gt;is_connected

Returns a true value if the object is connected to the bus,
and thus capable of being accessed by remote clients. Returns
false if the object is disconnected &amp; thus ready for garbage
collection. All objects start off in the connected state, and
will only transition if the C&lt;disconnect&gt; method is called.

=cut

sub is_connected {
    my $self = shift;

    return 0 unless $self-&gt;{parent};

    if ($self-&gt;{parent}-&gt;isa(__PACKAGE__)) {
	return $self-&gt;{parent}-&gt;is_connected;
    }
    return 1;
}

sub DESTROY {
    my $self = shift;
    # XXX there are some issues during global
    # destruction which need to be better figured
    # out before this will work
    #$self-&gt;disconnect;
}

sub _register_child {
    my $self = shift;
    my $object = shift;

    $self-&gt;get_service-&gt;_register_object($object);
    $self-&gt;{children}-&gt;{$object-&gt;get_object_path} = $object;
}


sub _unregister_child {
    my $self = shift;
    my $object = shift;

    $self-&gt;get_service-&gt;_unregister_object($object);
    delete $self-&gt;{children}-&gt;{$object-&gt;get_object_path};
}

# return a list of sub nodes for this object
sub _get_sub_nodes {
    my $self = shift;
    my %uniq;

    my $base = $self-&gt;{object_path};
    $base .= '/' if $base ne '/';
    foreach ( keys( %{$self-&gt;{children}} ) ) {
      m/^$base([^\/]+)/;
      $uniq{$1} = 1;
    }

    return sort( keys( %uniq ) );
}

=item my $service = $object-&gt;get_service

Retrieves the L&lt;Net::DBus::Service&gt; object within which this
object is exported.

=cut

sub get_service {
    my $self = shift;
    return $self-&gt;{service};
}


=item my $path = $object-&gt;get_object_path

Retrieves the path under which this object is exported

=cut

sub get_object_path {
    my $self = shift;
    return $self-&gt;{object_path};
}

=item $object-&gt;emit_signal_in($name, $interface, $client, @args);

Emits a signal from the object, with a name of C&lt;$name&gt;. If the
C&lt;$interface&gt; parameter is defined, the signal will be scoped
within that interface. If the C&lt;$client&gt; parameter is defined,
the signal will be unicast to that client on the bus. The
signal and the data types of the arguments C&lt;@args&gt; must have
been registered with L&lt;Net::DBus::Exporter&gt; by calling the
C&lt;dbus_signal&gt; method.

=cut

sub emit_signal_in {
    my $self = shift;
    my $name = shift;
    my $interface = shift;
    my $destination = shift;
    my @args = @_;

    die "object is disconnected from the bus" unless $self-&gt;is_connected;

    my $con = $self-&gt;get_service-&gt;get_bus-&gt;get_connection;

    my $signal = $con-&gt;make_signal_message($self-&gt;get_object_path,
					   $interface,
					   $name);
    if ($destination) {
	$signal-&gt;set_destination($destination);
    }

    my $ins = $self-&gt;_introspector;
    if ($ins) {
	$ins-&gt;encode($signal, "signals", $name, "params", @args);
    } else {
	$signal-&gt;append_args_list(@args);
    }
    $con-&gt;send($signal);

    # Short circuit locally registered callbacks
    if (exists $self-&gt;{callbacks}-&gt;{$interface} &amp;&amp;
	exists $self-&gt;{callbacks}-&gt;{$interface}-&gt;{$name}) {
	my $cb = $self-&gt;{callbacks}-&gt;{$interface}-&gt;{$name};
	&amp;$cb(@args);
    }
}

=item $self-&gt;emit_signal_to($name, $client, @args);

Emits a signal from the object, with a name of C&lt;$name&gt;. The
signal and the data types of the arguments C&lt;@args&gt; must have
been registered with L&lt;Net::DBus::Exporter&gt; by calling the
C&lt;dbus_signal&gt; method. The signal will be sent only to the
client named by the C&lt;$client&gt; parameter.

=cut

sub emit_signal_to {
    my $self = shift;
    my $name = shift;
    my $destination = shift;
    my @args = @_;

    my $intro = $self-&gt;_introspector;
    if (!$intro) {
	die "no introspection data available for '" . $self-&gt;get_object_path .
	    "', use the emit_signal_in method instead";
    }
    my @interfaces = $intro-&gt;has_signal($name);
    if ($#interfaces == -1) {
	die "no signal with name '$name' is exported in object '" .
	    $self-&gt;get_object_path . "'\n";
    } elsif ($#interfaces &gt; 0) {
	die "signal '$name' is exported in more than one interface of '" .
	    $self-&gt;get_object_path . "', use the emit_signal_in method instead.";
    }
    $self-&gt;emit_signal_in($name, $interfaces[0], $destination, @args);
}

=item $self-&gt;emit_signal($name, @args);

Emits a signal from the object, with a name of C&lt;$name&gt;. The
signal and the data types of the arguments C&lt;@args&gt; must have
been registered with L&lt;Net::DBus::Exporter&gt; by calling the
C&lt;dbus_signal&gt; method. The signal will be broadcast to all
clients on the bus.

=cut

sub emit_signal {
    my $self = shift;
    my $name = shift;
    my @args = @_;

    $self-&gt;emit_signal_to($name, undef, @args);
}

=item $object-&gt;connect_to_signal_in($name, $interface, $coderef);

Connects a callback to a signal emitted by the object. The C&lt;$name&gt;
parameter is the name of the signal within the object, and C&lt;$coderef&gt;
is a reference to an anonymous subroutine. When the signal C&lt;$name&gt;
is emitted by the remote object, the subroutine C&lt;$coderef&gt; will be
invoked, and passed the parameters from the signal. The C&lt;$interface&gt;
parameter is used to specify the explicit interface defining the
signal to connect to.

=cut

sub connect_to_signal_in {
    my $self = shift;
    my $name = shift;
    my $interface = shift;
    my $code = shift;

    die "object is disconnected from the bus" unless $self-&gt;is_connected;

    $self-&gt;{callbacks}-&gt;{$interface} = {} unless
	exists $self-&gt;{callbacks}-&gt;{$interface};
    $self-&gt;{callbacks}-&gt;{$interface}-&gt;{$name} = $code;
}

=item $object-&gt;connect_to_signal($name, $coderef);

Connects a callback to a signal emitted by the object. The C&lt;$name&gt;
parameter is the name of the signal within the object, and C&lt;$coderef&gt;
is a reference to an anonymous subroutine. When the signal C&lt;$name&gt;
is emitted by the remote object, the subroutine C&lt;$coderef&gt; will be
invoked, and passed the parameters from the signal.

=cut

sub connect_to_signal {
    my $self = shift;
    my $name = shift;
    my $code = shift;

    my $ins = $self-&gt;_introspector;
    if (!$ins) {
	die "no introspection data available for '" . $self-&gt;get_object_path .
	    "', use the connect_to_signal_in method instead";
    }
    my @interfaces = $ins-&gt;has_signal($name);

    if ($#interfaces == -1) {
	die "no signal with name '$name' is exported in object '" .
	    $self-&gt;get_object_path . "'\n";
    } elsif ($#interfaces &gt; 0) {
	die "signal with name '$name' is exported " .
	    "in multiple interfaces of '" . $self-&gt;get_object_path . "'" .
	    "use the connect_to_signal_in method instead";
    }

    $self-&gt;connect_to_signal_in($name, $interfaces[0], $code);
}


sub _dispatch {
    my $self = shift;
    my $connection = shift;
    my $message = shift;

    my $reply;
    my $method_name = $message-&gt;get_member;
    my $interface = $message-&gt;get_interface;
    if ((defined $interface) &amp;&amp;
        ($interface eq "org.freedesktop.DBus.Introspectable")) {
	if ($method_name eq "Introspect" &amp;&amp;
	    $self-&gt;_introspector &amp;&amp;
	    $ENABLE_INTROSPECT) {
	    if ($message-&gt;get_args_list) {
		$reply = $connection-&gt;make_error_message($message,
							 "org.freedesktop.DBus.Error.Failed",
							 "too many parameters for method 'Introspect'");
	    } else {
	    my $xml = $self-&gt;_introspector-&gt;format($self);
	    $reply = $connection-&gt;make_method_return_message($message);

	    $self-&gt;_introspector-&gt;encode($reply, "methods", $method_name, "returns", $xml);
	    }
	}
    } elsif ((defined $interface) &amp;&amp;
	     ($interface eq "org.freedesktop.DBus.Properties")) {
	if ($method_name eq "Get") {
	    $reply = $self-&gt;_dispatch_prop_read($connection, $message);
	} elsif ($method_name eq "GetAll") {
	    $reply = $self-&gt;_dispatch_all_prop_read($connection, $message);
	} elsif ($method_name eq "Set") {
	    $reply = $self-&gt;_dispatch_prop_write($connection, $message);
	}
    } else {
	$reply = $self-&gt;_dispatch_object($connection, $message);
    }

    if (!$reply) {
	$reply = $connection-&gt;make_error_message($message,
						 "org.freedesktop.DBus.Error.UnknownMethod",
						 "No such method " . ref($self) . "-&gt;" . $method_name);
    }

    if ($message-&gt;get_no_reply()) {
	# Not sending reply
    } else {
	$self-&gt;get_service-&gt;get_bus-&gt;get_connection-&gt;send($reply);
    }
}


=item $reply = $object-&gt;_dispatch_object($connection, $message);

The C&lt;_dispatch_object&gt; method is to be used to handle dispatch of
methods implemented by the object. The default implementation is
a no-op and should be overridden by subclasses todo whatever
processing is required. If the C&lt;$message&gt; could be handled then
another C&lt;Net::DBus::Binding::Message&gt; instance should be returned
for the reply. If C&lt;undef&gt; is returned, then a generic error will
be returned to the caller.

=cut

sub _dispatch_object {
    my $self = shift;
    my $connection = shift;
    my $message = shift;

    return 0;
}


=item $currvalue = $object-&gt;_dispatch_property($name);
=item $object-&gt;_dispatch_property($name, $newvalue);

The C&lt;_dispatch_property&gt; method is to be used to handle dispatch
of property reads and writes. The C&lt;$name&gt; parameter is the name
of the property being accessed. If C&lt;$newvalue&gt; is supplied then
the property is to be updated, otherwise the current value is to
be returned. The default implementation will simply raise an
error, so must be overridden in subclasses.

=cut

sub _dispatch_property {
    my $self = shift;
    my $name = shift;
    my $value = shift;

    die "No method for property $name";
}


sub _dispatch_prop_read {
    my $self = shift;
    my $connection = shift;
    my $message = shift;

    my $ins = $self-&gt;_introspector;

    if (!$ins) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "no introspection data exported for properties");
    }

    my ($pinterface, $pname, @pargs) = eval { $ins-&gt;decode($message, "methods", "Get", "params") };
    if ($@) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "$@");
    }
    if (@pargs) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "too many parameters for method 'Get'");
    }
    if (not defined $pinterface) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "no interface was specified");
    }
    if (not defined $pname) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "no property was specified for interface '$pinterface'");
    }

    if (!$ins-&gt;has_property($pname, $pinterface)) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "no property '$pname' exported in interface '$pinterface'");
    }

    if (!$ins-&gt;is_property_readable($pinterface, $pname)) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "property '$pname' in interface '$pinterface' is not readable");
    }

    my $value = eval {
	$self-&gt;_dispatch_property($pname);
    };
    if ($@) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "error reading '$pname' in interface '$pinterface': $@");
    } else {
	my $reply = $connection-&gt;make_method_return_message($message);
	
	$self-&gt;_introspector-&gt;encode($reply, "methods", "Get", "returns", $value);
	return $reply;
    }
}

sub _dispatch_all_prop_read {
    my $self = shift;
    my $connection = shift;
    my $message = shift;

    my $ins = $self-&gt;_introspector;

    if (!$ins) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "no introspection data exported for properties");
    }

    my ($pinterface, @pargs) = eval { $ins-&gt;decode($message, "methods", "GetAll", "params") };
    if ($@) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "$@");
    }
    if (@pargs) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "too many parameters for method 'GetAll'");
    }
    if (not defined $pinterface) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "no interface was specified");
    }

    my %values = ();
    foreach my $pname ($ins-&gt;list_properties($pinterface)) {
    	unless ($ins-&gt;is_property_readable($pinterface, $pname)) {
		next; # skip write-only properties
	}

	$values{$pname} = eval {
	    $self-&gt;_dispatch_property($pname);
	};
	if ($@) {
	    return $connection-&gt;make_error_message($message,
						   "org.freedesktop.DBus.Error.Failed",
						   "error reading '$pname' in interface '$pinterface': $@");
	}
    }

    my $reply = $connection-&gt;make_method_return_message($message);

    $self-&gt;_introspector-&gt;encode($reply, "methods", "GetAll", "returns", \%values);
    return $reply;
}

sub _dispatch_prop_write {
    my $self = shift;
    my $connection = shift;
    my $message = shift;

    my $ins = $self-&gt;_introspector;

    if (!$ins) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "no introspection data exported for properties");
    }

    my ($pinterface, $pname, $pvalue, @pargs) = eval { $ins-&gt;decode($message, "methods", "Set", "params") };
    if ($@) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "$@");
    }
    if (@pargs) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "too many parameters for method 'Set'");
    }
    if (not defined $pinterface) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "no interface was specified");
    }
    if (not defined $pname) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "no property was specified for interface '$pinterface'");
    }
    if (not defined $pvalue) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "no value was specified for property '$pname' in interface '$pinterface'");
    }

    if (!$ins-&gt;has_property($pname, $pinterface)) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "no property '$pname' exported in interface '$pinterface'");
    }

    if (!$ins-&gt;is_property_writable($pinterface, $pname)) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "property '$pname' in interface '$pinterface' is not writable");
    }

    eval {
	$self-&gt;_dispatch_property($pname, $pvalue);
    };
    if ($@) {
	return $connection-&gt;make_error_message($message,
					       "org.freedesktop.DBus.Error.Failed",
					       "error writing '$pname' in interface '$pinterface': $@");
    } else {
	return $connection-&gt;make_method_return_message($message);
    }
}


sub _introspector {
    my $self = shift;

    if (!$self-&gt;{introspected}) {
	$self-&gt;{introspector} = Net::DBus::Exporter::_dbus_introspector(ref($self));
	$self-&gt;{introspected} = 1;
    }
    return $self-&gt;{introspector};
}

1;


=pod

=back

=head1 AUTHOR

Daniel P. Berrange

=head1 COPYRIGHT

Copyright (C) 2005-2011 Daniel P. Berrange

=head1 SEE ALSO

L&lt;Net::DBus&gt;, L&lt;Net::DBus::Service&gt;, L&lt;Net::DBus::Object&gt;,
L&lt;Net::DBus::ProxyObject&gt;, L&lt;Net::DBus::Exporter&gt;,
L&lt;Net::DBus::RemoteObject&gt;

=cut
</pre></body></html>