#!/opt/bin/perl

=head1 NAME

mcp-atspi - inspect and control desktop applications through AT-SPI

=head1 SYNOPSIS

   mcp-atspi --stdio
   mcp-atspi --bus unix:path=/run/user/1000/at-spi/bus_0

=head1 DESCRIPTION

AT-SPI exposes the semantic structure of applications, including widgets,
text, selections, values and actions. Use applications to find an application
or window, tree to explore its accessible objects, and inspect for details.
Object IDs are opaque and local to this broker. Discover them again after a
restart or when the application changes its UI.

The session D-Bus, X11 AT_SPI_BUS root property and AT_SPI_BUS_ADDRESS
environment variable may advertise different accessibility buses. This broker
tries all of them and any explicitly supplied addresses. Failed connections
are reported by applications, not treated as empty registries. It does not
implicitly enable accessibility, although discovering the session bus may
start its launcher.

The broker uses Net::DBus directly, without libatspi or a GUI toolkit.
Calls are synchronous with short timeouts and bounded tree traversal. AT-SPI
implementations vary; an advertised interface may be incomplete or fail.
Cross-application child references are not traversed.

=head1 TOOLS

=over

=item applications

List applications and their top-level accessible objects, across all buses.
Also report discovery and enumeration errors.

=item tree

Textual subtree with bounded depth and node count. Optional literal role/name
filters (case-insensitive) and state filters. Limits apply to visited nodes,
not just matches. Inspect individual objects for more information.

=item inspect, read-text

Object details, including advertised interfaces, actions, screen coordinates,
text length, values and known related objects. Read-text returns a bounded
character range.

=item invoke, edit-text, set-value, select, focus

Invoke an advertised action (first by default), set/insert/delete text,
change a numeric value, select children or text, or request keyboard focus.
A false result from an AT-SPI method is a failure, not success.

=item keyboard, mouse

Simple X11 input via xdotool. Keyboard takes a list of key combinations
or literal text; mouse takes screen coordinates and an optional button.
Input is desktop-wide, not addressed to an accessible object.
Use keyboard only as a last resort: prefer invoke, edit-text, set-value
and select. Selecting or focusing an accessible object does not guarantee
that its window has X11 keyboard focus. Verify the intended window and
widget before sending keys, but note that focus can change at any time,
including during input. Success means input was sent, not that it reached
the intended object.

=item accessibility

Set session C<org.a11y.Status.IsEnabled>. Omit enabled to query the status.
This does not force any particular application to register.

=back

=head1 PERMISSIONS

Profile C<atspi-NAME>. Actions are read and write. A target selector offers
window, application instance (default), program, desktop and any desktop
scopes where applicable. Program identity uses the bus peer's Unix UID and
executable, not the advertised accessible name. Instance and window rules
are local to this broker lifetime and pruned lazily. IDs are retired when
disappearance or a changed ancestry is observed. AT-SPI does not guarantee
that all providers report object destruction or never reuse a path;
rediscover targets when the UI changes.

Global input and accessibility changes require desktop authority. The
broker checks available screen-lock indicators and known local permission
dialogs before writes. This is not a security boundary against arbitrary
applications, custom lockers or dialogs; run the broker in a trusted
desktop session. X11 is currently required for writes other than changing
accessibility status. Screen lock detection is best effort.

=head1 OPTIONS

=over

=item --bus ADDRESS

Additional accessibility D-Bus address. Repeat to specify multiple buses.
Normal discovery is still performed. No client-supplied bus addresses.

=back

Shared switches are documented in
L<AnyEvent::MCP::Server::Simple/COMMON COMMAND-LINE OPTIONS>.

=cut

use common::sense;
use Types::Serialiser ();

use Scalar::Util qw(looks_like_number);
use POSIX ();
use Time::HiRes qw(time);
use Net::DBus qw(dbus_int32 dbus_uint32 dbus_double dbus_string dbus_boolean dbus_variant);
use Net::DBus::Binding::Bus ();

use AnyEvent::MCP ();
use AnyEvent::MCP::Server::Permissions ();
use AnyEvent::MCP::Server::Simple;

my $options = mcp_getoptions
   {
      usage       => "Usage: mcp-atspi [OPTION]...\n",
      description => "Inspect and control desktop applications through AT-SPI.",
      options     => [["--bus ADDRESS", "Additional accessibility bus address (repeatable)"]],
      examples    => "  mcp-atspi --stdio\n",
   },
   "bus=s@" => \my @addresses,
;
@ARGV and die "Unexpected arguments\n";

my $permissions = AnyEvent::MCP::Server::Permissions->new (
   name    => "atspi-$options->{name}",
   actions => {
      read  => "Inspect accessible desktop applications",
      write => "Control desktop applications or change accessibility settings",
   },
);
mcp_permissions $permissions;

