Debian Codegraph @

gi/objectclass.hpp

raw symbols SCIP
1 #ifndef GI_OBJECTCLASS_HPP
2 #define GI_OBJECTCLASS_HPP
3
4 /**
5 * The purposes of the code and classes here is to perform registration of
6 * a new GType type for a custom class that (suitably) inherits from these.
7 * Setting up a new GType involves registration of a new type (and its signals
8 * and properties). This involves potentially custom overridden implementations
9 * of the parent class(es) (C-style virtual) methods (= entries in class
10 * structure) and likewise so for the interfaces. For either of the latter
11 * cases, pointers to wrapper functions are inserted in the class/interface
12 * struct, that will in turn call generated C++ virtual methods
13 * (which have presumably been overridden by the custom subclass).
14 *
15 * The tricky part in the above is that GType/C methods are "optional",
16 * in that an entry in a class/interface struct can be left as NULL,
17 * and it is a common pattern for calling code to check for such
18 * (rather than unconditionally calling). To preserve such behaviour,
19 * an entry in a class/interface struct should only be "routed" to a
20 * C++ virtual method if the custom SubClass actually has a definition for it.
21 * The approach below tries to detect this (basically by checking if
22 * SubClass::method is a different type than Base::method). But that might
23 * fail (with compilation errors due to overload resolution failure), so there
24 * is also a system to manually specify what is defined, e.g. whether the
25 * corresponding entry in the class/interface struct should be filled
26 * for the SubClass' generated GType.
27 *
28 */
29
30 #include "callback.hpp"
31 #include "object.hpp"
32
33 #include <stdint.h>
34
35 GI_MODULE_EXPORT
36 namespace gi
37 {
38 // slightly nasty; will be generated
39 namespace repository
40 {
41 namespace GObject
42 {
43 enum class SignalFlags : std::underlying_type<::GSignalFlags>::type;
44 }
45 } // namespace repository
46
47 // specify construction type when creating ObjectClass based object
48 struct construct_t
49 {
50 const int value;
51 constexpr explicit construct_t(int v = 0) : value(v) {}
52 };
53 struct construct_auto_t : public construct_t
54 {
55 constexpr construct_auto_t() : construct_t(0) {}
56 };
57 struct construct_cpp_t : public construct_t
58 {
59 constexpr construct_cpp_t() : construct_t(1) {}
60 };
61 struct construct_c_t : public construct_t
62 {
63 constexpr construct_c_t() : construct_t(2) {}
64 };
65
66 namespace detail
67 {
68 class ObjectBaseClass : public noncopyable
69 {
70 public:
71 virtual ~ObjectBaseClass() {}
72
73 ObjectBaseClass() : gobject_(nullptr) {}
74
75 ObjectBaseClass(ObjectBaseClass &&other)
76 {
77 gobject_ = other.gobject_;
78 other.gobject_ = nullptr;
79 }
80
81 ObjectBaseClass &operator=(ObjectBaseClass &&other)
82 {
83 if (this != &other) {
84 gobject_ = other.gobject_;
85 other.gobject_ = nullptr;
86 }
87 return *this;
88 }
89
90 protected:
91 typedef void (*interface_register_function)(GType class_type, gpointer init);
92 void request_interface(interface_register_function reg, gpointer init)
93 {
94 itfs.emplace_back(reg, init);
95 }
96
97 GType base_gtype()
98 {
99 return gobject_ ? g_type_parent(G_OBJECT_TYPE(gobject_)) : G_TYPE_NONE;
100 }
101
102 protected:
103 // owns 1 ref (possibly managed externally)
104 GObject *gobject_;
105 // GType in case no gobject_
106 GType gtype_;
107 // additional type setup
108 using interface_init_t = std::pair<interface_register_function, gpointer>;
109 using interface_inits_t = std::vector<interface_init_t>;
110 interface_inits_t itfs;
111 };
112
113 //// interface setup ////
114
115 // virtual inheritance as multiple inheritance will be used
116 // however, only 1 base instance should be around
117 class InterfaceClass : public virtual ObjectBaseClass
118 {
119 protected:
120 static void add_interface(GType class_type, GType itf_type,
121 GInterfaceInitFunc itf_init, gpointer init_data)
122 {
123 GInterfaceInfo itf_info = {
124 itf_init, // interface_init
125 nullptr, // interface_finalize
126 init_data // interface_data
127 };
128
129 g_type_add_interface_static(class_type, itf_type, &itf_info);
130 }
131 };
132
133 template<typename ClassDef, typename SubClass>
134 gpointer forward_make_type_init_data();
135
136 template<typename InterfaceDef>
137 class InterfaceImpl : public InterfaceDef, public InterfaceClass
138 {
139 typedef typename InterfaceDef::instance_type instance_type_t;
140
141 protected:
142 static void register_interface(GType class_type, gpointer init_data)
143 {
144 add_interface(class_type, InterfaceDef::instance_type::get_type_(),
145 InterfaceDef::interface_init, init_data);
146 }
147
148 // init data for registration-only use
149 template<typename SubClass>
150 static ObjectBaseClass::interface_init_t interface_init_data()
151 {
152 return {InterfaceImpl::register_interface,
153 (gpointer)forward_make_type_init_data<InterfaceImpl, SubClass>()};
154 }
155
156 InterfaceImpl(gpointer init_data = nullptr)
157 {
158 request_interface(InterfaceImpl::register_interface, init_data);
159 }
160
161 // conversion to regular interface side
162 instance_type_t interface_(gi::interface_tag<instance_type_t>)
163 {
164 return gi::wrap(
165 (typename instance_type_t::BaseObjectType *)g_object_ref(gobject_),
166 gi::transfer_full);
167 }
168
169 instance_type_t interface_()
170 {
171 return gi::wrap(
172 (typename instance_type_t::BaseObjectType *)g_object_ref(gobject_),
173 gi::transfer_full);
174 }
175 };
176
177 template<typename InterfaceImpl>
178 class InterfaceClassImpl : public InterfaceImpl
179 {
180 typedef typename InterfaceImpl::instance_type::BaseObjectType *c_type;
181 typedef typename InterfaceImpl::interface_type interface_type_t;
182
183 // use runtime data to avoid code generation of template
184 // interface_type_t *istruct_;
185 GType klass_;
186
187 protected:
188 static interface_type_t *get_struct_(GType ktype)
189 {
190 auto klass = g_type_class_peek(ktype);
191 return (interface_type_t *)g_type_interface_peek(
192 klass, InterfaceImpl::instance_type::get_type_());
193 }
194
195 interface_type_t *get_struct_() { return get_struct_(klass_); }
196
197 c_type gobj_() { return (c_type)this->gobject_; }
198
199 InterfaceClassImpl(GType klass, gpointer itf_init_data = nullptr)
200 : InterfaceImpl(itf_init_data), klass_(klass)
201 {}
202 };
203
204 class ObjectClass;
205 class PropertyBase;
206
207 inline GQuark
208 object_data_quark()
209 {
210 static const char *OBJECT_DATA_KEY = "GIOBJECT_OBJECT";
211 static GQuark q = g_quark_from_static_string(OBJECT_DATA_KEY);
212 return q;
213 }
214
215 using repository::GObject::Object;
216 using repository::GObject::ParamSpec;
217 using repository::GObject::SignalFlags;
218
219 //// init data collection ////
220
221 // a function pointer that serves as factory for the actual class_init data
222 // (e.g. holds data on which methods have been overridden)
223 // (void return to avoid function cast warning; returns real data otherwise)
224 typedef void (*type_init_data_factory_t)();
225 template<typename ClassDef, typename SubClass,
226 typename std::enable_if<std::is_same<SubClass, void>::value>::type * =
227 nullptr>
228 type_init_data_factory_t
229 make_type_init_data()
230 {
231 return nullptr;
232 }
233
234 template<typename BaseDef, typename SubClass,
235 typename std::enable_if<!std::is_same<SubClass, void>::value>::type * =
236 nullptr>
237 type_init_data_factory_t
238 make_type_init_data()
239 {
240 // hard cast; should return meaningful data
241 return (type_init_data_factory_t)&BaseDef::TypeInitData::template factory<
242 SubClass>;
243 }
244
245 template<typename ClassDef, typename SubClass>
246 gpointer
247 forward_make_type_init_data()
248 {
249 return (gpointer)make_type_init_data<ClassDef, SubClass>();
250 }
251
252 // in generated code;
253 // each class/interface member (function) is assocated with a single type
254 // base class for tagged boolean member types
255 // (default to true for legacy case where no init data is captured from type)
256 template<typename Tag>
257 struct member_type
258 {
259 bool value;
260 constexpr member_type(bool v = true) : value(v) {}
261 explicit operator bool() { return value; }
262 };
263
264 // combine manual Spec with code generated Default
265 template<typename Spec, typename Default>
266 struct Combine : public Spec, public Default
267 {
268 using Default::has_definition;
269 using Spec::defines;
270 // dispatch from query signature to default if no manual specificiation
271 template<typename MemberType, typename SubClass>
272 constexpr static bool defines(const MemberType *m, const SubClass *cl)
273 {
274 return has_definition(m, cl);
275 };
276 };
277
278 template<typename SubClass, typename Default>
279 using DefinitionData = Combine<typename SubClass::DefinitionData, Default>;
280
281 // see objectclass macros in gi_inc for how the above is used
282
283 //// class setup ////
284
285 // this collects properties that will be installed on a class type
286 // during the class_init (as opposed to added later on by property members)
287 // this is especially needed to install properties required by an interface
288 // (as those are checked by object_interface_check_properties early on)
289 typedef std::map<std::string, std::pair<PropertyBase *, ParamSpec>> properties;
290
291 template<typename T>
292 class property;
293
294 template<typename T, typename Base = repository::GObject::Object>
295 class signal;
296
297 struct ParamSpecInit : public ParamSpec
298 {
299 cstring_v name_;
300 ParamSpec spec_;
301
302 // full spec arguments
303 template<typename T, typename P, typename... Args,
304 typename std::enable_if<sizeof...(Args) != 1>::type * = nullptr>
305 ParamSpecInit(property<P> T::*, Args &&...args)
306 : spec_(ParamSpec::new_<P>(std::forward<Args>(args)...))
307 {}
308
309 // name suffices for override property
310 template<typename T, typename P>
311 ParamSpecInit(property<P> T::*, const cstring_v name) : name_(name)
312 {}
313 };
314
315 struct properties_init : public properties
316 {
317 properties_init(std::initializer_list<ParamSpecInit> pd)
318 {
319 for (auto &&e : pd) {
320 // should have either one
321 auto name = e.name_;
322 if (e.spec_)
323 name = e.spec_.name_();
324 insert({name, {nullptr, e.spec_}});
325 }
326 }
327 };
328
329 struct SignalSpec
330 {
331 GType ret_type;
332 std::vector<GType> types;
333 gi::cstring_v name;
334 SignalFlags flags;
335
336 template<typename T, typename R, typename Instance, typename... Args>
337 SignalSpec(signal<R(Instance, Args...)> T::*, const gi::cstring_v _name,
338 SignalFlags _flags = (SignalFlags)0)
339 : ret_type(gi::traits::gtype<R>::get_type()),
340 types({gi::traits::gtype<Args>::get_type()...}), name(_name),
341 flags(_flags)
342 {}
343 };
344
345 using SignalSpecInit = SignalSpec;
346
347 using signals = std::vector<SignalSpec>;
348 using signals_init = signals;
349
350 inline void class_init_props_sigs(
351 ObjectClass *impl, gpointer g_class, gpointer props, gpointer sigs);
352
353 inline gi::cstring_v
354 klass_type_name(const std::type_info &ti, gi::cstring_v klassname)
355 {
356 return (klassname && klassname.at(0)) ? klassname : ti.name();
357 }
358
359 template<typename T, typename Enable = void>
360 struct custom_class_init : public std::false_type
361 {
362 static constexpr GClassInitFunc value = nullptr;
363 };
364
365 template<typename T>
366 struct custom_class_init<T,
367 typename traits::if_valid_type<decltype(T::custom_class_init)>::type>
368 : public std::true_type
369 {
370 static constexpr auto value = T::custom_class_init;
371 };
372
373 template<typename T, typename Enable = void>
374 struct custom_instance_init : public std::false_type
375 {
376 static constexpr GInstanceInitFunc value = nullptr;
377 };
378
379 template<typename T>
380 struct custom_instance_init<T,
381 typename traits::if_valid_type<decltype(T::custom_init)>::type>
382 : public std::true_type
383 {
384 static constexpr auto value = T::custom_init;
385 };
386
387 class ObjectClass : public virtual ObjectBaseClass
388 {
389 public:
390 typedef gi::repository::GObject::Object instance_type;
391 typedef GObjectClass class_type;
392 // above init code refers to this inner type unconditionally
393 // so arrange for a fallback in baseclass
394 struct DefinitionData
395 {
396 constexpr static bool defines(...) { return false; }
397 };
398
399 // used as single argument in constructor for c-first style subclass
400 struct InitData
401 {
402 mutable Object instance;
403
404 explicit operator bool() const { return instance.gobj_(); }
405
406 protected:
407 // only for internal use
408 // and also complicates calling any function/constructor using this type
409 // silly dummy argument prevents ambiguity in ObjectImpl constructors
410 // when specifying all {}
411 explicit InitData(int) {}
412 friend class ObjectClass;
413 };
414
415 protected:
416 struct ClassInitNode
417 {
418 GClassInitFunc self;
419 type_init_data_factory_t class_init_data_factory;
420 const ClassInitNode *child;
421 };
422
423 private:
424 static const constexpr char *CLASS_PREFIX = "GIOBJECT__";
425
426 static std::string canonical_name(const std::string &name)
427 {
428 auto result = name;
429 for (auto &p : result) {
430 if (!(g_ascii_isalnum(p) || p == '_' || p == '-'))
431 p = '+';
432 }
433 return result;
434 }
435
436 typedef void (*GObjectConstructed)(GObject *object);
437 typedef GObject *(*GObjectConstructor)(GType type,
438 guint n_construct_properties,
439 GObjectConstructParam *construct_properties);
440
441 typedef std::vector<std::pair<GClassInitFunc, type_init_data_factory_t>>
442 class_inits_t;
443 struct class_data_t
444 {
445 std::unique_ptr<class_inits_t> class_inits;
446 GClassInitFunc custom_class_init;
447 const properties *props;
448 const signals *sigs;
449 ObjectClass *impl;
450 GObjectConstructor constructor;
451 };
452
453 struct custom_inits_t
454 {
455 GClassInitFunc custom_class_init{};
456 GInstanceInitFunc custom_init{};
457 GObjectConstructor constructor{};
458 GObjectConstructed constructed{};
459 };
460
461 static void class_init_all(gpointer g_class, gpointer class_data)
462 {
463 std::unique_ptr<class_data_t> data((class_data_t *)class_data);
464
465 // class_init below is called with top-level class_data,
466 // others (= code generated) with their own
467 for (auto &&ci : *data->class_inits)
468 ci.first(
469 g_class, ci.first == &class_init ? class_data : gpointer(ci.second));
470 }
471
472 static void class_init(gpointer g_class, gpointer class_data)
473 {
474 class_data_t *data = ((class_data_t *)class_data);
475 // delegate property handling
476 class_init_props_sigs(
477 data->impl, g_class, (gpointer)data->props, (gpointer)data->sigs);
478 // set constructed to invoke constructor
479 if (data->constructor)
480 ((GObjectClass *)(g_class))->constructor = data->constructor;
481 // also call top-level class custom class init
482 if (data->custom_class_init) {
483 data->custom_class_init(g_class, nullptr);
484 }
485 }
486
487 GType register_type(GType base_type, const gi::cstring_v klassname,
488 const ClassInitNode &init_node, const interface_inits_t &itfs,
489 const properties &props, const signals &sigs, custom_inits_t custom_inits)
490 {
491 // nothing to do if already registered
492 GType custom_type = g_type_from_name(klassname.c_str());
493 if (custom_type)
494 return custom_type;
495
496 // otherwise create with same class/instance size as parent type
497 GTypeQuery base_query = {
498 0,
499 nullptr,
500 0,
501 0,
502 };
503 g_type_query(base_type, &base_query);
504
505 const guint16 class_size = (guint16)base_query.class_size;
506 const guint16 instance_size = (guint16)base_query.instance_size;
507
508 // collect chain of class inits
509 std::unique_ptr<class_inits_t> class_inits(new class_inits_t());
510 auto node = &init_node;
511 while (node) {
512 if (node->self)
513 class_inits->push_back({node->self, node->class_init_data_factory});
514 node = node->child;
515 }
516
517 // assemble class_data
518 std::unique_ptr<class_data_t> class_data(new class_data_t());
519 // class creation will be triggered upon instance creation
520 // which will happen shortly after this class
521 // (so the list has to handled special, but the others will still be
522 // around)
523 class_data->class_inits = std::move(class_inits);
524 class_data->custom_class_init = custom_inits.custom_class_init;
525 class_data->impl = this;
526 class_data->props = &props;
527 class_data->sigs = &sigs;
528 class_data->constructor = custom_inits.constructor;
529
530 const GTypeInfo derived_info = {
531 class_size,
532 nullptr, // base_init
533 nullptr, // base_finalize
534 class_init_all,
535 nullptr, // class_finalize
536 class_data.release(), // class_data
537 instance_size,
538 0, // n_preallocs
539 custom_inits.custom_init, // instance_init
540 nullptr, // value_table
541 };
542
543 custom_type = g_type_register_static(
544 base_type, klassname.c_str(), &derived_info, GTypeFlags(0));
545
546 // handle interfaces
547 for (auto &&itf : itfs)
548 itf.first(custom_type, itf.second);
549
550 // force/finish class creation,
551 // so a subsequent _peek does not return NULL
552 // (and lists above are still around)
553 g_type_class_unref(g_type_class_ref(custom_type));
554
555 return custom_type;
556 }
557
558 // minor convenience wrap for the above
559 GType register_type(GType parent, const gi::cstring_v klassname,
560 const ClassInitNode *node, const properties &props, const signals &sigs,
561 custom_inits_t custom_inits)
562 {
563 auto gtype = register_type(parent, klassname, {class_init, nullptr, node},
564 itfs, props, sigs, custom_inits);
565 itfs.clear();
566 return gtype;
567 }
568
569 void setup_instance(GType gtype,
570 const repository::GObject::construct_params &params,
571 gpointer instance = nullptr)
572 {
573 // not good if provided instance already has associated C++ instance
574 g_return_if_fail(!instance || !ObjectClass::instance((GObject *)instance));
575 g_return_if_fail(gtype);
576
577 // no longer needed
578 itfs.clear();
579 // create and link object instance
580 // if needed, that is, otherwise use provided instance and tie onto that one
581 gtype_ = gtype;
582 GObject *obj = gobject_ =
583 (GObject *)(instance ? instance : Object::new_(gtype, params));
584 // should still be floating, then we assume ownership
585 // if it is no longer, then it has already been stolen (e.g. GtkWindow),
586 // and we need to add one here
587 if (!instance && g_type_is_a(gtype, G_TYPE_INITIALLY_UNOWNED))
588 g_object_ref_sink(gobject_);
589 // mark this as associated wrapper object as retrieved by .instance()
590 g_object_set_qdata_full(obj, object_data_quark(), this, destroy_notify);
591 }
592
593 // C++ side construction
594 // always (try to) register type and create instance
595 template<typename SubClass>
596 void register_setup(GType parent, const gi::cstring_v klassname,
597 const ClassInitNode *node,
598 const repository::GObject::construct_params &params,
599 const properties &props, const signals &sigs, custom_inits_t custom_inits,
600 gpointer instance = nullptr, std::nullptr_t = nullptr)
601 {
602 // sort-of internal prefixed klassname
603 auto custom_name = std::string(CLASS_PREFIX) + canonical_name(klassname);
604 auto gtype =
605 register_type(parent, custom_name, node, props, sigs, custom_inits);
606 setup_instance(gtype, params, instance);
607 }
608
609 template<typename SubClass>
610 static GObject *instance_constructor(GType type, guint n_construct_properties,
611 GObjectConstructParam *construct_properties)
612 {
613 // chain up, but we can skip other parent variations of this function
614 auto gtype = SubClass::baseclass_type::get_type_();
615 auto klass = G_OBJECT_CLASS(g_type_class_peek(gtype));
616 auto instance =
617 klass->constructor(type, n_construct_properties, construct_properties);
618
619 g_assert(instance);
620 // there should be no C++ side yet
621 // as we chain up past any possible C++ parent
622 g_assert(!ObjectClass::instance(instance));
623
624 // handle C++ setup
625 auto floating = g_object_is_floating(instance);
626 // avoid inadvertent sink
627 InitData id{0};
628 id.instance = gi::wrap((GObject *)g_object_ref(instance), transfer_full);
629 #if GI_CONFIG_EXCEPTIONS
630 try {
631 #endif
632 auto self = new SubClass(id);
633 // sanity check on ref
634 if (floating && !g_object_is_floating(instance)) {
635 g_warning("%s constructor sinks instance", typeid(SubClass).name());
636 // try to unsink if it seems safe and applicable
637 auto obj = (GObject *)instance;
638 // theoretically not MT safe, but worse things can happen otherwise
639 // whoever (some wrapper?) un-floated the object presumably intended
640 // to take a (real) ref/ownership, so let's arrange for that here
641 // and restore the original floating situation
642 g_warning("re-floating instance and converting to ref");
643 g_object_force_floating(obj);
644 g_object_ref(obj);
645 }
646 (void)self;
647 // self->setup is essentially run below at bottom of constructor chain)
648 // this will then assign ownership of self to instance
649 g_assert(self->gobj_() == (gpointer)instance);
650 #if GI_CONFIG_EXCEPTIONS
651 } catch (const std::exception &exc) {
652 // bad things will happen
653 report_exception(exc);
654 g_critical("constructor failed in instance_init");
655 }
656 #endif
657
658 return instance;
659 }
660
661 // C-side construction
662 // either register type, or finish setup of an instance (triggered on C side_
663 template<typename SubClass>
664 void register_setup(GType parent, const gi::cstring_v klassname,
665 const ClassInitNode *node,
666 const repository::GObject::construct_params &params,
667 const properties &props, const signals &sigs, custom_inits_t custom_inits,
668 gpointer instance = nullptr, const InitData *id = {})
669 {
670 g_assert(id);
671 g_assert(!instance);
672 // no real instance, so used for type registration purpose
673 if (!id->instance) {
674 // these parts are not applicable
675 (void)instance;
676 (void)params;
677 g_assert(!instance);
678 g_assert(params.empty());
679 // we have our own custom init, which creates the cpp object
680 // so the latter's constructor serves as custom init
681 // custom_inits.custom_init = instance_init<SubClass>;
682 custom_inits.constructor = instance_constructor<SubClass>;
683 // there is no gobject_ instance
684 // make sure to track type for subsequent signal and property registration
685 gtype_ =
686 register_type(parent, klassname, node, props, sigs, custom_inits);
687 g_assert(gtype_);
688 } else {
689 // so this is a new instance as created by instance_init
690 // ensure instance association here at the end of constructor chain
691 // so it is that way for the sequel of the subclass constructor
692 // (and redundant signal and property registration)
693 instance = id->instance.gobj_();
694 setup_instance(G_OBJECT_TYPE(instance), {}, instance);
695 }
696 }
697
698 static void destroy_notify(gpointer data)
699 {
700 ObjectClass *impl = (ObjectClass *)data;
701 // sever link with object instance
702 impl->gobject_ = nullptr;
703 delete impl;
704 }
705
706 protected:
707 template<typename SubClass>
708 static custom_inits_t make_custom_inits()
709 {
710 return {GClassInitFunc(custom_class_init<SubClass>::value),
711 GInstanceInitFunc(custom_instance_init<SubClass>::value)};
712 }
713
714 ObjectClass(GType parent, const gi::cstring_v klassname,
715 const ClassInitNode &node,
716 const repository::GObject::construct_params &params,
717 const properties &props)
718 {
719 register_setup<void>(
720 parent, klassname, &node, params, props, {}, {}, nullptr, nullptr);
721 }
722
723 template<typename SubClass, typename InitData>
724 ObjectClass(const SubClass *, GType parent, const gi::cstring_v klassname,
725 const ClassInitNode &node,
726 const repository::GObject::construct_params &params,
727 const properties &props, gpointer instance, InitData id)
728 {
729 register_setup<SubClass>(parent, klassname, &node, params, props, {},
730 make_custom_inits<SubClass>(), instance, id);
731 }
732
733 template<typename SubClass>
734 ObjectClass(const SubClass *, const gi::cstring_v klassname, GType base,
735 const ObjectClass::ClassInitNode &node, const interface_inits_t &itfs,
736 const properties &props, const signals &sigs)
737 {
738 this->itfs = itfs;
739 auto id = InitData{0};
740 register_setup<SubClass>(base, klassname, &node, {}, props, sigs,
741 make_custom_inits<SubClass>(), nullptr, &id);
742 }
743
744 ~ObjectClass()
745 {
746 // object destruction should typically be initiated from the
747 // associated object instance based on refcount,
748 // and so pass through destroy_notify, in which case no more gobject_
749 // but it could come here first for a stack based custom object or alike
750 if (gobject_) {
751 // corresponding object should not have outstanding refs out there
752 // not good otherwise, and why it should not be destructed this way
753 if (gobject_->ref_count != 1)
754 g_error("destroying object with outstanding object refs");
755 // NOTE the unref might still trigger vmethod calls,
756 // but destruction already happened down to this level,
757 // so derived cast and vmethod call no longer possible
758 // so sever link anyway to make that clear
759 g_object_steal_qdata(gobject_, object_data_quark());
760 g_object_unref(gobject_);
761 }
762 }
763
764 public:
765 ObjectClass(const std::type_info &ti,
766 const repository::GObject::construct_params &params = {},
767 const properties &props = {})
768 {
769 register_setup<void>(instance_type::get_type_(), ti.name(), nullptr, params,
770 props, {}, {}, nullptr, nullptr);
771 }
772
773 template<typename SubClass, typename InitData = std::nullptr_t>
774 ObjectClass(const SubClass *,
775 const repository::GObject::construct_params &params = {},
776 const properties &props = {}, gpointer instance = nullptr,
777 const gi::cstring_v klassname = nullptr, InitData id = nullptr)
778 {
779 const auto &ti = typeid(SubClass);
780 register_setup<SubClass>(instance_type::get_type_(),
781 klass_type_name(ti, klassname), nullptr, params, props, {},
782 make_custom_inits<SubClass>(), instance, id);
783 }
784
785 operator Object() { return gi::wrap(gobject_, transfer_none); }
786
787 GObject *gobj_() { return gobject_; }
788
789 GType gobj_klass_type()
790 {
791 // there should almost always be an object instance
792 // except during initial registration of c-first style
793 return gobject_ ? G_OBJECT_TYPE(gobject_) : gtype_;
794 }
795
796 GObjectClass *gobj_klass()
797 {
798 return (GObjectClass *)g_type_class_peek(gobj_klass_type());
799 }
800
801 static ObjectClass *instance(GObject *gobject)
802 {
803 return (ObjectClass *)g_object_get_qdata(gobject, object_data_quark());
804 }
805
806 private:
807 template<typename T>
808 friend GType register_type();
809
810 template<typename T>
811 static GType register_type_()
812 {
813 // check if the class has defined a get_type_()
814 // rather than nifty compile-time checks, simply use runtme
815 auto btype = T::baseclass_type::get_type_();
816 auto gtype = T::get_type_();
817 if (gtype == btype) {
818 // so nothing happened, use constructor to register
819 // instantiate dummy instance that registers type
820 gtype = (T{InitData{0}}).gobj_klass_type();
821 }
822 return gtype;
823 }
824 };
825
826 // interfaces need to go left; constructors need to run first (to request
827 // interface) class constructor deals with class_init last
828 template<typename ClassDef, typename BaseClass, typename... Interfaces>
829 class ClassTemplate : public ClassDef, public Interfaces..., public BaseClass
830 {
831 typedef typename ClassDef::instance_type::BaseObjectType *c_type;
832 typedef typename ClassDef::class_type class_type_t;
833 typedef typename ClassDef::instance_type instance_type_t;
834
835 // make private
836 using ClassDef::class_init;
837
838 protected:
839 class_type_t *get_struct_()
840 {
841 return (class_type_t *)g_type_class_peek(this->base_gtype());
842 }
843
844 c_type gobj_() { return (c_type)this->gobject_; }
845
846 // constructor to be used by custom subclass
847 [[deprecated]] ClassTemplate(const std::type_info &ti,
848 const repository::GObject::construct_params &params = {},
849 const properties &props = {})
850 : Interfaces(instance_type_t::get_type_())...,
851 BaseClass(instance_type_t::get_type_(), ti.name(),
852 {&ClassDef::class_init, nullptr, nullptr}, params, props)
853 {}
854
855 // constructor for inner inheritance chain
856 [[deprecated]] ClassTemplate(GType base, const gi::cstring_v klassname,
857 const ObjectClass::ClassInitNode &node,
858 const repository::GObject::construct_params &params,
859 const properties &props)
860 : Interfaces(instance_type_t::get_type_())...,
861 BaseClass(base, klassname, {&ClassDef::class_init, nullptr, &node},
862 params, props)
863 {}
864
865 // as above, new style
866 // constructor to be used by custom subclass
867 template<typename SubClass, typename InitData = std::nullptr_t>
868 ClassTemplate(const SubClass *sub,
869 const repository::GObject::construct_params &params = {},
870 const properties &props = {}, gpointer instance = nullptr,
871 const gi::cstring_v klassname = nullptr, InitData id = nullptr)
872 : Interfaces(instance_type_t::get_type_(),
873 gpointer(make_type_init_data<Interfaces, SubClass>()))...,
874 BaseClass(sub, instance_type_t::get_type_(),
875 klass_type_name(typeid(SubClass), klassname),
876 {&ClassDef::class_init, make_type_init_data<ClassDef, SubClass>(),
877 nullptr},
878 params, props, instance, id)
879 {}
880
881 // constructor for inner inheritance chain
882 template<typename SubClass, typename InitData = std::nullptr_t>
883 ClassTemplate(const SubClass *sub, GType base, const gi::cstring_v klassname,
884 const ObjectClass::ClassInitNode &node,
885 const repository::GObject::construct_params &params,
886 const properties &props, gpointer instance = nullptr,
887 InitData id = nullptr)
888 : Interfaces(instance_type_t::get_type_(),
889 gpointer(make_type_init_data<Interfaces, SubClass>()))...,
890 BaseClass(sub, base, klassname,
891 {&ClassDef::class_init, make_type_init_data<ClassDef, SubClass>(),
892 &node},
893 params, props, instance, id)
894 {}
895
896 // constructor used in inner inheritance chain for registration collection
897 template<typename SubClass>
898 ClassTemplate(const SubClass *sub, const gi::cstring_v klassname, GType base,
899 const ObjectClass::ClassInitNode &node,
900 const typename ClassTemplate::interface_inits_t &itfs,
901 const properties &props, const signals &sigs)
902 : Interfaces(instance_type_t::get_type_(),
903 gpointer(make_type_init_data<Interfaces, SubClass>()))...,
904 BaseClass(sub, klassname, base,
905 {&ClassDef::class_init, make_type_init_data<ClassDef, SubClass>(),
906 &node},
907 itfs, props, sigs)
908 {}
909
910 public:
911 class_type_t *gobj_klass() { return (class_type_t *)BaseClass::gobj_klass(); }
912
913 // repeat to disambiguate
914 typedef typename ClassDef::instance_type instance_type;
915
916 // access to regular object side
917 instance_type_t object_()
918 {
919 auto obj = this->gobject_ ? g_object_ref(this->gobject_) : nullptr;
920 return gi::wrap(
921 (typename instance_type_t::BaseObjectType *)(obj), gi::transfer_full);
922 }
923 };
924
925 // NOTE as the impl and regular object side are both inherited here,
926 // ambiguity might not only result from inheriting multiple interfaces,
927 // but also between either of these sides
928 // as such, no operator cast is added on the impl side
929 // instead, use the object_() member to pass to/through regular side
930 template<typename ObjectT, typename ClassT>
931 class ObjectImpl : public ObjectT, public ClassT
932 {
933 public:
934 typedef typename ClassT::instance_type baseclass_type;
935 using ObjectT::gobj_;
936
937 protected:
938 [[deprecated]] ObjectImpl(const std::type_info &ti,
939 const repository::GObject::construct_params &params =
940 repository::GObject::construct_params{},
941 const properties &props = properties{})
942 : ClassT(ti, params, props)
943 { // link object ptrs (untracked by ObjectBase)
944 this->data_ = this->gobject_;
945 }
946
947 // NOTE only 1 gtype will be registered,
948 // so all (subclass) constructors should specify consistent/same data
949 template<typename SubClass>
950 ObjectImpl(const SubClass *sub,
951 const repository::GObject::construct_params &params =
952 repository::GObject::construct_params{},
953 const properties &props = properties{})
954 : ClassT(sub, params, props)
955 { // link object ptrs (untracked by ObjectBase)
956 this->data_ = this->gobject_;
957 }
958
959 // special advanced case (for internal/override use) by custom subclass
960 // where constructed instance is associated with provided object instance
961 // (rather than the latter created as part of construction, as usual)
962 // if klassname KlassName is specified,
963 // registered typename is GIOBJECT__KlassName
964 // CAUTION the approach below is more likely applicable
965 template<typename SubClass>
966 ObjectImpl(ObjectT instance, const SubClass *sub,
967 const gi::cstring_v klassname = nullptr,
968 const repository::GObject::construct_params &params =
969 repository::GObject::construct_params{},
970 const properties &props = properties{})
971 : ClassT(sub, params, props, instance.gobj_(), klassname)
972 { // link object ptrs (untracked by ObjectBase)
973 this->data_ = this->gobject_;
974 }
975
976 // this will either;
977 // + register an object GType with an instance_init that
978 // new()'s a corresponding cpp object (and associates suitably)
979 // so, it can be safely created based on GType (e.g. by some C-factory)
980 // (InitData is essentially empty in this case,
981 // and the cpp ObjectImpl instance is a transient dummy)
982 // + construct instance invoked as part of the aforementioned new()
983 // (InitData then holds C object instance)
984 // registered type is klassname (as-is)
985 template<typename SubClass>
986 ObjectImpl(const SubClass *sub, const ObjectClass::InitData &id,
987 const gi::cstring_v klassname = {},
988 const properties &props = properties{})
989 : ClassT(sub, {}, props, nullptr, klassname, &id)
990 { // should have a name if this is used to register a type
991 g_return_if_fail(id || !klassname.empty());
992 // link object ptrs (untracked by ObjectBase)
993 this->data_ = this->gobject_;
994 }
995
996 ~ObjectImpl()
997 { // disconnect (avoid ObjectBase management)
998 this->data_ = nullptr;
999 }
1000
1001 // registers a type (instead of using that part of the constructor above)
1002 // if parent is 0, then it defaults to the type of the immediate parent
1003 // (so it should only be specified if subclass'ing a subclass)
1004 // itfs: use {I::interface_init_data(), ...} for *immediate* parents I,
1005 // *not* parent interfaces of parents
1006 // props, signals: use succinct list-initialization (as used elsewhere)
1007 template<typename SubClass>
1008 static GType register_type_(const gi::cstring_v klassname, GType parent,
1009 const typename ClassT::interface_inits_t &itfs,
1010 const properties_init &props, const signals_init &sigs)
1011 {
1012 // collect all data using constructor chain and register type
1013 // MT-safe according to C++11 specs
1014 static GType gtype =
1015 ObjectImpl((SubClass *)nullptr, klassname, parent, itfs, props, sigs)
1016 .gobj_klass_type();
1017 return gtype;
1018 }
1019
1020 private:
1021 // circumvent protected constructors/destructors
1022 template<typename SubClass>
1023 ObjectImpl(const SubClass *sub, const gi::cstring_v klassname, GType parent,
1024 const typename ClassT::interface_inits_t &itfs,
1025 const properties_init &props, const signals_init &sigs)
1026 : ClassT(sub, klassname, parent ? parent : baseclass_type::get_type_(),
1027 {nullptr, nullptr, nullptr}, itfs, props, sigs)
1028 {}
1029 };
1030
1031 // wrapper helper to call virtual method
1032 // used in implementation, so we can casually use types in default argument
1033 template<typename C, typename T, typename RetTransfer,
1034 typename ArgTransfers = void,
1035 typename CSig = typename map_cpp_function<T,
1036 typename std::conditional<std::is_null_pointer<RetTransfer>::value, T,
1037 void>::type>::type>
1038 struct method_wrapper;
1039
1040 template<typename C, typename R, typename... Args, typename RetTransfer,
1041 typename... Transfers, typename CR, typename... CArgs>
1042 struct method_wrapper<C, R (*)(Args...), RetTransfer, std::tuple<Transfers...>,
1043 CR(CArgs...)>
1044 {
1045 private:
1046 typedef R (C::*member_type)(Args...);
1047
1048 struct caller_data
1049 {
1050 C *this_;
1051 const member_type m;
1052 };
1053 static R caller(Args &&...args, void *user_data)
1054 {
1055 auto d = (caller_data *)user_data;
1056 return ((d->this_)->*(d->m))(std::forward<Args>(args)...);
1057 }
1058
1059 public:
1060 template<member_type m>
1061 static CR wrapper(
1062 typename traits::ctype<typename C::instance_type>::type p, CArgs... args)
1063 {
1064 ObjectClass *oc = ObjectClass::instance((GObject *)p);
1065 C *c = dynamic_cast<C *>(oc);
1066 if (!oc) {
1067 // connection already severed by heap destruction
1068 // use refptr instead of stack allocation if this is a problem
1069 g_error("missing object");
1070 } else if (!c) {
1071 // on our way to crash anyway
1072 g_error("wrong object type");
1073 }
1074 caller_data d{c, m};
1075 return transform_caller<R(Args...), RetTransfer, std::tuple<Transfers...>,
1076 CR(CArgs...)>::wrapper(args..., caller, &d);
1077 }
1078 };
1079
1080 // simplified special case for plain/raw fallback with no wrapping/transfer
1081 // (pick std::nullptr_t for specialization to represent absence of transfer)
1082 template<typename C, typename R, typename... Args>
1083 struct method_wrapper<C, R (*)(Args...), std::nullptr_t>
1084 {
1085 private:
1086 typedef R (C::*member_type)(Args...);
1087
1088 public:
1089 template<member_type m>
1090 static R wrapper(
1091 typename traits::ctype<typename C::instance_type>::type p, Args... args)
1092 {
1093 ObjectClass *oc = ObjectClass::instance((GObject *)p);
1094 C *c = dynamic_cast<C *>(oc);
1095 if (!oc) {
1096 // connection already severed by heap destruction
1097 // use refptr instead of stack allocation if this is a problem
1098 g_error("missing object");
1099 } else if (!c) {
1100 // on our way to crash anyway
1101 g_error("wrong object type");
1102 }
1103 return ((c)->*(m))(std::forward<Args>(args)...);
1104 }
1105 };
1106
1107 //// property handling ////
1108
1109 class PropertyBase
1110 {
1111 typedef PropertyBase self_type;
1112
1113 // subclass handles this
1114 virtual void set_property(const GValue *value) = 0;
1115 virtual void get_property(GValue *value) = 0;
1116
1117 static GQuark get_instance_quark(guint prop_id)
1118 {
1119 auto str = std::string("GI__") +
1120 std::to_string((uintptr_t)(&class_init)) + '_' +
1121 std::to_string(prop_id);
1122 return g_quark_from_string(str.c_str());
1123 }
1124
1125 static PropertyBase *get_instance(
1126 GObject *object, GParamSpec *pspec, guint prop_id)
1127 {
1128 auto impl = ObjectClass::instance(object);
1129 auto poffset = g_param_spec_get_qdata(pspec, get_instance_quark(prop_id));
1130 return poffset ? (PropertyBase *)((char *)impl + GPOINTER_TO_INT(poffset))
1131 : nullptr;
1132 }
1133
1134 static void get_property(
1135 GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
1136 {
1137 auto prop = get_instance(object, pspec, prop_id);
1138 if (prop) {
1139 prop->get_property(value);
1140 } else {
1141 G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
1142 }
1143 }
1144
1145 static void set_property(
1146 GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
1147 {
1148 auto prop = get_instance(object, pspec, prop_id);
1149 if (prop) {
1150 prop->set_property(value);
1151 } else {
1152 G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
1153 }
1154 }
1155
1156 protected:
1157 static GQuark get_prop_quark(const char *name)
1158 {
1159 auto str = std::string("GI__") + name;
1160 return g_quark_from_string(str.c_str());
1161 }
1162
1163 public:
1164 static void install_property(ObjectClass *impl, GObjectClass *klass,
1165 self_type *self, ParamSpec pspec, const gi::cstring_v name = "")
1166 {
1167 g_return_if_fail(impl);
1168 g_return_if_fail(klass);
1169 // need at least 1 parameter
1170 g_return_if_fail(pspec || name.size());
1171
1172 // identify any property tracked by this PropertyBase code
1173 // (may or may not be unique process-wise)
1174 static guint prop_id;
1175
1176 auto pname = name;
1177 if (pspec) {
1178 // mind transfer full
1179 g_object_class_install_property(klass, ++prop_id, pspec.gobj_copy_());
1180 // normalize name
1181 pname = pspec.name_();
1182 } else {
1183 g_object_class_override_property(klass, ++prop_id, name.c_str());
1184 }
1185
1186 // mark property installed on this klass/type (by whatever code path)
1187 // sadly, in case of overridden properties,
1188 // glib does not expose sufficient info on whether it is already further up
1189 // or the override that we may be trying to add to this/our class
1190 // so, setup some parallel tracking using qdata
1191 auto gtype = G_OBJECT_CLASS_TYPE(klass);
1192 g_type_set_qdata(
1193 gtype, get_prop_quark(pname.c_str()), GINT_TO_POINTER(prop_id));
1194
1195 // self may be absent if only registering type
1196 if (self) {
1197 install_property_offset(impl, klass, self, pname, prop_id);
1198 }
1199 }
1200
1201 static void install_property_offset(ObjectClass *impl, GObjectClass *klass,
1202 self_type *self, const gi::cstring_v name, guint prop_id)
1203 {
1204 g_return_if_fail(self);
1205
1206 // add metadata to pspec to retrieve upon set/get
1207 // an overridden one will be passed to get/set
1208 // (and returned by find as well)
1209 auto gpspec = g_object_class_find_property(klass, name.c_str());
1210 g_assert(gpspec);
1211 auto quark = get_instance_quark(prop_id);
1212 // NOTE no race/issue if multiple threads set this (to same value)
1213 // (internal locks are used by glib)
1214 if (!g_param_spec_get_qdata(gpspec, quark)) {
1215 auto offset = ((char *)self - (char *)impl);
1216 g_param_spec_set_qdata(gpspec, quark, GINT_TO_POINTER(offset));
1217 }
1218 }
1219
1220 virtual ~PropertyBase() {}
1221
1222 static void class_init(
1223 ObjectClass *impl, gpointer g_class, gpointer class_data)
1224 {
1225 auto klass = (GObjectClass *)g_class;
1226 auto props = (properties *)class_data;
1227
1228 klass->get_property = get_property;
1229 klass->set_property = set_property;
1230
1231 // need to add override properties at this point
1232 // (before creation of any instance or class struct)
1233 for (auto &&e : *props)
1234 install_property(impl, klass, e.second.first, e.second.second, e.first);
1235 }
1236 };
1237
1238 inline void
1239 class_init_props_sigs(
1240 ObjectClass *impl, gpointer g_class, gpointer props, gpointer _sigs)
1241 {
1242 g_return_if_fail(g_class);
1243
1244 if (props)
1245 PropertyBase::class_init(impl, g_class, props);
1246
1247 // handle signals right here
1248 if (_sigs) {
1249 auto sigs = (signals *)_sigs;
1250 for (auto &sig : *sigs) {
1251 auto gtype = G_OBJECT_CLASS_TYPE(g_class);
1252 g_signal_newv(sig.name.c_str(), gtype, (GSignalFlags)sig.flags, nullptr,
1253 nullptr, nullptr, nullptr, sig.ret_type, sig.types.size(),
1254 sig.types.data());
1255 }
1256 }
1257 }
1258
1259 template<typename T>
1260 class property : protected property_proxy<T>, public PropertyBase
1261 {
1262 T val_;
1263
1264 void add_property(ObjectClass *impl, gi::cstring_v name)
1265 {
1266 auto pspec = Object::find_property(impl->gobj_klass_type(), name);
1267 // could have been defined already upon prior object creation
1268 if (pspec) {
1269 this->pspec_ = pspec;
1270 // normalize name
1271 name = pspec.name_();
1272 // could be defined by a superclass
1273 // or already added to this class by prior instance
1274 auto gtype = G_OBJECT_CLASS_TYPE(impl->gobj_klass());
1275 if (auto pd = g_type_get_qdata(gtype, get_prop_quark(name.c_str()))) {
1276 install_property_offset(
1277 impl, impl->gobj_klass(), this, name, GPOINTER_TO_INT(pd));
1278 } else {
1279 install_property(impl, impl->gobj_klass(), this, nullptr, name);
1280 }
1281 } else {
1282 pspec = this->pspec_;
1283 install_property(impl, impl->gobj_klass(), this, pspec);
1284 }
1285 // set value to default param value
1286 Value value;
1287 value.init<T>();
1288 g_param_value_set_default(pspec.gobj_(), &value);
1289 val_ = detail::get_value<T>(&value);
1290 // avoid circular ref loop
1291 if (this->object_)
1292 g_object_unref(this->object_.gobj_());
1293 }
1294
1295 protected:
1296 void set_property(const GValue *value) override
1297 {
1298 val_ = detail::get_value<T>(value);
1299 }
1300
1301 void get_property(GValue *value) override { detail::set_value(value, val_); }
1302
1303 public:
1304 template<typename... Args,
1305 typename std::enable_if<sizeof...(Args) != 1>::type * = nullptr>
1306 property(ObjectClass *impl, Args &&...args)
1307 : property_proxy<T>(
1308 (Object)(*impl), ParamSpec::new_<T>(std::forward<Args>(args)...))
1309 {
1310 add_property(impl, this->pspec_.get_name());
1311 }
1312
1313 property(ObjectClass *impl, const gi::cstring_v name)
1314 : property_proxy<T>((Object)(*impl), ParamSpec())
1315 {
1316 add_property(impl, name);
1317 }
1318
1319 ~property()
1320 {
1321 // clear link
1322 this->object_.release_();
1323 }
1324
1325 void notify()
1326 {
1327 g_object_notify_by_pspec(this->object_.gobj_(), this->pspec_.gobj_());
1328 }
1329
1330 PropertyBase &operator=(T value)
1331 {
1332 val_ = value;
1333 notify();
1334 return *this;
1335 }
1336
1337 void set_value(T value, bool _notify = true)
1338 {
1339 val_ = value;
1340 if (_notify)
1341 notify();
1342 }
1343
1344 T get_value() const { return val_; }
1345
1346 operator T() const { return val_; }
1347
1348 property_proxy<T> get_proxy() const { return *this; }
1349 };
1350
1351 template<typename T>
1352 class property_read : public property<T>
1353 {
1354 public:
1355 template<typename... Args>
1356 property_read(ObjectClass *impl, Args &&...args)
1357 : property<T>(
1358 impl, std::forward<Args>(args)..., ParamFlags(G_PARAM_READABLE))
1359 {}
1360
1361 property_proxy_read<T> get_proxy() const
1362 {
1363 return {this->object_, this->pspec_};
1364 }
1365 };
1366
1367 template<typename T>
1368 class property_write : public property<T>
1369 {
1370 public:
1371 template<typename... Args>
1372 property_write(ObjectClass *impl, Args &&...args)
1373 : property<T>(
1374 impl, std::forward<Args>(args)..., ParamFlags(G_PARAM_WRITABLE))
1375 {}
1376
1377 property_proxy_write<T> get_proxy() const
1378 {
1379 return {this->object_, this->pspec_};
1380 }
1381 };
1382
1383 //// signal handling ////
1384
1385 template<typename R, typename Instance, typename... Args, typename Base>
1386 class signal<R(Instance, Args...), Base>
1387 : public signal_proxy<R(Instance, Args...)>
1388 {
1389 typedef signal_proxy<R(Instance, Args...)> super;
1390
1391 static guint new_(const gi::cstring_v name, GType itype, SignalFlags flags)
1392 {
1393 // collect array of types
1394 GType types[] = {traits::gtype<Args>::get_type()...};
1395 const int nparams = sizeof...(Args);
1396 const GType ret_type = traits::gtype<R>::get_type();
1397 // TODO accumulator
1398 return g_signal_newv(name.c_str(), itype, (GSignalFlags)flags, nullptr,
1399 nullptr, nullptr, nullptr, ret_type, nparams, types);
1400 }
1401
1402 public:
1403 signal(ObjectClass *owner, const gi::cstring_v name,
1404 SignalFlags flags = (SignalFlags)0)
1405 // do not take an extra ref;
1406 // avoid ref loop and accidental sink of floating ref
1407 : super(gi::wrap(owner->gobj_(), transfer_full), name)
1408 {
1409 const GType itype = owner->gobj_klass_type();
1410 if (!g_signal_lookup(name.c_str(), itype))
1411 new_(name, itype, flags);
1412 }
1413
1414 ~signal()
1415 {
1416 // clear link (since no real ref was taken at construction)
1417 this->object_.release_();
1418 }
1419 };
1420
1421 template<typename T>
1422 struct ObjectDeleter
1423 {
1424 void operator()(T *ob)
1425 {
1426 if (ob->gobj_())
1427 g_object_unref(ob->gobj_());
1428 }
1429 };
1430
1431 template<typename T>
1432 class ref_ptr : public std::unique_ptr<T, ObjectDeleter<T>>
1433 {
1434 typedef std::unique_ptr<T, ObjectDeleter<T>> super;
1435 typedef typename T::baseclass_type baseclass_type;
1436
1437 public:
1438 ref_ptr(T *ptr = nullptr, bool own = true) : super(ptr)
1439 {
1440 if (ptr && !own)
1441 g_object_ref(ptr->gobj_());
1442 }
1443
1444 ref_ptr(ref_ptr &&other) = default;
1445 ref_ptr(const ref_ptr &other) : super(nullptr)
1446 {
1447 if (other)
1448 g_object_ref(other->gobj_());
1449 this->reset(other.get());
1450 }
1451
1452 ref_ptr &operator=(ref_ptr &&other) = default;
1453 ref_ptr &operator=(const ref_ptr &other)
1454 {
1455 if (other && &other != this)
1456 g_object_ref(other->gobj_());
1457 this->reset(other.get());
1458 return *this;
1459 }
1460
1461 operator baseclass_type() { return *this->get(); }
1462 };
1463
1464 template<typename T, typename... Args>
1465 ref_ptr<T>
1466 make_ref_tagged(construct_cpp_t, Args &&...args)
1467 {
1468 // move ownership of ref acquired during creation
1469 return ref_ptr<T>(new T(std::forward<Args>(args)...));
1470 }
1471
1472 template<typename T, typename traits::if_valid_type<
1473 typename T::baseclass_type>::type * = nullptr>
1474 ref_ptr<T>
1475 ref_ptr_cast(Object ob)
1476 {
1477 if (ob) {
1478 ObjectClass *instance = ObjectClass::instance(ob.gobj_());
1479 if (instance) {
1480 auto obj = dynamic_cast<T *>(instance);
1481 if (obj) {
1482 // arrange to obtain an extra ref
1483 return ref_ptr<T>(obj, false);
1484 }
1485 }
1486 }
1487 return nullptr;
1488 }
1489
1490 // similar to a typical glib xyz_get_type
1491 // as both register the type (once) and return it (many times)
1492 template<typename T>
1493 GType
1494 register_type()
1495 {
1496 // C++11 standard specifies this should be MT-safe and occur only once
1497 // as such similar to the typical g_once in xyz_get_type
1498 static GType gtype = ObjectClass::register_type_<T>();
1499 return gtype;
1500 }
1501
1502 template<typename T, typename... Args>
1503 ref_ptr<T>
1504 make_ref_tagged(construct_c_t, Args &&...args)
1505 {
1506 auto gtype = register_type<T>();
1507 auto obj = Object::new_<::GObject *>(gtype, std::forward<Args>(args)...);
1508 return ref_ptr_cast<T>(obj);
1509 }
1510
1511 // Construct can be specified explicitly;
1512 // construct_c_t; also selected in auto case if supported,
1513 // Args specify construct properties (see also GObject::new_)
1514 // construct_cpp_t; Args are forwarded to any applicable constructor
1515 template<typename T, typename Construct = construct_auto_t, typename... Args>
1516 ref_ptr<T>
1517 make_ref(Args &&...args)
1518 {
1519 using tag_t = typename std::conditional<
1520 std::is_same<Construct, construct_auto_t>::value,
1521 typename std::conditional<
1522 std::is_constructible<T, ObjectClass::InitData>::value, construct_c_t,
1523 construct_cpp_t>::type,
1524 Construct>::type;
1525 return make_ref_tagged<T>(tag_t(), std::forward<Args>(args)...);
1526 }
1527
1528 } // namespace detail
1529
1530 // TODO impl namespace ??
1531
1532 using detail::property;
1533 using detail::property_read;
1534 using detail::property_write;
1535 using detail::signal;
1536
1537 using detail::make_ref;
1538 using detail::ref_ptr;
1539 using detail::ref_ptr_cast;
1540 using detail::register_type;
1541
1542 namespace repository
1543 {
1544 namespace GObject
1545 {
1546 namespace impl
1547 {
1548 // bring into namespaces as in code generation
1549
1550 namespace internal
1551 {
1552 using ObjectClass = detail::ObjectClass;
1553
1554 } // namespace internal
1555
1556 using ObjectImpl = detail::ObjectImpl<Object, detail::ObjectClass>;
1557
1558 } // namespace impl
1559
1560 } // namespace GObject
1561
1562 } // namespace repository
1563
1564 } // namespace gi
1565
1566 #endif // GI_OBJECTCLASS_HPP