-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilepick.go
95 lines (78 loc) · 2.07 KB
/
filepick.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"log"
"github.com/godbus/dbus/v5"
)
const (
busName = "org.freedesktop.portal.Desktop"
objectPath = "/org/freedesktop/portal/desktop"
methodName = "org.freedesktop.portal.FileChooser.OpenFile"
requestIFace = "org.freedesktop.portal.Request"
responseSignal = "Response"
handleToken = "revelation"
dialogTitle = "Choose file"
)
func SelectFile() string {
conn := connectDBus()
defer conn.Close()
responsePath := openFileDialog(conn)
setupSignalHandler(conn, responsePath)
return processSignal(<-waitForSignal(conn), responsePath)
}
func connectDBus() *dbus.Conn {
conn, err := dbus.ConnectSessionBus()
if err != nil {
log.Fatalf("Failed to connect to session bus: %v", err)
}
return conn
}
func openFileDialog(conn *dbus.Conn) dbus.ObjectPath {
options := map[string]dbus.Variant{
"handle_token": dbus.MakeVariant(handleToken),
"title": dbus.MakeVariant(dialogTitle),
}
call := conn.Object(busName, objectPath).Call(methodName, 0, "", "", options)
if call.Err != nil {
log.Fatalf("Failed to trigger file picker: %v", call.Err)
}
return call.Body[0].(dbus.ObjectPath)
}
func setupSignalHandler(conn *dbus.Conn, path dbus.ObjectPath) {
err := conn.AddMatchSignal(
dbus.WithMatchInterface(requestIFace),
dbus.WithMatchMember(responseSignal),
dbus.WithMatchPathNamespace(path),
)
if err != nil {
log.Fatalf("Failed to add signal match: %v", err)
}
}
func waitForSignal(conn *dbus.Conn) <-chan *dbus.Signal {
ch := make(chan *dbus.Signal, 1)
conn.Signal(ch)
return ch
}
func processSignal(signal *dbus.Signal, expectedPath dbus.ObjectPath) string {
if signal.Path != expectedPath || signal.Name != requestIFace+"."+responseSignal {
return ""
}
if len(signal.Body) < 2 {
// nothing selected
return ""
}
results, ok := signal.Body[1].(map[string]dbus.Variant)
if !ok {
// invalid response
return ""
}
urisVariant, exists := results["uris"]
if !exists {
// nothing selected
return ""
}
uris, ok := urisVariant.Value().([]string)
if ok && len(uris) > 0 {
return uris[0]
}
return ""
}