Debian Codegraph @

gi/object.hpp

raw symbols SCIP
1 #ifndef GI_OBJECT_HPP
2 #define GI_OBJECT_HPP
3
4 #include "callback.hpp"
5 #include "container.hpp"
6 #include "exception.hpp"
7 #include "objectbase.hpp"
8 #include "paramspec.hpp"
9 #include "value.hpp"
10
11 GI_MODULE_EXPORT
12 namespace gi
13 {
14 namespace detail
15 {
16 // helper
17
18 // signal argument connect/emit helper;
19 // turn (C++) argument into a GType or GValue
20 // most arguments are inputs (with specific GType),
21 // but some arguments are used as output with G_TYPE_POINTER (e.g. int*)
22 // which are mapped to (e.g.) int* or int& in C++ signature
23 template<typename Arg, bool DECAY>
24 struct signal_arg
25 {
26 static GType get_type() { return traits::gtype<Arg>::get_type(); }
27 static detail::Value make(Arg arg)
28 {
29 return detail::Value(std::forward<Arg>(arg));
30 }
31 };
32
33 // re-route e.g. const std::string& cases
34 template<typename Arg>
35 struct signal_arg<const Arg &, false> : public signal_arg<const Arg &, true>
36 {};
37
38 template<typename Arg>
39 struct signal_arg<Arg &, false>
40 {
41 static GType get_type() { return G_TYPE_POINTER; }
42 static detail::Value make(Arg &arg)
43 {
44 return signal_arg<Arg *, false>::make(&arg);
45 }
46 };
47
48 template<typename Arg>
49 struct signal_arg<Arg *, false>
50 {
51 static GType get_type() { return G_TYPE_POINTER; }
52 static detail::Value make(Arg *arg)
53 {
54 // (size of) wrapper argument should match wrappee
55 static_assert(sizeof(typename traits::ctype<Arg>::type) == sizeof(Arg), "");
56 // the above should suffice for proper handling
57 // however, in these output cases, transfer should also be considered,
58 // which is not (yet) available here
59 // (but could be passed along similar to callback argument info)
60 // so, restrict to plain cases for now
61 static_assert(traits::is_plain<Arg>::value, "");
62 return detail::Value(gpointer(arg));
63 }
64 };
65
66 // returns -size if signed numeric, +size if unsigned numeric, otherwise 0
67 inline int
68 get_number_size_signed(GType type)
69 {
70 // note; these are generally lower (absolute) bounds
71 // at least it works in the context where it is used below
72 #define GI_HANDLE_TYPE_SWITCH(cpptype, g_type, factor) \
73 case g_type: \
74 return factor * int(sizeof(cpptype));
75 switch (type) {
76 GI_HANDLE_TYPE_SWITCH(gchar, G_TYPE_CHAR, -1)
77 GI_HANDLE_TYPE_SWITCH(guchar, G_TYPE_UCHAR, 1)
78 GI_HANDLE_TYPE_SWITCH(gint, G_TYPE_INT, -1)
79 GI_HANDLE_TYPE_SWITCH(guint, G_TYPE_UINT, 1)
80 GI_HANDLE_TYPE_SWITCH(glong, G_TYPE_LONG, -1)
81 GI_HANDLE_TYPE_SWITCH(gulong, G_TYPE_ULONG, 1)
82 GI_HANDLE_TYPE_SWITCH(gint64, G_TYPE_INT64, -1)
83 GI_HANDLE_TYPE_SWITCH(guint64, G_TYPE_UINT64, 1)
84 }
85 #undef GI_HANDLE_TYPE_SWITCH
86 return 0;
87 }
88
89 // glib type systems treats G_TYPE_INT64 as distinct from the other types
90 // in practice, however, quite likely C gint64 == long
91 inline bool
92 compatible_type(GType expected, GType actual)
93 {
94 if (expected == G_TYPE_BOOLEAN)
95 return std::abs(get_number_size_signed(actual)) == sizeof(gboolean);
96 auto ssa_e = get_number_size_signed(expected);
97 auto ssa_a = get_number_size_signed(actual);
98 return ssa_e == ssa_a;
99 }
100
101 inline void
102 check_signal_type(GType tp, const gi::cstring_v name, GType return_type,
103 GType *param_types, guint n_params)
104 {
105 const char *errmsg("expected ");
106 auto check_types = [tp, &name, &errmsg](const std::string &desc,
107 GType expected, GType actual) {
108 // normalize
109 expected &= ~G_SIGNAL_TYPE_STATIC_SCOPE;
110 actual &= ~G_SIGNAL_TYPE_STATIC_SCOPE;
111 if (expected == actual || compatible_type(expected, actual) ||
112 g_type_is_a(expected, actual))
113 return;
114 std::string msg = errmsg;
115 msg += desc + " type ";
116 msg += detail::make_string(g_type_name(expected)) + " != ";
117 msg += detail::make_string(g_type_name(actual));
118 detail::try_throw(invalid_signal_callback_error(tp, name, msg));
119 };
120
121 // determine signal (detail)
122 guint id;
123 GQuark detail;
124 if (!g_signal_parse_name(name.c_str(), tp, &id, &detail, false) || (id == 0))
125 detail::try_throw(unknown_signal_error(tp, name));
126 // get signal info
127 GSignalQuery query;
128 g_signal_query(id, &query);
129 // check
130 if (n_params != query.n_params + 1) {
131 auto msg = std::string(errmsg) + "argument count ";
132 msg += std::to_string(query.n_params);
133 msg += " != " + std::to_string(n_params);
134 detail::try_throw(invalid_signal_callback_error(tp, name, msg));
135 }
136 check_types("return", query.return_type, return_type);
137 check_types("instance", query.itype, param_types[0]);
138 const std::string arg("argument ");
139 for (guint i = 0; i < query.n_params; ++i)
140 check_types(
141 arg + std::to_string(i + 1), query.param_types[i], param_types[i + 1]);
142 }
143
144 template<typename G>
145 struct signal_type;
146
147 template<typename R, typename... Args>
148 struct signal_type<R(Args...)>
149 {
150 static void check(GType tp, const gi::cstring_v name)
151 {
152 // capture type info and delegate
153 const int argcount = sizeof...(Args);
154 GType ti[] = {signal_arg<Args, false>::get_type()...};
155 check_signal_type(tp, name, traits::gtype<R>::get_type(), ti, argcount);
156 }
157 };
158
159 // like GParameter, but with extra Value trimming
160 struct Parameter
161 {
162 const char *name;
163 detail::Value value;
164 };
165
166 #ifdef GI_OBJECT_NEWV
167 GI_DISABLE_DEPRECATED_WARN_BEGIN
168 static_assert(sizeof(Parameter) == sizeof(GParameter), "");
169 GI_DISABLE_DEPRECATED_WARN_END
170 #endif
171
172 inline void
173 fill_parameters(Parameter *)
174 {
175 // no-op
176 }
177
178 template<typename Arg, typename... Args>
179 inline void
180 fill_parameters(Parameter *param, const char *name, Arg &&arg, Args &&...args)
181 {
182 param->name = name;
183 param->value.init<typename std::remove_reference<Arg>::type>();
184 set_value(&param->value, std::forward<Arg>(arg));
185 fill_parameters(param + 1, std::forward<Args>(args)...);
186 }
187
188 } // namespace detail
189
190 #if GLIB_CHECK_VERSION(2, 54, 0)
191 #define GI_GOBJECT_PROPERTY_VALUE 1
192 #endif
193
194 namespace repository
195 {
196 /* if you have arrived here due to an ambiguous GObject reference
197 * (both the C typedef GObject and this namespace)
198 * then that can be worked-around by:
199 * + using _GObject (struct name instead)
200 * + adjust 'using namespace' style imports e.g. alias
201 * namespace GObject_ = gi::GObject;
202 * or simply do not mention GObject at all and simply use the wrappers ;-)
203 */
204 namespace GObject
205 {
206 typedef std::vector<detail::Parameter> construct_params;
207
208 template<typename... Args>
209 construct_params
210 make_construct_params(Args &&...args)
211 {
212 const int nparams = sizeof...(Args) / 2;
213 construct_params parameters;
214 parameters.resize(nparams);
215 detail::fill_parameters(parameters.data(), std::forward<Args>(args)...);
216 return parameters;
217 }
218
219 class Object : public detail::ObjectBase
220 {
221 typedef Object self;
222 typedef detail::ObjectBase super_type;
223
224 public:
225 typedef ::GObject BaseObjectType;
226
227 Object(std::nullptr_t = nullptr) : super_type() {}
228
229 BaseObjectType *gobj_() { return (BaseObjectType *)super_type::gobj_(); }
230 const BaseObjectType *gobj_() const
231 {
232 return (const BaseObjectType *)super_type::gobj_();
233 }
234 BaseObjectType *gobj_copy_() const
235 {
236 return (BaseObjectType *)super_type::gobj_copy_();
237 }
238
239 // class type
240 static GType get_type_() { return G_TYPE_OBJECT; }
241 // instance type
242 GType gobj_type_() const { return G_OBJECT_TYPE(gobj_()); }
243
244 // type-erased generic object creation
245 // transfer full return
246 static gpointer new_(GType gtype, const construct_params &params)
247 {
248 #ifdef GI_OBJECT_NEWV
249 GI_DISABLE_DEPRECATED_WARN_BEGIN
250 auto result =
251 g_object_newv(gtype, params.size(), (GParameter *)params.data());
252 GI_DISABLE_DEPRECATED_WARN_END
253 #else
254 std::vector<const char *> names;
255 std::vector<GValue> values;
256 names.reserve(params.size());
257 values.reserve(params.size());
258 // ownership remains in params
259 for (auto &&p : params) {
260 names.push_back(p.name);
261 values.emplace_back(p.value);
262 }
263 auto result = g_object_new_with_properties(
264 gtype, params.size(), names.data(), values.data());
265 #endif
266 // GIR says transfer full, but let's be careful and really make it so
267 // if likely still floating, then we assume ownership
268 // but if it is no longer, then it has already been stolen (e.g.
269 // GtkWindow), and we need to add one here
270 if (g_type_is_a(gtype, G_TYPE_INITIALLY_UNOWNED))
271 g_object_ref_sink(result);
272 return result;
273 }
274
275 // type-based generic object creation
276 template<typename CTYPE, typename... Args>
277 static auto new_(GType gtype, Args &&...args)
278 {
279 auto parameters = make_construct_params(std::forward<Args>(args)...);
280 auto *result = CTYPE(new_(gtype, parameters));
281 return gi::wrap(result, transfer_full);
282 }
283
284 // type-based generic object creation
285 // Args are a sequence of name, value
286 template<typename TYPE, typename... Args>
287 static TYPE new_(Args &&...args)
288 {
289 return new_<typename TYPE::BaseObjectType *>(
290 TYPE::get_type_(), std::forward<Args>(args)...);
291 }
292
293 // property stuff
294 // generic type unsafe
295 template<typename V>
296 self &set_property(ParamSpec _pspec, V &&val)
297 {
298 // additional checks
299 // allows for basic conversion between arithmetic types
300 // without worrying about those details
301 auto pspec = _pspec.gobj_();
302 detail::Value v(std::forward<V>(val));
303 detail::Value dest;
304 GValue *p = &v;
305 if (G_VALUE_TYPE(&v) != pspec->value_type) {
306 g_value_init(&dest, pspec->value_type);
307 if (!g_value_transform(&v, &dest))
308 detail::try_throw(
309 detail::transform_error(pspec->value_type, pspec->name));
310 p = &dest;
311 }
312 g_object_set_property(gobj_(), pspec->name, p);
313 return *this;
314 }
315
316 template<typename V>
317 self &set_property(const gi::cstring_v propname, V &&val)
318 {
319 return set_property<V>(find_property(propname, true), std::forward<V>(val));
320 }
321
322 template<typename V>
323 self &set_properties(const gi::cstring_v propname, V &&val)
324 {
325 return set_property<V>(propname, std::forward<V>(val));
326 }
327
328 // set a number of props
329 template<typename V, typename... Args>
330 self &set_properties(const gi::cstring_v propname, V &&val, Args... args)
331 {
332 g_object_freeze_notify(gobj_());
333 #if GI_CONFIG_EXCEPTIONS
334 try {
335 #endif
336 set_property(propname, std::forward<V>(val));
337 set_properties(std::forward<Args>(args)...);
338 #if GI_CONFIG_EXCEPTIONS
339 } catch (...) {
340 g_object_thaw_notify(gobj_());
341 throw;
342 }
343 #endif
344 g_object_thaw_notify(gobj_());
345 return *this;
346 }
347
348 #ifdef GI_GOBJECT_PROPERTY_VALUE
349 self &set_property(const gi::cstring_v propname, Value val)
350 {
351 g_object_set_property(gobj_(), propname.c_str(), val.gobj_());
352 return *this;
353 }
354 #endif
355
356 template<typename V>
357 V get_property(const char *propname) const
358 {
359 // this would return a ref to what is owned by stack-local v below
360 static_assert(!traits::is_reftype<V>::value, "dangling ref");
361 detail::Value v;
362 v.init<V>();
363 // the _get_ already tries to transform
364 // also close enough to const
365 g_object_get_property(const_cast<::GObject *>(gobj_()), propname, &v);
366 return detail::get_value<V>(&v);
367 }
368
369 template<typename V>
370 V get_property(const gi::cstring_v propname) const
371 {
372 return get_property<V>(propname.c_str());
373 }
374
375 #ifdef GI_GOBJECT_PROPERTY_VALUE
376 Value get_property(const gi::cstring_v propname) const
377 {
378 Value result;
379 const gchar *name = propname.c_str();
380 GValue *val = result.gobj_();
381 g_object_getv(const_cast<::GObject *>(gobj_()), 1, &name, val);
382 return result;
383 }
384 #endif
385
386 static ParamSpec find_property(
387 GType gtype, const gi::cstring_v propname, bool _throw = false)
388 {
389 GParamSpec *spec;
390 if (g_type_is_a(gtype, G_TYPE_INTERFACE)) {
391 // interface should be loaded if we have an instance here
392 auto vtable = g_type_default_interface_peek(gtype);
393 spec = g_object_interface_find_property(vtable, propname.c_str());
394 } else {
395 spec = g_object_class_find_property(
396 (GObjectClass *)g_type_class_peek(gtype), propname.c_str());
397 }
398 if (_throw && !spec)
399 detail::try_throw(
400 detail::unknown_property_error(gtype, propname.c_str()));
401 return gi::wrap(spec, transfer_none);
402 }
403
404 ParamSpec find_property(
405 const gi::cstring_v propname, bool _throw = false) const
406 {
407 return find_property(gobj_type_(), propname, _throw);
408 }
409
410 gi::Collection<gi::DSpan, GParamSpec *, gi::transfer_container_t>
411 list_properties() const
412 {
413 GParamSpec **specs;
414 guint nspecs = 0;
415 if (g_type_is_a(gobj_type_(), G_TYPE_INTERFACE)) {
416 // interface should be loaded if we have an instance here
417 auto vtable = g_type_default_interface_peek(gobj_type_());
418 specs = g_object_interface_list_properties(vtable, &nspecs);
419 } else {
420 specs =
421 g_object_class_list_properties(G_OBJECT_GET_CLASS(gobj_()), &nspecs);
422 }
423 return wrap_to<
424 gi::Collection<gi::DSpan, GParamSpec *, gi::transfer_container_t>>(
425 specs, nspecs, transfer_container);
426 }
427
428 // signal stuff
429 private:
430 template<typename F, typename Functor>
431 gulong connect_data(
432 const gi::cstring_v signal, Functor &&f, GConnectFlags flags)
433 {
434 // runtime signature check
435 detail::signal_type<F>::check(gobj_type_(), signal);
436 auto w = new detail::transform_signal_wrapper<F>(std::forward<Functor>(f));
437 // mind gcc's -Wcast-function-type
438 return g_signal_connect_data(gobj_(), signal.c_str(),
439 (GCallback)&w->wrapper, w, (GClosureNotify)(GCallback)&w->destroy,
440 flags);
441 }
442
443 public:
444 template<typename F, typename Functor>
445 gulong connect(const gi::cstring_v signal, Functor &&f)
446 {
447 return connect_data<F, Functor>(
448 signal, std::forward<Functor>(f), (GConnectFlags)0);
449 }
450
451 template<typename F, typename Functor>
452 gulong connect_after(const gi::cstring_v signal, Functor &&f)
453 {
454 return connect_data<F, Functor>(
455 signal, std::forward<Functor>(f), G_CONNECT_AFTER);
456 }
457
458 // TODO the object variants ??
459
460 // in case of unsupported signal signature
461 // connect using a plain C signature without check/transform (wrap/unwrap)
462 template<typename F, typename Functor>
463 gulong connect_unchecked(
464 const gi::cstring_v signal, Functor &&f, GConnectFlags flags = {})
465 {
466 auto w = new detail::callback_wrapper<F>(std::forward<Functor>(f));
467 // mind gcc's -Wcast-function-type
468 return g_signal_connect_data(gobj_(), signal.c_str(),
469 (GCallback)&w->wrapper, w, (GClosureNotify)(GCallback)&w->destroy,
470 flags);
471 }
472
473 void disconnect(gulong id) { g_signal_handler_disconnect(gobj_(), id); }
474
475 // Args... may be explicitly specified or deduced
476 // if deduced; arrange to decay/strip reference below
477 // if not deduced; may need to considere specified type as-is
478 template<typename R, bool DECAY = true, typename... Args>
479 R emit(const gi::cstring_v signal, Args &&...args)
480 {
481 // static constexpr bool DECAY = true;
482 guint id;
483 GQuark detail;
484 if (!g_signal_parse_name(signal.c_str(), gobj_type_(), &id, &detail, true))
485 detail::try_throw(std::out_of_range(std::string("unknown signal name: ") +
486 detail::make_string(signal.c_str())));
487
488 detail::Value values[] = {detail::Value(*this),
489 detail::signal_arg<Args, DECAY>::make(std::forward<Args>(args))...};
490 detail::Value retv;
491 retv.init<R>();
492 g_signal_emitv(values, id, detail, &retv);
493 return detail::get_value<R>(&retv);
494 }
495
496 void handler_block(gulong handler_id)
497 {
498 g_signal_handler_block(gobj_(), handler_id);
499 }
500
501 void handler_unblock(gulong handler_id)
502 {
503 g_signal_handler_unblock(gobj_(), handler_id);
504 }
505
506 bool handler_is_connected(gulong handler_id)
507 {
508 return g_signal_handler_is_connected(gobj_(), handler_id);
509 }
510
511 void stop_emission(guint id, GQuark detail)
512 {
513 g_signal_stop_emission(gobj_(), id, detail);
514 }
515
516 void stop_emission_by_name(const gi::cstring_v signal)
517 {
518 g_signal_stop_emission_by_name(gobj_(), signal.c_str());
519 }
520 };
521
522 } // namespace GObject
523
524 template<>
525 struct declare_cpptype_of<::GObject>
526 {
527 typedef repository::GObject::Object type;
528 };
529
530 namespace GLib
531 {
532 // predefined
533 typedef detail::callback<void(), gi::transfer_none_t> DestroyNotify;
534 } // namespace GLib
535
536 } // namespace repository
537
538 // type safe signal connection
539 template<typename T, typename Base = repository::GObject::Object>
540 class signal_proxy;
541
542 template<typename R, typename Instance, typename... Args, typename Base>
543 class signal_proxy<R(Instance, Args...), Base>
544 {
545 protected:
546 typedef R(CppSig)(Instance, Args...);
547 Base object_;
548 gi::cstring name_;
549
550 public:
551 typedef CppSig function_type;
552 typedef detail::connectable<function_type> slot_type;
553
554 signal_proxy(Base owner, gi::cstring name)
555 : object_(owner), name_(std::move(name))
556 {}
557
558 template<typename Functor>
559 gulong connect(Functor &&f)
560 {
561 return object_.template connect<CppSig>(name_, std::forward<Functor>(f));
562 }
563
564 template<typename Functor>
565 gulong connect_after(Functor &&f)
566 {
567 return object_.template connect_after<CppSig>(
568 name_, std::forward<Functor>(f));
569 }
570
571 R emit(Args... args)
572 {
573 return object_.template emit<R, false, Args...>(
574 name_, std::forward<Args>(args)...);
575 }
576
577 template<typename Functor>
578 slot_type slot(Functor &&f)
579 {
580 return slot_type(std::forward<Functor>(f));
581 }
582 };
583
584 // type safe property setting
585 template<typename T, typename Base = repository::GObject::Object>
586 class property_proxy
587 {
588 typedef property_proxy self;
589 typedef repository::GObject::ParamSpec ParamSpec;
590
591 protected:
592 Base object_;
593 ParamSpec pspec_;
594
595 public:
596 property_proxy(Base owner, ParamSpec pspec) : object_(owner), pspec_(pspec) {}
597
598 property_proxy(Base owner, const gi::cstring_v name)
599 : property_proxy(owner, owner.find_property(name, true))
600 {}
601
602 void set(T v) { object_.set_property(pspec_, std::move(v)); }
603
604 self &operator=(T v)
605 {
606 set(v);
607 return *this;
608 }
609
610 T get() const
611 {
612 return object_.template get_property<T>(pspec_.gobj_()->name);
613 }
614
615 ParamSpec param_spec() const { return pspec_; }
616
617 signal_proxy<void(Base, ParamSpec)> signal_notify() const
618 {
619 return signal_proxy<void(Base, ParamSpec)>(
620 object_, gi::cstring_v("notify::") + gi::cstring_v(pspec_.name_()));
621 }
622 };
623
624 template<typename T, typename Base = repository::GObject::Object>
625 class property_proxy_read : private property_proxy<T, Base>
626 {
627 typedef property_proxy<T, Base> super;
628
629 public:
630 using super::get;
631 using super::property_proxy;
632 };
633
634 template<typename T, typename Base = repository::GObject::Object>
635 class property_proxy_write : private property_proxy<T, Base>
636 {
637 typedef property_proxy<T, Base> super;
638
639 public:
640 using super::property_proxy;
641 using super::set;
642 using super::operator=;
643 };
644
645 // interface (ptr) is wrapped the same way,
646 // as it is essentially a ptr to implementing object
647 // TODO use other intermediate base ??
648 using InterfaceBase = repository::GObject::Object;
649
650 namespace repository
651 {
652 namespace GObject
653 {
654 // connection helpers
655 namespace internal
656 {
657 class SignalConnection : public detail::connection_impl
658 {
659 public:
660 SignalConnection(gulong id, detail::connection_status s, Object object)
661 : connection_impl(id, s), object_(object)
662 {}
663
664 void disconnect() { object_.disconnect(id_); }
665
666 private:
667 Object object_;
668 };
669
670 } // namespace internal
671
672 using SignalConnection = detail::connection<internal::SignalConnection>;
673 using SignalScopedConnection = detail::scoped_connection<SignalConnection>;
674
675 } // namespace GObject
676
677 } // namespace repository
678
679 // connection callback type
680 template<typename G>
681 using slot = detail::connectable<G>;
682
683 template<typename G>
684 inline repository::GObject::SignalConnection
685 make_connection(
686 gulong id, const gi::slot<G> &s, repository::GObject::Object object)
687 {
688 using repository::GObject::SignalConnection;
689 return SignalConnection(id, s.connection(), object);
690 }
691
692 } // namespace gi
693
694 #endif // GI_OBJECT_HPP