feat: filepick file and return file

This commit is contained in:
jabuxas 2025-02-27 10:52:51 -03:00
parent 5a0e5e2ea3
commit 5d6ab3eb5a
4 changed files with 70 additions and 1 deletions

65
filepick.go Normal file
View File

@ -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 ""
}

2
go.mod
View File

@ -1,3 +1,5 @@
module github.com/jabuxas/revelation module github.com/jabuxas/revelation
go 1.23.4 go 1.23.4
require github.com/godbus/dbus/v5 v5.1.0 // indirect

2
go.sum Normal file
View File

@ -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=

View File

@ -5,5 +5,5 @@ import (
) )
func main() { func main() {
fmt.Println("Hello world") fmt.Println(SelectFile())
} }