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