From 5d6ab3eb5a7c3e2cb5004fc231d2190feeebe1bb Mon Sep 17 00:00:00 2001 From: jabuxas Date: Thu, 27 Feb 2025 10:52:51 -0300 Subject: [PATCH] feat: filepick file and return file --- filepick.go | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++ go.mod | 2 ++ go.sum | 2 ++ revelation.go | 2 +- 4 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 filepick.go create mode 100644 go.sum diff --git a/filepick.go b/filepick.go new file mode 100644 index 0000000..15a6241 --- /dev/null +++ b/filepick.go @@ -0,0 +1,65 @@ +package main + +import ( + "fmt" + "log" + "os" + + "github.com/godbus/dbus/v5" +) + +func SelectFile() string { + conn, err := dbus.ConnectSessionBus() + if err != nil { + fmt.Fprintln(os.Stderr, "Failed to connect to session bus:", err) + os.Exit(1) + } + defer conn.Close() + + token := "revelation" + options := map[string]dbus.Variant{ + "handle_token": dbus.MakeVariant(token), + "title": dbus.MakeVariant("Choose file"), + } + + obj := conn.Object("org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop") + call := obj.Call("org.freedesktop.portal.FileChooser.OpenFile", 0, "revelation", "", options) + if call.Err != nil { + log.Fatalf("Failed to trigger file picker: %v", call.Err) + } + + replyPath := call.Body[0].(dbus.ObjectPath) + + err = conn.AddMatchSignal( + dbus.WithMatchOption("interface", "org.freedesktop.portal.Request"), + dbus.WithMatchOption("member", "Response"), + dbus.WithMatchOption("path", string(replyPath)), + ) + if err != nil { + log.Fatalf("Failed to add match signal: %v", err) + } + + c := make(chan *dbus.Signal, 1) + conn.Signal(c) + + for signal := range c { + if signal.Path == replyPath && signal.Name == "org.freedesktop.portal.Request.Response" { + reply := signal.Body + if len(reply) > 1 { + results, ok := reply[1].(map[string]dbus.Variant) + if ok { + if urisVariant, exists := results["uris"]; exists { + uris, ok := urisVariant.Value().([]string) + if ok && len(uris) > 0 { + return uris[0] + } else { + return "" + } + } + } + } + break + } + } + return "" +} diff --git a/go.mod b/go.mod index a0db732..3b91c69 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module github.com/jabuxas/revelation go 1.23.4 + +require github.com/godbus/dbus/v5 v5.1.0 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..024b269 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= diff --git a/revelation.go b/revelation.go index 24dcac8..0204227 100644 --- a/revelation.go +++ b/revelation.go @@ -5,5 +5,5 @@ import ( ) func main() { - fmt.Println("Hello world") + fmt.Println(SelectFile()) }