mcp_config
   server_name        => "mcp-atspi",
   server_version     => $AnyEvent::MCP::VERSION,
   short_instructions => "Semantic desktop UI: applications, textual trees, object inspection, text, actions, values, selections and input.",
   instructions       => "List applications, then tree/inspect objects by opaque ID. IDs may become stale as the UI changes. "
                       . "Prefer object-directed invoke, edit-text, set-value and select. Use keyboard/mouse only as a last resort: desktop-wide, not object-directed. "
                       . "Verify X11 window and widget focus before keyboard input; focus checks are racy and AT-SPI focus/selection alone is insufficient. "
                       . "Refresh applications/tree after UI changes. Errors from applications may leave writes with unknown outcome.",
   on_request         => sub {
      my ($server, $req) = @_;
      my $id = $req->{args}{object};
      mcp_log_request $server, $req, (defined $id && !ref $id ? (object => $id) : ());
   };

my $root     = "/org/a11y/atspi/accessible/root";
my $null     = "/org/a11y/atspi/null";
my $registry = "org.a11y.atspi.Registry";
my $access   = "org.a11y.atspi.Accessible";
my $prop     = "org.freedesktop.DBus.Properties";
my $dbus     = "org.freedesktop.DBus";
my $dbuspath = "/org/freedesktop/DBus";
my $a11ybus  = "org.a11y.Bus";
my $a11ypath = "/org/a11y/bus";
my $status   = "org.a11y.Status";
my $json     = AnyEvent::MCP::json->allow_nonref;
my $epoch    = unpack "H*", AnyEvent::MCP::random_bytes (8);
my $desktop  = "D" . unpack ("H*", AnyEvent::MCP::utf8enc ("$<:" . ($ENV{DISPLAY} || $ENV{WAYLAND_DISPLAY} || $ENV{DBUS_SESSION_BUS_ADDRESS} || "session"))) . "/";
my $display  = $ENV{DISPLAY} || $ENV{WAYLAND_DISPLAY} || "session";
my ($session, %buses, %address_bus, %objects, $next_bus, $next_object);
our $deadline;

sub dbus_dec;

sub dbus_dec {
   my ($v) = @_;

   return [map { dbus_dec $_ } @$v] if ref $v eq "ARRAY";
   return +{ map { (dbus_dec $_) => (dbus_dec $v->{$_}) } keys %$v } if ref $v eq "HASH";
   return AnyEvent::MCP::utf8dec $v if defined $v && !ref $v && !utf8::is_utf8 ($v) && $v =~ /[\x80-\xff]/;
   $v
}

sub call {
   my ($bus, $name, $path, $interface, $method, @args) = @_;

   my $timeout = defined $deadline ? int (1000 * ($deadline - time)) : 1000;
   $timeout > 0 or die "AT-SPI operation time limit reached\n";
   $timeout = 1000 if $timeout > 1000;

   my $msg = $bus->make_method_call_message ($name, $path, $interface, $method);
   $msg->append_args_list (@args);
   my @reply = map { dbus_dec $_ } $bus->send_with_reply_and_block ($msg, $timeout)->get_args_list;

   wantarray ? @reply : $reply[0]
}

sub bus_call {
   my ($bus, $method, @args) = @_;

   call $bus, $dbus, $dbuspath, $dbus, $method, @args
}

sub session_bus {
   return $session if $session && $session->is_connected;

   $session = Net::DBus::Binding::Bus->new (type => Net::DBus::Binding::Bus::SESSION ())
}

sub status_call {
   my ($method, @args) = @_;

   call +(session_bus), $a11ybus, $a11ypath, $prop, $method, @args
}

sub x11 {
   require X11::Protocol;
   X11::Protocol->new ($ENV{DISPLAY} || die "No X11 display\n")
}

sub xproperty {
   my ($x, $window, $name) = @_;

   my ($value) = $x->GetProperty ($window, $x->atom ($name), 0, 0, 4096, 0);
   $value
}

sub short_error {
   my $error = "$_[0]";
   $error =~ s/\s+\z//;
   substr $error, 0, 500
}

sub discover {
   my %addresses = map { $_ => "explicit" } @addresses;
   $addresses{$ENV{AT_SPI_BUS_ADDRESS}} = "environment" if length $ENV{AT_SPI_BUS_ADDRESS};

   my @errors;
   my $address = eval { call +(session_bus), $a11ybus, $a11ypath, $a11ybus, "GetAddress" };
   push @errors, "Session bus: " . short_error ($@) if $@;
   $addresses{$address} = "session" if length $address;

   if ($ENV{DISPLAY}) {
      my $xaddress = eval { my $x = x11; xproperty $x, $x->root, "AT_SPI_BUS" };
      push @errors, "X11 discovery: " . short_error ($@) if $@;
      $addresses{$xaddress} = "X11" if length $xaddress;
   }

   my @online;
   my %seen;
   for my $address (sort keys %addresses) {
      my $b = $address_bus{$address};

      unless ($b && $b->{conn}->is_connected) {
         $b = eval {
            my $conn = Net::DBus::Binding::Bus->new (address => $address);
            my $guid = bus_call $conn, "GetId";
            if ($buses{$guid} && $buses{$guid}{conn}->is_connected) {
               $buses{$guid}
            } else {
               $buses{$guid} = {
                  conn => $conn, guid => $guid, id => $epoch . "-" . ++$next_bus, refs => {},
               }
            }
         };
         if ($@) {
            push @errors, "$addresses{$address} ($address): " . short_error ($@);
            next;
         }
         $address_bus{$address} = $b;
      }

      push @online, $b unless $seen{$b->{id}}++;
   }

   (\@online, \@errors, \%addresses)
}

