#!/usr/bin/env perl
# thunar-fm-proxy - add o.f.FileManager1 support on top of Thunar's own API
# (c) 2017 Mantas Mikulėnas <grawity@gmail.com>
# Released under the MIT License <https://spdx.org/licenses/MIT>
#
# 2019-01-28: Thunar.git now has native support for the fdo interface, so this
#             script is mostly obsolete and for demonstration purposes only.

use warnings;
use strict;

package FakeFileManager;
	use base "Net::DBus::Object";
	use File::Basename;
	use Net::DBus::Exporter "org.freedesktop.FileManager1";

	dbus_method("ShowFolders", [["array", "string"], "string"], []);
	dbus_method("ShowItems", [["array", "string"], "string"], []);
	dbus_method("ShowItemProperties", [["array", "string"], "string"], []);

	sub get_Thunar {
		(shift)
		->get_service("org.xfce.FileManager")
		->get_object("/org/xfce/FileManager")
	}

	sub ShowFolders {
		my ($self, $uris, $startup_id) = @_;

		my $Thunar = get_Thunar($self->get_service->get_bus);
		my $display = "";

		for my $uri (@$uris) {
			$Thunar->DisplayFolder($uri, $display, $startup_id);
		}
		return;
	}

	sub ShowItems {
		my ($self, $uris, $startup_id) = @_;

		my $Thunar = get_Thunar($self->get_service->get_bus);
		my $display = "";

		for my $uri (@$uris) {
			my $dir_uri = dirname($uri);
			my $basename = basename($uri);
			$Thunar->DisplayFolderAndSelect($dir_uri, $basename,
							$display, $startup_id);
		}
		return;
	}

	sub ShowItemProperties {
		my ($self, $uris, $startup_id) = @_;

		my $Thunar = get_Thunar($self->get_service->get_bus);
		my $display = "";

		for my $uri (@$uris) {
			$Thunar->DisplayFileProperties($uri, $display, $startup_id);
		}
		return;
	}

package main;
	use Net::DBus;
	use Net::DBus::Reactor;

	my $bus = Net::DBus->session;
	my $svc = $bus->export_service("org.freedesktop.FileManager1");
	my $obj = FakeFileManager->new($svc, "/org/freedesktop/FileManager1");
	Net::DBus::Reactor->main->run;
