Debian Codegraph @

examples/gtk.cpp

raw symbols SCIP
1 #ifndef USE_GI_MODULE
2 // no inline as the implementation is in another TU
3 // #define GI_INLINE 1
4 #include <gtk/gtk.hpp>
5 #else
6 // optional, but recommended if gi macros are used
7 #include <gi/gi_inc.hpp>
8 // we use some gtk macros
9 #include <gtk/gtk.h>
10 // import recursive module
11 import gi.repo.gtk.rec;
12 #endif
13
14 // adapt to API as needed
15 #if GTK_CHECK_VERSION(4, 0, 0)
16 #define GTK4 1
17 #endif
18
19 #include <fstream>
20 #include <iostream>
21 #include <tuple>
22 #include <vector>
23
24 namespace GLib = gi::repository::GLib;
25 namespace GObject_ = gi::repository::GObject;
26 namespace Gtk = gi::repository::Gtk;
27
28 static GLib::MainLoop loop;
29
30 #ifdef GI_CLASS_IMPL
31 // based on python-gtk3 example
32 // https://python-gtk-3-tutorial.readthedocs.io/en/latest/treeview.html
33
34 // list of tuples for each software,
35 // containing the software name, initial release, and main programming languages
36 const std::vector<std::tuple<std::string, int, std::string>> software_list{
37 std::make_tuple("Firefox", 2002, "C++"),
38 std::make_tuple("Eclipse", 2004, "Java"),
39 std::make_tuple("Pitivi", 2004, "Python"),
40 std::make_tuple("Netbeans", 1996, "Java"),
41 std::make_tuple("Chrome", 2008, "C++"),
42 std::make_tuple("Filezilla", 2001, "C++"),
43 std::make_tuple("Bazaar", 2005, "Python"),
44 std::make_tuple("Git", 2005, "C"),
45 std::make_tuple("Linux Kernel", 1991, "C"),
46 std::make_tuple("GCC", 1987, "C"),
47 std::make_tuple("Frostwire", 2004, "Java")};
48
49 class TreeViewFilterWindow : public Gtk::impl::WindowImpl
50 {
51 typedef TreeViewFilterWindow self_type;
52
53 Gtk::ListStore store_;
54 Gtk::TreeModelFilter language_filter_;
55 std::string current_filter_language_;
56
57 public:
58 TreeViewFilterWindow() : Gtk::impl::WindowImpl(this)
59 {
60 Gtk::Window &self = *(this);
61 self.set_title("TreeView filter demo");
62 #ifdef GTK4
63 #else
64 self.set_border_width(10);
65 #endif
66
67 // set up the grid in which elements are positioned
68 auto grid = Gtk::Grid::new_();
69 grid.set_column_homogeneous(true);
70 grid.set_row_homogeneous(true);
71 #ifdef GTK4
72 self.set_child(grid);
73 #if 0
74 // this could work, but the annotation for .load_from_data
75 // is too unstable across versions
76 { // migrate call above to CSS style
77 const char *css = "grid { margin: 10px; }";
78 auto provider = Gtk::CssProvider::new_();
79 provider.load_from_data((guint8 *)css, -1);
80 grid.get_style_context().add_provider(
81 provider, Gtk::STYLE_PROVIDER_PRIORITY_USER_);
82 }
83 #endif
84 #else
85 self.add(grid);
86 #endif
87
88 // create ListStore model
89 store_ = Gtk::ListStore::new_type_<std::string, int, std::string>();
90 for (auto &e : software_list) {
91 auto it = store_.append();
92 GObject_::Value cols[] = {std::get<0>(e), std::get<1>(e), std::get<2>(e)};
93 for (unsigned i = 0; i < G_N_ELEMENTS(cols); ++i) {
94 store_.set_value(it, i, cols[i]);
95 }
96 }
97
98 // create the filter, feeding it with the liststore model
99 auto treemodel = store_.interface_(gi::interface_tag<Gtk::TreeModel>());
100 language_filter_ =
101 gi::object_cast<Gtk::TreeModelFilter>(treemodel.filter_new(nullptr));
102 // set the filter function
103 language_filter_.set_visible_func(
104 gi::mem_fun(&self_type::language_filter_func, this));
105
106 // create the treeview, make it use the filter as a model, and add
107 // columns
108 auto treeview = Gtk::TreeView::new_with_model(language_filter_);
109 int i = 0;
110 for (auto &e : {"Software", "Release Year", "Programming Language"}) {
111 auto renderer = Gtk::CellRendererText::new_();
112 auto column = Gtk::TreeViewColumn::new_(e, renderer, {{"text", i}});
113 treeview.append_column(column);
114 ++i;
115 }
116
117 // create buttons to filter by programming language, and set up their
118 // events
119 std::vector<Gtk::Widget> buttons;
120 for (auto &prog_language : {"Java", "C", "C++", "Python", "None"}) {
121 auto button = Gtk::Button::new_with_label(prog_language);
122 buttons.push_back(button);
123 button.signal_clicked().connect(
124 gi::mem_fun(&self_type::on_selection_button_clicked, this));
125 }
126
127 // set up the layout;
128 // put the treeview in a scrollwindow, and the buttons in a row
129 auto scrollable_treelist = Gtk::ScrolledWindow::new_();
130 scrollable_treelist.set_vexpand(true);
131 grid.attach(scrollable_treelist, 0, 0, 8, 10);
132 grid.attach_next_to(
133 buttons[0], scrollable_treelist, Gtk::PositionType::BOTTOM_, 1, 1);
134 auto it = buttons.begin() + 1;
135 while (it != buttons.end()) {
136 grid.attach_next_to(*it, *(it - 1), Gtk::PositionType::RIGHT_, 1, 1);
137 ++it;
138 }
139 #ifdef GTK4
140 scrollable_treelist.set_child(treeview);
141 self.show();
142 #else
143 scrollable_treelist.add(treeview);
144 self.show_all();
145 #endif
146 }
147
148 bool language_filter_func(Gtk::TreeModel filter, Gtk::TreeIter_Ref it) const
149 {
150 if (current_filter_language_.empty() || current_filter_language_ == "None")
151 return true;
152 return current_filter_language_ ==
153 filter.get_value(it, 2).get_value<std::string>();
154 }
155
156 void on_selection_button_clicked(Gtk::Button button)
157 {
158 // set the current language filter to the button's label
159 current_filter_language_ = button.get_label();
160 std::cout << current_filter_language_ << " language selected!" << std::endl;
161 // update the filter, which updates in turn the view
162 language_filter_.refilter();
163 }
164 };
165
166 // other part based on gtkmm builder example
167 namespace Gio = gi::repository::Gio;
168
169 auto templ = R"|(
170 <interface>
171 <template class="FooWidget" parent="GtkBox">
172 <property name="orientation">GTK_ORIENTATION_HORIZONTAL</property>
173 <property name="spacing">4</property>
174 <child>
175 <object class="GtkButton" id="hello_button">
176 <property name="label">Hello World</property>
177 <signal name="clicked" handler="hello_button_clicked"/>
178 <signal name="clicked" handler="hello_button_clicked_object" object="label" swapped="no"/>
179 <signal name="clicked" handler="hello_button_clicked_object_swapped" object="label" swapped="yes"/>
180 </object>
181 </child>
182 <child>
183 <object class="GtkButton" id="goodbye_button">
184 <property name="label">Goodbye World</property>
185 </object>
186 </child>
187 <child>
188 <object class="GtkLabel" id="label">
189 <property name="label">Greetings World</property>
190 </object>
191 </child>
192 </template>
193 </interface>
194 )|";
195
196 auto templ_child = R"|(
197 <child>
198 <object class="FooWidget" id="foowidget1"/>
199 </child>
200 )|";
201
202 using WidgetTemplateHelper = Gtk::impl::WidgetTemplateHelper;
203
204 class FooWidget : public Gtk::impl::BoxImpl, public WidgetTemplateHelper
205 {
206 using self_type = FooWidget;
207
208 public:
209 static void custom_class_init(GtkBoxClass *klass, gpointer)
210 {
211 // this is similar to the C case
212 // plain C functions are used, as klass struct has no direct equivalent
213 auto wklass = GTK_WIDGET_CLASS(klass);
214 auto bytes = GLib::Bytes::new_static((const guint8 *)templ, strlen(templ));
215 gtk_widget_class_set_template(wklass, bytes.gobj_());
216 gtk_widget_class_bind_template_child_full(wklass, "hello_button", TRUE, 0);
217 // chain up
218 WidgetTemplateHelper::custom_class_init<gi::register_type<self_type>>(
219 klass, nullptr);
220 }
221
222 public:
223 Gtk::Button hello_;
224
225 void on_hello(Gtk::Button) { std::cout << "Hi" << std::endl; }
226
227 void on_hello_tail(Gtk::Button b, Gtk::Label l)
228 {
229 g_assert(l.gobj_type_() == GTK_TYPE_LABEL);
230 g_assert(b.gobj_type_() == GTK_TYPE_BUTTON);
231 std::cout << "Hi tail" << std::endl;
232 }
233
234 void on_hello_head(Gtk::Label l, Gtk::Button b)
235 {
236 g_assert(l.gobj_type_() == GTK_TYPE_LABEL);
237 g_assert(b.gobj_type_() == GTK_TYPE_BUTTON);
238 std::cout << "Hi head" << std::endl;
239 }
240
241 FooWidget(const InitData &id)
242 : Gtk::impl::BoxImpl(this, id, "FooWidget"),
243 WidgetTemplateHelper(object_())
244 {
245 // skip registration case
246 if (!id) {
247 // as we have defined a get_type_() below, that should not happen
248 g_assert_not_reached();
249 return;
250 }
251
252 // locate object
253 hello_ = gi::object_cast<Gtk::Button>(
254 get_template_child(gobj_type_(), "hello_button"));
255
256 // setup signal
257 // NOTE the "manual" signature here should suitably match
258 // (also considering object/swapped flags, etc)
259 auto ok = set_handler<void(Gtk::Button)>(
260 "hello_button_clicked", gi::mem_fun(&self_type::on_hello, this));
261 g_assert(ok);
262 ok = set_handler<void(Gtk::Button, Gtk::Label), ConnectObject::TAIL>(
263 "hello_button_clicked_object",
264 gi::mem_fun(&self_type::on_hello_tail, this));
265 g_assert(ok);
266 ok = set_handler<void(Gtk::Label, Gtk::Button), ConnectObject::HEAD>(
267 "hello_button_clicked_object_swapped",
268 gi::mem_fun(&self_type::on_hello_head, this));
269 g_assert(ok);
270 }
271
272 static GType get_type_()
273 {
274 return register_type_<FooWidget>("FooWidget", 0, {}, {}, {});
275 }
276 };
277
278 class ExampleWindow : public Gtk::impl::WindowImpl
279 {
280 using self_type = ExampleWindow;
281
282 public:
283 ExampleWindow(Gtk::Window base, Gtk::Builder builder)
284 : Gtk::impl::WindowImpl(base, this, "ExampleWindow")
285 // custom name parameter is optional, but can be provided if used in .ui
286 {
287 (void)builder;
288 setup();
289 }
290
291 // name parameter is required and specifies registered type as-is
292 // (so some proper namespace prefix is advisable in real case)
293 ExampleWindow(const InitData &id)
294 : Gtk::impl::WindowImpl(this, id, "ExampleWindow")
295 {
296 // skip registration case
297 if (id)
298 setup();
299 }
300
301 void setup()
302 {
303 auto actions = Gio::SimpleActionGroup::new_();
304 auto am = Gio::ActionMap(actions);
305 auto action = Gio::SimpleAction::new_("help");
306 action.signal_activate().connect(gi::mem_fun(&self_type::on_help, this));
307 am.add_action(action);
308 insert_action_group("win", actions);
309 }
310
311 void on_help(Gio::Action, GLib::Variant) { std::cout << "Help" << std::endl; }
312
313 // subclass_type == 0; UI specifies GtkWindow
314 // subclass_type < 0; UI specifies GIOBJECT__ExampleWindow
315 // in either cases above; manual C++ association is needed
316 // (uses first constructor)
317 // -> NOT recommended
318 // subclass_type > 0; UI specifies ExampleWindow;
319 // all is properly created by (C-side) instance construction
320 // (uses second constructor)
321 // -> recommended
322 // subclass_type > 1; also insert a FooWidget
323 // (also all created by C-side construction)
324 static Gtk::Window build(int subclass_type)
325 {
326 const char *UIFILE = G_STRINGIFY(EXAMPLES_DIR) "/gtk-builder.ui";
327 const char *WINID = "window1";
328
329 auto builder = Gtk::Builder::new_();
330 // if the subtype has additional functionality (e.g. method overrides)
331 // then builder should instantiate using that type,
332 // otherwise base type suffices
333 // NOTE in the former case, there is a "short time" that the GObject side
334 // exists without a corresponding C++ side, so any attempt to use the
335 // extended parts (e.g. method calls) will be unfortunate
336 if (subclass_type) {
337 std::string WINCLASS = "GtkWindow";
338 std::ifstream f(UIFILE, std::ios::binary);
339 std::string ui;
340 std::getline(f, ui, '\0');
341
342 auto index = ui.find(WINCLASS);
343 assert(index != ui.npos);
344 ui.replace(ui.begin() + index, ui.begin() + index + WINCLASS.size(),
345 subclass_type < 0 ? "GIOBJECT__ExampleWindow" : "ExampleWindow");
346 if (subclass_type > 1) {
347 // sprinkle a template instance
348 std::string MARKER = "<!-- INSERT -->";
349 index = ui.find(MARKER);
350 ui.replace(ui.begin() + index, ui.begin() + index + MARKER.size(),
351 templ_child);
352 // ensure type registered
353 gi::register_type<FooWidget>();
354 }
355 // now we got a UI file that references the subclass type
356 // ensure the latter is registered
357 if (subclass_type < 0) {
358 // use a temporary instance
359 gi::make_ref<ExampleWindow, gi::construct_cpp_t>(nullptr, builder);
360 } else {
361 // a new cleaner way
362 gi::register_type<ExampleWindow>();
363 }
364 builder.add_from_string(ui, -1);
365 } else {
366 builder.add_from_file(UIFILE);
367 }
368 if (false) {
369 // some compile checks
370 builder.get_object(WINID);
371 builder.get_object<Gtk::Window>(WINID);
372 }
373 if (subclass_type > 1) {
374 // verify proper C++ side setup
375 auto foo_obj =
376 builder.get_object<FooWidget::baseclass_type>("foowidget1");
377 assert(foo_obj);
378 auto foo = gi::ref_ptr_cast<FooWidget>(foo_obj);
379 assert(foo);
380 assert(foo->hello_);
381 }
382 // the special _derived may be needed to setup C++ side and associate
383 return subclass_type > 0 ? builder.get_object<Gtk::Window>(WINID)
384 : builder.get_object_derived<self_type>(WINID);
385 }
386 };
387 #endif // GI_CLASS_IMPL
388
389 int
390 main(int argc, char **argv)
391 {
392 #ifdef GTK4
393 (void)argc;
394 (void)argv;
395 gtk_init();
396 #else
397 gtk_init(&argc, &argv);
398 #endif
399
400 loop = GLib::MainLoop::new_();
401
402 // recommended general approach iso stack based
403 // too much vmethod calling which is not safe for plain case
404 Gtk::Window win;
405 #ifdef GI_CLASS_IMPL
406 // silly compile/link check
407 static_assert(gi::transfer_full.value == 1, "");
408 if (argc == gi::transfer_full.value) {
409 win = gi::make_ref<TreeViewFilterWindow>();
410 } else {
411 win = ExampleWindow::build(std::stoi(argv[1]));
412 }
413 // TODO auto-handle arg ignore ??
414 #ifdef GTK4
415 win.signal_close_request().connect([](Gtk::Window) {
416 loop.quit();
417 return true;
418 });
419 win.show();
420 #else
421 win.signal_destroy().connect([](Gtk::Widget) { loop.quit(); });
422 win.show_all();
423 #endif
424 #else // GI_CLASS_IMPL
425 (void)win;
426 #endif
427
428 loop.run();
429 }