prop.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. // Package prop provides the Properties struct which can be used to implement
  2. // org.freedesktop.DBus.Properties.
  3. package prop
  4. import (
  5. "reflect"
  6. "sync"
  7. "github.com/godbus/dbus/v5"
  8. "github.com/godbus/dbus/v5/introspect"
  9. )
  10. // EmitType controls how org.freedesktop.DBus.Properties.PropertiesChanged is
  11. // emitted for a property. If it is EmitTrue, the signal is emitted. If it is
  12. // EmitInvalidates, the signal is also emitted, but the new value of the property
  13. // is not disclosed. If it is EmitConst, the property never changes value during
  14. // the lifetime of the object it belongs to, and hence the signal is never emitted
  15. // for it.
  16. type EmitType byte
  17. const (
  18. EmitFalse EmitType = iota
  19. EmitTrue
  20. EmitInvalidates
  21. EmitConst
  22. )
  23. func (e EmitType) String() (str string) {
  24. switch e {
  25. case EmitFalse:
  26. str = "false"
  27. case EmitTrue:
  28. str = "true"
  29. case EmitInvalidates:
  30. str = "invalidates"
  31. case EmitConst:
  32. str = "const"
  33. default:
  34. panic("invalid value for EmitType")
  35. }
  36. return
  37. }
  38. // ErrIfaceNotFound is the error returned to peers who try to access properties
  39. // on interfaces that aren't found.
  40. var ErrIfaceNotFound = dbus.NewError("org.freedesktop.DBus.Properties.Error.InterfaceNotFound", nil)
  41. // ErrPropNotFound is the error returned to peers trying to access properties
  42. // that aren't found.
  43. var ErrPropNotFound = dbus.NewError("org.freedesktop.DBus.Properties.Error.PropertyNotFound", nil)
  44. // ErrReadOnly is the error returned to peers trying to set a read-only
  45. // property.
  46. var ErrReadOnly = dbus.NewError("org.freedesktop.DBus.Properties.Error.ReadOnly", nil)
  47. // ErrInvalidArg is returned to peers if the type of the property that is being
  48. // changed and the argument don't match.
  49. var ErrInvalidArg = dbus.NewError("org.freedesktop.DBus.Properties.Error.InvalidArg", nil)
  50. // The introspection data for the org.freedesktop.DBus.Properties interface.
  51. var IntrospectData = introspect.Interface{
  52. Name: "org.freedesktop.DBus.Properties",
  53. Methods: []introspect.Method{
  54. {
  55. Name: "Get",
  56. Args: []introspect.Arg{
  57. {Name: "interface", Type: "s", Direction: "in"},
  58. {Name: "property", Type: "s", Direction: "in"},
  59. {Name: "value", Type: "v", Direction: "out"},
  60. },
  61. },
  62. {
  63. Name: "GetAll",
  64. Args: []introspect.Arg{
  65. {Name: "interface", Type: "s", Direction: "in"},
  66. {Name: "props", Type: "a{sv}", Direction: "out"},
  67. },
  68. },
  69. {
  70. Name: "Set",
  71. Args: []introspect.Arg{
  72. {Name: "interface", Type: "s", Direction: "in"},
  73. {Name: "property", Type: "s", Direction: "in"},
  74. {Name: "value", Type: "v", Direction: "in"},
  75. },
  76. },
  77. },
  78. Signals: []introspect.Signal{
  79. {
  80. Name: "PropertiesChanged",
  81. Args: []introspect.Arg{
  82. {Name: "interface", Type: "s", Direction: "out"},
  83. {Name: "changed_properties", Type: "a{sv}", Direction: "out"},
  84. {Name: "invalidates_properties", Type: "as", Direction: "out"},
  85. },
  86. },
  87. },
  88. }
  89. // The introspection data for the org.freedesktop.DBus.Properties interface, as
  90. // a string.
  91. const IntrospectDataString = `
  92. <interface name="org.freedesktop.DBus.Properties">
  93. <method name="Get">
  94. <arg name="interface" direction="in" type="s"/>
  95. <arg name="property" direction="in" type="s"/>
  96. <arg name="value" direction="out" type="v"/>
  97. </method>
  98. <method name="GetAll">
  99. <arg name="interface" direction="in" type="s"/>
  100. <arg name="props" direction="out" type="a{sv}"/>
  101. </method>
  102. <method name="Set">
  103. <arg name="interface" direction="in" type="s"/>
  104. <arg name="property" direction="in" type="s"/>
  105. <arg name="value" direction="in" type="v"/>
  106. </method>
  107. <signal name="PropertiesChanged">
  108. <arg name="interface" type="s"/>
  109. <arg name="changed_properties" type="a{sv}"/>
  110. <arg name="invalidates_properties" type="as"/>
  111. </signal>
  112. </interface>
  113. `
  114. // Prop represents a single property. It is used for creating a Properties
  115. // value.
  116. type Prop struct {
  117. // Initial value. Must be a DBus-representable type. This is not modified
  118. // after Properties has been initialized; use Get or GetMust to access the
  119. // value.
  120. Value interface{}
  121. // If true, the value can be modified by calls to Set.
  122. Writable bool
  123. // Controls how org.freedesktop.DBus.Properties.PropertiesChanged is
  124. // emitted if this property changes.
  125. Emit EmitType
  126. // If not nil, anytime this property is changed by Set, this function is
  127. // called with an appropriate Change as its argument. If the returned error
  128. // is not nil, it is sent back to the caller of Set and the property is not
  129. // changed.
  130. Callback func(*Change) *dbus.Error
  131. }
  132. // Introspection returns the introspection data for p.
  133. // The "name" argument is used as the property's name in the resulting data.
  134. func (p *Prop) Introspection(name string) introspect.Property {
  135. var result = introspect.Property{Name: name, Type: dbus.SignatureOf(p.Value).String()}
  136. if p.Writable {
  137. result.Access = "readwrite"
  138. } else {
  139. result.Access = "read"
  140. }
  141. result.Annotations = []introspect.Annotation{
  142. {
  143. Name: "org.freedesktop.DBus.Property.EmitsChangedSignal",
  144. Value: p.Emit.String(),
  145. },
  146. }
  147. return result
  148. }
  149. // Change represents a change of a property by a call to Set.
  150. type Change struct {
  151. Props *Properties
  152. Iface string
  153. Name string
  154. Value interface{}
  155. }
  156. // Properties is a set of values that can be made available to the message bus
  157. // using the org.freedesktop.DBus.Properties interface. It is safe for
  158. // concurrent use by multiple goroutines.
  159. type Properties struct {
  160. m Map
  161. mut sync.RWMutex
  162. conn *dbus.Conn
  163. path dbus.ObjectPath
  164. }
  165. // New falls back to Export, but it returns nil if properties export fails,
  166. // swallowing the error, shouldn't be used.
  167. //
  168. // Deprecated: use Export instead.
  169. func New(conn *dbus.Conn, path dbus.ObjectPath, props Map) *Properties {
  170. p, err := Export(conn, path, props)
  171. if err != nil {
  172. return nil
  173. }
  174. return p
  175. }
  176. // Export returns a new Properties structure that manages the given properties.
  177. // The key for the first-level map of props is the name of the interface; the
  178. // second-level key is the name of the property. The returned structure will be
  179. // exported as org.freedesktop.DBus.Properties on path.
  180. func Export(
  181. conn *dbus.Conn, path dbus.ObjectPath, props Map,
  182. ) (*Properties, error) {
  183. p := &Properties{m: copyProps(props), conn: conn, path: path}
  184. if err := conn.Export(p, path, "org.freedesktop.DBus.Properties"); err != nil {
  185. return nil, err
  186. }
  187. return p, nil
  188. }
  189. // Map is a helper type for supplying the configuration of properties to be handled.
  190. type Map = map[string]map[string]*Prop
  191. func copyProps(in Map) Map {
  192. out := make(Map, len(in))
  193. for intf, props := range in {
  194. out[intf] = make(map[string]*Prop)
  195. for name, prop := range props {
  196. out[intf][name] = new(Prop)
  197. *out[intf][name] = *prop
  198. val := reflect.New(reflect.TypeOf(prop.Value))
  199. val.Elem().Set(reflect.ValueOf(prop.Value))
  200. out[intf][name].Value = val.Interface()
  201. }
  202. }
  203. return out
  204. }
  205. // Get implements org.freedesktop.DBus.Properties.Get.
  206. func (p *Properties) Get(iface, property string) (dbus.Variant, *dbus.Error) {
  207. p.mut.RLock()
  208. defer p.mut.RUnlock()
  209. m, ok := p.m[iface]
  210. if !ok {
  211. return dbus.Variant{}, ErrIfaceNotFound
  212. }
  213. prop, ok := m[property]
  214. if !ok {
  215. return dbus.Variant{}, ErrPropNotFound
  216. }
  217. return dbus.MakeVariant(reflect.ValueOf(prop.Value).Elem().Interface()), nil
  218. }
  219. // GetAll implements org.freedesktop.DBus.Properties.GetAll.
  220. func (p *Properties) GetAll(iface string) (map[string]dbus.Variant, *dbus.Error) {
  221. p.mut.RLock()
  222. defer p.mut.RUnlock()
  223. m, ok := p.m[iface]
  224. if !ok {
  225. return nil, ErrIfaceNotFound
  226. }
  227. rm := make(map[string]dbus.Variant, len(m))
  228. for k, v := range m {
  229. rm[k] = dbus.MakeVariant(reflect.ValueOf(v.Value).Elem().Interface())
  230. }
  231. return rm, nil
  232. }
  233. // GetMust returns the value of the given property and panics if either the
  234. // interface or the property name are invalid.
  235. func (p *Properties) GetMust(iface, property string) interface{} {
  236. p.mut.RLock()
  237. defer p.mut.RUnlock()
  238. return reflect.ValueOf(p.m[iface][property].Value).Elem().Interface()
  239. }
  240. // Introspection returns the introspection data that represents the properties
  241. // of iface.
  242. func (p *Properties) Introspection(iface string) []introspect.Property {
  243. p.mut.RLock()
  244. defer p.mut.RUnlock()
  245. m := p.m[iface]
  246. s := make([]introspect.Property, 0, len(m))
  247. for name, prop := range m {
  248. s = append(s, prop.Introspection(name))
  249. }
  250. return s
  251. }
  252. // set sets the given property and emits PropertyChanged if appropriate. p.mut
  253. // must already be locked.
  254. func (p *Properties) set(iface, property string, v interface{}) error {
  255. prop := p.m[iface][property]
  256. err := dbus.Store([]interface{}{v}, prop.Value)
  257. if err != nil {
  258. return err
  259. }
  260. return p.emitChange(iface, property)
  261. }
  262. func (p *Properties) emitChange(iface, property string) error {
  263. prop := p.m[iface][property]
  264. switch prop.Emit {
  265. case EmitFalse:
  266. return nil // do nothing
  267. case EmitInvalidates:
  268. return p.conn.Emit(p.path, "org.freedesktop.DBus.Properties.PropertiesChanged",
  269. iface, map[string]dbus.Variant{}, []string{property})
  270. case EmitTrue:
  271. return p.conn.Emit(p.path, "org.freedesktop.DBus.Properties.PropertiesChanged",
  272. iface, map[string]dbus.Variant{property: dbus.MakeVariant(prop.Value)},
  273. []string{})
  274. case EmitConst:
  275. return nil
  276. default:
  277. panic("invalid value for EmitType")
  278. }
  279. }
  280. // Set implements org.freedesktop.Properties.Set.
  281. func (p *Properties) Set(iface, property string, newv dbus.Variant) *dbus.Error {
  282. p.mut.Lock()
  283. defer p.mut.Unlock()
  284. m, ok := p.m[iface]
  285. if !ok {
  286. return ErrIfaceNotFound
  287. }
  288. prop, ok := m[property]
  289. if !ok {
  290. return ErrPropNotFound
  291. }
  292. if !prop.Writable {
  293. return ErrReadOnly
  294. }
  295. if newv.Signature() != dbus.SignatureOf(prop.Value) {
  296. return ErrInvalidArg
  297. }
  298. if prop.Callback != nil {
  299. err := prop.Callback(&Change{p, iface, property, newv.Value()})
  300. if err != nil {
  301. return err
  302. }
  303. }
  304. if err := p.set(iface, property, newv.Value()); err != nil {
  305. return dbus.MakeFailedError(err)
  306. }
  307. return nil
  308. }
  309. // SetMust sets the value of the given property and panics if the interface or
  310. // the property name are invalid.
  311. func (p *Properties) SetMust(iface, property string, v interface{}) {
  312. p.mut.Lock()
  313. defer p.mut.Unlock() // unlock in case of panic
  314. err := p.set(iface, property, v)
  315. if err != nil {
  316. panic(err)
  317. }
  318. }