sub object_call {
   my ($o, $interface, $method, @args) = @_;

   $o->{bus}{conn}->is_connected or die "Accessibility bus disconnected; list applications again\n";
   call $o->{bus}{conn}, $o->{name}, $o->{path}, $interface, $method, @args
}

sub get_property {
   my ($o, $interface, $name) = @_;

   object_call $o, $prop, "Get", $interface, $name
}

sub properties {
   my ($o, $interface, @names) = @_;

   # Qt before 6.9.2 can crash on GetAll (QTBUG-137344, also Qt 5).
   +{ map { $_ => (scalar get_property $o, $interface, $_) } @names }
}

my @states = qw(invalid active armed busy checked collapsed defunct editable enabled expandable expanded focusable focused
                has_tooltip horizontal iconified modal multi_line multiselectable opaque pressed resizable selectable selected
                sensitive showing single_line stale transient vertical visible manages_descendants indeterminate required
                truncated animated invalid_entry supports_autocompletion selectable_text is_default visited checkable has_popup read_only);

sub states {
   my ($o) = @_;

   my $bits = object_call $o, $access, "GetState";
   [map $states[$_], grep { ($bits->[$_ >> 5] >> ($_ & 31)) & 1 } 0 .. $#states]
}

sub retire;

sub live {
   my ($o) = @_;

   my $s = states $o;
   unless (!grep /\A(?:defunct|invalid|stale)\z/, @$s) {
      retire $o if grep $_ eq "defunct", @$s;
      die "Accessible object is stale; inspect the tree again\n";
   }
   $s
}

sub retire {
   my ($o) = @_;

   delete $objects{$o->{id}};
   my $key = "$o->{name}\0$o->{path}";
   delete $o->{bus}{refs}{$key} if $o->{bus}{refs}{$key} eq $o->{id};
}

sub intern {
   my ($b, $ref, $app, $window) = @_;

   my ($name, $path) = @$ref;
   return unless length $path && $path ne $null;
   return unless length $name || $app;
   if ($name !~ /^:/) {
      $name = length $name ? bus_call ($b->{conn}, "GetNameOwner", $name) : $app->{name};
   }
   return if $app && $name ne $app->{name};

   my $key = "$name\0$path";
   my $o = $objects{$b->{refs}{$key}};
   my $win = $window ? $window->{id} : "";
   if ($o) {
      return $o if !$app || $o->{app} eq $app->{id} && ($win eq $o->{window} || !$win && $o->{window} eq $o->{id});
      retire $o;
   }

   my $id = "$b->{id}:" . ++$next_object;
   $o = $objects{$id} = {
      id => $id, bus => $b, name => $name, path => $path,
      app => $app ? $app->{id} : $id,
      window => $app ? ($win || $id) : "",
   };
   $b->{refs}{$key} = $id;
   $o
}

sub children {
   my ($o, $p, $limit) = @_;

   my $refs = eval { object_call $o, $access, "GetChildren" };
   if (!$refs) {
      $refs = [];
      my $n = $p->{ChildCount};
      $n = $limit if $n > $limit;
      push @$refs, (scalar object_call $o, $access, "GetChildAtIndex", dbus_int32 ($_)) for 0 .. $n - 1;
   }

   my $complete = @$refs == $p->{ChildCount};
   @$refs = grep $_->[1] ne $null, @$refs;
   $complete &&= @$refs <= $limit;
   splice @$refs, $limit if @$refs > $limit;
   ($refs, $complete)
}

sub peer {
   my ($o) = @_;

   my $pid = bus_call $o->{bus}{conn}, "GetConnectionUnixProcessID", $o->{name};
   my $uid = bus_call $o->{bus}{conn}, "GetConnectionUnixUser", $o->{name};
   my $exe = readlink "/proc/$pid/exe";

   ($pid, $uid, $exe)
}

sub program_prefix {
   my ($app) = @_;

   my $exe = $app->{exe};
   $desktop . "P" . (defined $exe ? unpack ("H*", "$app->{uid}:$exe") : "unknown") . "/"
}

sub instance_prefix {
   my ($app) = @_;

   program_prefix ($app) . "I" . $app->{id} . "/"
}

sub window_prefix {
   my ($app, $window) = @_;

   instance_prefix ($app) . "W" . $window->{id} . "/"
}

sub label {
   my ($s) = @_;

   $json->encode (substr $s, 0, 160)
}

sub permission {
   my ($req, $action, $app, $window, $reason) = @_;

   my @choices;
   my $value = $desktop;
   my $default = "^$desktop";

   if ($app) {
      my $instance = instance_prefix $app;
      $value = $instance;
      $default = "^$instance";

      if ($window) {
         $value = window_prefix $app, $window;
         push @choices, { id => "window", label => "This window: " . label ($window->{label}), match => "^$value" };
      }

      push @choices, { id => "instance", label => "This application instance: " . label ($app->{label}), match => "^$instance" };
      push @choices, { id => "program", label => "This program: " . label ($app->{exe}), match => "^" . program_prefix ($app) }
         if defined $app->{exe};
   }

   push @choices,
      { id => "desktop", label => "This desktop: $display", match => "^$desktop" },
      { id => "any", label => "Any desktop served by this profile", match => "^D" };

   $req->require_permission ({
      tool => $req->{tool}, action => $action, reason => $reason,
      sandbox_grants => [],
      dimensions => {
         target => { label => "Target scope", value => $value, choices => \@choices, default => $default },
      },
   });
}

sub resolve {
   my ($id) = @_;

   my $o = $objects{$id} or die "Unknown or stale object ID; list applications/tree again\n";
   my $app = $objects{$o->{app}} or die "Application disappeared; list applications again\n";
   my $window = $objects{$o->{window}} if length $o->{window};
   length $o->{window} && !$window and die "Window disappeared; list applications again\n";

   # unique bus names do not get reassigned, even if a well-known name does.
   my ($pid, $uid, $exe) = peer $app;
   $pid == $app->{pid} && $uid == $app->{uid}
      && (!defined $app->{exe} || defined $exe && $exe eq $app->{exe})
      or die "Application identity changed; list applications again\n";

   my $s = live $o;
   if ($window) {
      my $cur = $o;
      my %seen;
      for (1 .. 128) {
         my $parent = get_property $cur, $access, "Parent";
         my ($name, $path) = @$parent;
         ($name eq $app->{name} || !length $name) && !$seen{$path}++
            or die "Accessible object ancestry changed; inspect tree again\n";

         if ($path eq $app->{path}) {
            $cur->{path} eq $window->{path}
               or die "Accessible object moved to a different window; inspect tree again\n";
            return ($o, $app, $window, $s);
         }

         $cur = { %$cur, path => $path };
      }
      die "Accessible object ancestry too deep\n";
   }

   ($o, $app, undef, $s)
}

sub prune_rules {
   # Only generated, exact instance/window prefixes; leave hand-written rules
   # and rules belonging to other desktops alone.
   my $lock = $permissions->_lock;
   my $rules = $permissions->rules;
   my @keep = grep {
      my $match = $_->{"match.target"};
      if ($match =~ m{\A\^\Q$desktop\EP(?:[0-9a-f]+|unknown)/I([0-9a-f]+-\d+:\d+)/(?:W([0-9a-f]+-\d+:\d+)/)?\z}) {
         my ($app, $window) = ($1, $2);
         exists $objects{$app} && (!defined $window || exists $objects{$window})
      } else {
         1
      }
   } @$rules;
   $permissions->_write (\@keep) if @keep != @$rules;
}

sub applications {
   my ($req) = @_;

   permission $req, "read", undef, undef, "List desktop applications";
   local $deadline = time + 10;
   my ($buses, $errors, $addresses) = discover;
   my @apps;

   for my $b (@$buses) {
      my $refs = eval { call $b->{conn}, $registry, $root, $access, "GetChildren" };
      unless ($refs) {
         push @$errors, "Bus $b->{id}: " . short_error ($@);
         next;
      }

      my %seen;
      my $complete = 1;
      for my $ref (@$refs) {
         next if $ref->[1] eq $null;
         eval {
            my $app = intern $b, $ref, undef, undef or die "Invalid application reference\n";
            $seen{$app->{id}} = 1;
            my ($pid, $uid, $exe) = peer $app;
            my $p = properties $app, $access, qw(Name ChildCount);
            @$app{qw(pid uid exe label)} = ($pid, $uid, $exe, $p->{Name});
            my ($children, $all) = children $app, $p, 256;
            my (@windows, %windows);
            for my $ref (@$children) {
               eval {
                  my $w = intern $b, $ref, $app, undef or die "Invalid window reference\n";
                  $windows{$w->{id}} = 1;
                  $w->{label} = get_property $w, $access, "Name";
                  push @windows, { id => $w->{id}, name => $w->{label}, role => (scalar object_call $w, $access, "GetRoleName") };
               };
               if ($@) {
                  push @$errors, "Window @$ref: " . short_error ($@);
                  $all = 0;
               }
            }
            if ($all) {
               for my $o (values %objects) {
                  next unless $o->{app} eq $app->{id} && length $o->{window} && !$windows{$o->{window}};
                  retire $o;
               }
            }
            push @apps, {
               id => $app->{id}, name => $app->{label}, pid => $pid, uid => $uid,
               (defined $exe ? (program => AnyEvent::MCP::utf8dec ($exe)) : ()),
               windows => \@windows, (!$all ? (incomplete => Types::Serialiser::true) : ()),
            };
         };
         if ($@) {
            push @$errors, "Application @$ref: " . short_error ($@);
            $complete = 0;
         }
         last if time >= $deadline && !($complete = 0);
      }

      if ($complete) {
         for my $o (values %objects) {
            next unless $o->{bus} == $b && !$seen{$o->{app}};
            retire $o;
         }
      }
   }

   prune_rules;
   $req->result ({
      applications => \@apps,
      (@$errors || keys %$addresses > 1 ? (diagnostics => {
         addresses => [sort keys %$addresses], errors => $errors,
      }) : ()),
   });
}

sub interfaces {
   my ($o) = @_;

   +{ map { my $i = $_; $i =~ s/^org[.]a11y[.]atspi[.]//; ($i => 1) } @{object_call $o, $access, "GetInterfaces"} }
}

sub actions {
   my ($o) = @_;

   my $interface = "org.a11y.atspi.Action";
   my $actions = eval { object_call $o, $interface, "GetActions" };
   return $actions if ref $actions eq "ARRAY";

   my $n = get_property $o, $interface, "NActions";
   $n >= 0 && $n <= 256 or die "Invalid action count\n";
   [map {
      my $i = dbus_int32 $_;
      [map { scalar object_call $o, $interface, $_, $i } qw(GetName GetDescription GetKeyBinding)]
   } 0 .. $n - 1]
}

sub tree {
   my ($req, $args, $o, $app, $window) = @_;

   my $max_depth = $args->{depth} // 5;
   my $limit = $args->{limit} // 120;
   my @todo = ([$o, 0]);
   my (@lines, @errors, %seen, $visited, $truncated);

   while (@todo && $visited < $limit && time < $deadline) {
      my ($node, $depth) = @{pop @todo};
      next if $seen{$node->{id}}++;
      ++$visited;

      eval {
         my $p = properties $node, $access, qw(Name ChildCount);
         $node->{label} = $p->{Name};
         my $role = object_call $node, $access, "GetRoleName";
         my $s = live $node;
         my %state = map { $_ => 1 } @$s;
         if ((!defined $args->{role} || index (lc $role, lc $args->{role}) >= 0)
             && (!defined $args->{name} || index (lc $p->{Name}, lc $args->{name}) >= 0)
             && !(grep !$state{$_}, @{$args->{state} || []})) {
            my @flags = grep $state{$_}, qw(active checked collapsed expanded focused selected editable indeterminate required read_only);
            push @flags, "disabled" unless $state{enabled} || $role eq "application";
            push @lines, ("  " x $depth) . "$node->{id} $role " . label ($p->{Name})
               . (@flags ? " [" . join (" ", @flags) . "]" : "")
               . ($p->{ChildCount} ? " ($p->{ChildCount} children)" : "");
         }

         if ($depth < $max_depth && $p->{ChildCount} != 0) {
            my ($refs, $all) = children $node, $p, $limit - $visited;
            $truncated ||= !$all;
            my $w = $objects{$node->{window}};
            for my $ref (reverse @$refs) {
               my $child = intern $node->{bus}, $ref, $app, $w;
               if ($child) {
                  push @todo, [$child, $depth + 1];
               } else {
                  $truncated = 1;
               }
            }
         } elsif ($p->{ChildCount}) {
            $truncated = 1;
         }
      };
      if ($@) {
         push @errors, "$node->{id}: " . short_error ($@) if @errors < 10;
         $truncated = 1;
      }
   }

   $req->result ({
      tree => join ("\n", @lines), visited => 0 + $visited,
      truncated => $truncated || @todo ? Types::Serialiser::true : Types::Serialiser::false,
      (@errors ? (errors => \@errors) : ()),
   });
}

sub inspect {
   my ($req, $o, $s) = @_;

   my $p = properties $o, $access, qw(Name Description ChildCount);
   my $i = interfaces $o;
   my $result = {
      id => $o->{id}, name => $p->{Name}, description => $p->{Description},
      role => (scalar object_call $o, $access, "GetRoleName"), state => $s,
      children => $p->{ChildCount}, interfaces => [sort keys %$i],
   };

   # A partially implemented optional interface must not hide the rest.
   my @errors;
   for my $field (
      [attributes => sub { object_call $o, $access, "GetAttributes" }],
      [actions => sub { actions $o }, "Action"],
      [geometry => sub { object_call $o, "org.a11y.atspi.Component", "GetExtents", dbus_uint32 (0) }, "Component"],
      [text => sub { properties $o, "org.a11y.atspi.Text", qw(CharacterCount CaretOffset) }, "Text"],
      [value => sub { properties $o, "org.a11y.atspi.Value", qw(CurrentValue MinimumValue MaximumValue MinimumIncrement) }, "Value"],
      [relations => sub {
         [map {
            my ($type, $refs) = @$_;
            [$type, [grep defined, map {
               my $id = $o->{bus}{refs}{join "\0", @$_};
               my $related = $objects{$id};
               $related && $related->{app} eq $o->{app}
                  && (!$o->{window} || $related->{window} eq $o->{window}) ? $id : undef
            } @$refs]]
         } @{object_call $o, $access, "GetRelationSet"}]
      }],
   ) {
      next if $field->[2] && !$i->{$field->[2]};
      my $v = eval { scalar $field->[1]->() };
      $@ ? push (@errors, "$field->[0]: " . short_error ($@)) : ($result->{$field->[0]} = $v);
   }
   $result->{errors} = \@errors if @errors;
   $req->result ($result);
}

sub screen_guard {
   my ($input) = @_;

   my $bus = eval { session_bus };
   if ($bus) {
      for my $name (qw(org.freedesktop.ScreenSaver org.gnome.ScreenSaver org.xfce.ScreenSaver)) {
         next unless eval { bus_call $bus, "NameHasOwner", $name };
         my $path = $name eq "org.freedesktop.ScreenSaver" ? "/ScreenSaver" : "/" . join "/", split /[.]/, $name;
         my $active = eval { call $bus, $name, $path, $name, "GetActive" };
         $active and die "Desktop screen saver/lock is active\n";
      }
   }
   return unless $input;
   my $x = x11;
   my (undef, undef, @windows) = $x->QueryTree ($x->root);
   my @todo = map [$_, 0], @windows;
   my $count;

   while (@todo) {
      ++$count <= 8192 or die "Cannot verify desktop lock/dialog state\n";
      my ($w, $depth) = @{pop @todo};
      my %a = eval { $x->GetWindowAttributes ($w) };
      next unless $a{map_state} eq "Viewable";
      my $class = eval { xproperty $x, $w, "WM_CLASS" };
      my $title = eval { xproperty $x, $w, "_NET_WM_NAME" };
      $title ||= eval { xproperty $x, $w, "WM_NAME" };
      if ($class =~ /(?:i3lock|xsecurelock|slock|xlock|xscreensaver|light-locker|kscreenlocker|xfce4-screensaver|gnome-screensaver)/i) {
         die "Desktop lock window is visible\n";
      }
      if ($title =~ /(?:MCP (?:critical )?permission|MCP question|MCP elicitation|MCP form)/i
          || $class =~ /anyevent-mcp/i) {
         die "MCP permission or question dialog is visible\n";
      }
      if ($depth < 3) {
         my (undef, undef, @children) = eval { $x->QueryTree ($w) };
         push @todo, map [$_, $depth + 1], @children;
      }
   }
}

sub write_guard {
   my ($app) = @_;

   screen_guard 1;
   if ($app) {
      my $exe = $app->{exe};
      $exe =~ m{/(?:anyevent-mcp-askpermission|anyevent-mcp-form-elicitation)\z}
         and die "Permission helper applications cannot be controlled\n";
      if (open my $fh, "<:raw", "/proc/$app->{pid}/cmdline") {
         local $/;
         my $cmdline = <$fh>;
         $cmdline =~ /(?:^|[\0\/])anyevent-mcp-(?:askpermission|form-elicitation)(?:\0|$)/
            and die "Permission helper applications cannot be controlled\n";
      }
   }
}

sub checked {
   my ($req, $success) = @_;

   $success or die "Application refused the requested operation\n";
   $req->result ({ success => Types::Serialiser::true });
}

sub validate;

sub validate {
   my ($schema, $v, $key) = @_;

   my $type = $schema->{type};
   if ($type eq "array") {
      ref $v eq "ARRAY" && @$v >= ($schema->{minItems} // 0) && @$v <= $schema->{maxItems}
         or die "Invalid $key array\n";
      validate $schema->{items}, $_, $key for @$v;
   } elsif ($type eq "boolean") {
      Types::Serialiser::is_bool ($v) or die "Invalid $key boolean\n";
   } else {
      defined $v && !ref $v or die "Invalid $key\n";
      if ($type eq "integer" || $type eq "number") {
         looks_like_number ($v) && POSIX::isfinite (0 + $v)
            && ($type ne "integer" || $v == int $v)
            && (!defined $schema->{minimum} || $v >= $schema->{minimum})
            && (!defined $schema->{maximum} || $v <= $schema->{maximum})
            or die "Invalid $key number\n";
      } else {
         $v !~ /\0/ && (!defined $schema->{maxLength} || length $v <= $schema->{maxLength})
            or die "Invalid $key string\n";
      }
      !$schema->{enum} || (grep $_ eq $v, @{$schema->{enum}}) or die "Invalid $key choice\n";
   }
}

sub expose {
   my ($name, $description, $action, $required, $properties, $cb) = @_;

   mcp_tool $name => $description,
      {
         type => "object", required => $required, additionalProperties => Types::Serialiser::false,
         properties => $properties,
      },
      readonly => 0 + ($action eq "read"), closedworld => 1,
      sub {
         my ($req, $args) = @_;

         ref $args eq "HASH" or die "Expected arguments object\n";
         exists $args->{$_} or die "Missing $_\n" for @$required;
         for my $key (keys %$args) {
            my $schema = $properties->{$key} or die "Unknown argument $key\n";
            validate $schema, $args->{$key}, $key;
         }

         local $deadline = time + 10;
         $cb->($req, $args);
      };
}

my $object = { type => "string", description => "Opaque object ID from applications/tree" };
my $offset = { type => "integer", minimum => 0, maximum => 2147483647 };
my $text = { type => "string", maxLength => 65536 };

sub object_tool {
   my ($name, $description, $action, $required, $properties, $cb) = @_;

   expose $name, $description, $action, ["object", @$required], { object => $object, %$properties }, sub {
      my ($req, $args) = @_;

      my ($o, $app, $window, $s) = resolve $args->{object};
      my %details = %$args;
      delete $details{object};
      permission $req, $action, $app, $window,
         "$name " . label ($o->{label}) . " ($o->{id}) in " . label ($app->{label})
         . (keys %details ? "\n" . substr ($json->canonical->encode (\%details), 0, 500) : "");
      write_guard $app if $action eq "write";
      $cb->($req, $args, $o, $app, $window, $s);
   };
}

expose applications => "List all accessible applications and top-level objects, across discovered buses. Includes discovery errors.",
   "read", [], {}, \&applications;

object_tool tree => "Bounded textual subtree. Filter literal role/name and required states; limit counts visited objects.",
   "read", [], {
      depth => { type => "integer", minimum => 0, maximum => 20, default => 5 },
      limit => { type => "integer", minimum => 1, maximum => 1000, default => 120 },
      role => { type => "string" }, name => { type => "string" },
      state => { type => "array", items => { type => "string", enum => \@states }, maxItems => 20 },
   }, \&tree;

object_tool inspect => "Inspect role, state, properties, interfaces, advertised actions, geometry, value and known relations.",
   "read", [], {}, sub { inspect $_[0], $_[2], $_[5] };

object_tool "read-text" => "Read a bounded character range from Text. End exclusive; omitted end reads up to max_chars.",
   "read", [], {
      start => $offset, end => $offset, max_chars => { type => "integer", minimum => 1, maximum => 65536, default => 4096 },
   }, sub {
      my ($req, $args, $o) = @_;

      my $n = get_property $o, "org.a11y.atspi.Text", "CharacterCount";
      my $start = $args->{start} // 0;
      my $end = $args->{end} // $n;
      $start <= $n && $end >= $start or die "Invalid character range\n";
      $end = $n if $end > $n;
      my $limit = $args->{max_chars} // 4096;
      my $truncated = $end - $start > $limit;
      $end = $start + $limit if $truncated;
      $req->result ({
         text => (scalar object_call $o, "org.a11y.atspi.Text", "GetText", dbus_int32 ($start), dbus_int32 ($end)),
         start => $start, end => $end, characters => $n,
         truncated => $truncated ? Types::Serialiser::true : Types::Serialiser::false,
      });
   };

object_tool invoke => "Invoke an advertised action by exact name; omit action for the default (first) action.",
   "write", [], { action => { type => "string" } }, sub {
      my ($req, $args, $o) = @_;

      my $a = actions $o;
      my ($index) = grep !defined $args->{action} || $a->[$_][0] eq $args->{action}, 0 .. $#$a;
      defined $index or die "No such advertised action\n";
      checked $req, scalar object_call $o, "org.a11y.atspi.Action", "DoAction", dbus_int32 ($index);
   };

object_tool "edit-text" => "Set, insert or delete EditableText. Offsets count characters; end exclusive.",
   "write", ["operation"], {
      operation => { type => "string", enum => [qw(set insert delete)] },
      text => $text, start => $offset, end => $offset,
   }, sub {
      my ($req, $args, $o) = @_;

      my $op = $args->{operation};
      my $interface = "org.a11y.atspi.EditableText";
      if ($op eq "delete") {
         defined $args->{start} && defined $args->{end} && $args->{start} <= $args->{end} or die "Expected start/end\n";
         checked $req, scalar object_call $o, $interface, "DeleteText", dbus_int32 ($args->{start}), dbus_int32 ($args->{end});
      } else {
         defined $args->{text} && $args->{text} !~ /\0/ or die "Expected text without NUL\n";
         if ($op eq "set") {
            checked $req, scalar object_call $o, $interface, "SetTextContents",
               dbus_string (AnyEvent::MCP::utf8enc ($args->{text}));
         } else {
            defined $args->{start} or die "Expected start\n";
            checked $req, scalar object_call $o, $interface, "InsertText", dbus_int32 ($args->{start}),
               dbus_string (AnyEvent::MCP::utf8enc ($args->{text})), dbus_int32 (length AnyEvent::MCP::utf8enc ($args->{text}));
         }
      }
   };

object_tool "set-value" => "Set the numeric CurrentValue property of a Value object.",
   "write", ["value"], { value => { type => "number" } }, sub {
      my ($req, $args, $o) = @_;
      object_call $o, $prop, "Set", "org.a11y.atspi.Value", "CurrentValue", dbus_variant (dbus_double ($args->{value}));
      checked $req, 1;
   };

object_tool select => "Select/deselect children by child index; clear/all; add/set/remove a text selection.",
   "write", ["operation"], {
      operation => { type => "string", enum => [qw(child deselect clear all text-add text-set text-remove)] },
      index => $offset, start => $offset, end => $offset,
   }, sub {
      my ($req, $args, $o) = @_;

      my $op = $args->{operation};
      my %method = (
         child => "SelectChild", deselect => "DeselectChild", clear => "ClearSelection", all => "SelectAll",
         "text-add" => "AddSelection", "text-set" => "SetSelection", "text-remove" => "RemoveSelection",
      );
      my @a;
      if ($op =~ /\A(?:child|deselect|text-set|text-remove)\z/) {
         defined $args->{index} or die "Expected index\n";
         push @a, dbus_int32 ($args->{index});
      }
      if ($op =~ /\Atext-(?:add|set)\z/) {
         defined $args->{start} && defined $args->{end} && $args->{start} <= $args->{end} or die "Expected start/end\n";
         push @a, dbus_int32 ($args->{start}), dbus_int32 ($args->{end});
      }
      checked $req, scalar object_call $o, ($op =~ /^text-/ ? "org.a11y.atspi.Text" : "org.a11y.atspi.Selection"), $method{$op}, @a;
   };

object_tool focus => "Request keyboard focus via Component.GrabFocus.",
   "write", [], {}, sub { checked $_[0], scalar object_call $_[2], "org.a11y.atspi.Component", "GrabFocus" };

sub xdotool {
   open my $fh, "-|", "xdotool", @_ or die "Cannot start xdotool: $!\n";
   1 while <$fh>; # stdout belongs to the MCP protocol
   close $fh or die "xdotool failed (status $?)\n";
}

our %keysyms;

expose keyboard => "Last resort: prefer invoke, edit-text, set-value or select. Global X11 input (xdotool syntax, e.g. ctrl+l, or literal text). No target object; verify window and widget focus. Focus can change during input.",
   "write", [], {
      keys => { type => "array", minItems => 1, maxItems => 64, items => { type => "string", pattern => '^[A-Za-z0-9_]+(?:[+][A-Za-z0-9_]+)*$' } },
      text => { type => "string", maxLength => 4096 },
   }, sub {
      my ($req, $args) = @_;

      defined $args->{keys} != defined $args->{text} or die "Specify keys or text\n";
      my @keys;
      if ($args->{keys}) {
         unless (%keysyms) {
            require X11::Keysyms;
            X11::Keysyms->import ("%keysyms");
         }
         for my $key (@{$args->{keys}}) {
            $key =~ /\A[A-Za-z0-9_]+(?:[+][A-Za-z0-9_]+)*\z/ && length $key <= 128 or die "Invalid key combination\n";
            my @parts = split /[+]/, $key;
            for (@parts) {
               $_ = lc $_ if /\A(?:ctrl|alt|shift|super|meta|hyper)\z/i;
               exists $keysyms{$_} || /\A(?:ctrl|alt|shift|super|meta|hyper|XF86[A-Za-z0-9_]+)\z/
                  or die "Unknown key symbol $_\n";
            }
            push @keys, join "+", @parts;
         }
      } else {
         $args->{text} !~ /\0/ or die "NUL in text\n";
      }
      permission $req, "write", undef, undef, "Send keyboard input to the current desktop focus\n"
         . (@keys ? join (" ", @keys) : label ($args->{text}));
      write_guard undef;

      if ($args->{keys}) {
         # One key combination per invocation, never an arbitrary command chain.
         for my $key (@keys) {
            time < $deadline or die "Keyboard operation timed out\n";
            screen_guard 1;
            xdotool "key", "--clearmodifiers", $key;
         }
      } else {
         xdotool "type", "--clearmodifiers", "--delay", "0", "--", AnyEvent::MCP::utf8enc ($args->{text});
      }
      checked $req, 1;
   };

expose mouse => "Move pointer to screen x/y, optionally click button 1-5. Desktop-wide X11 input.",
   "write", [qw(x y)], {
      x => $offset, y => $offset, button => { type => "integer", minimum => 1, maximum => 5 },
   }, sub {
      my ($req, $args) = @_;

      permission $req, "write", undef, undef, "Move/click pointer at $args->{x},$args->{y}";
      write_guard undef;
      xdotool "mousemove", int $args->{x}, int $args->{y};
      xdotool "click", int $args->{button} if defined $args->{button};
      checked $req, 1;
   };

expose accessibility => "Get session accessibility flags; enabled explicitly sets IsEnabled (write permission).",
   "write", [], { enabled => { type => "boolean" } }, sub {
      my ($req, $args) = @_;

      if (exists $args->{enabled}) {
         permission $req, "write", undef, undef, ($args->{enabled} ? "Enable" : "Disable") . " session accessibility";
         screen_guard 0;
         status_call "Set", $status, "IsEnabled", dbus_variant (dbus_boolean (0 + !!$args->{enabled}));
      } else {
         permission $req, "read", undef, undef, "Read session accessibility status";
      }
      my $s = status_call "GetAll", $status;
      $req->result ({ enabled => $s->{IsEnabled} ? Types::Serialiser::true : Types::Serialiser::false,
                     screen_reader_enabled => $s->{ScreenReaderEnabled} ? Types::Serialiser::true : Types::Serialiser::false });
   };

mcp_start %$options;
