Skip to content

Commit 9dad1c3

Browse files
authored
Port 'Menu' demo to Vala (#172)
1 parent 12fe3fc commit 9dad1c3

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

src/Menu/main.vala

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#! /usr/bin/env -S vala workbench.vala --pkg libadwaita-1
2+
3+
public void main () {
4+
var label = (Gtk.Label) workbench.builder.get_object ("label");
5+
6+
var text_group = new SimpleActionGroup ();
7+
label.insert_action_group ("text", text_group);
8+
9+
var text_state = new HashTable<string, Variant> (str_hash, str_equal);
10+
text_state.insert ("italic", false);
11+
text_state.insert ("bold", false);
12+
text_state.insert ("foreground", "green");
13+
14+
var italic_action = new SimpleAction.stateful ("italic", null, new Variant.boolean (false));
15+
italic_action.notify["state"].connect (() => {
16+
text_state.replace ("italic", italic_action.state.get_boolean ());
17+
label.attributes = (state_to_attr (text_state));
18+
});
19+
text_group.add_action (italic_action);
20+
21+
var bold_action = new SimpleAction.stateful ("bold", null, new Variant.boolean (false));
22+
bold_action.notify["state"].connect (() => {
23+
text_state.replace ("bold", bold_action.state.get_boolean ());
24+
label.attributes = (state_to_attr (text_state));
25+
});
26+
text_group.add_action (bold_action);
27+
28+
var color_action = new SimpleAction.stateful ("color", new VariantType ("s"), new Variant.string ("green"));
29+
color_action.notify["state"].connect (() => {
30+
text_state.replace ("foreground", color_action.state.get_string ());
31+
label.attributes = (state_to_attr (text_state));
32+
});
33+
text_group.add_action (color_action);
34+
}
35+
36+
// Helper function to create a PangoAttrList from text_state
37+
private Pango.AttrList state_to_attr (HashTable<string, Variant> state) {
38+
string attr_string = "";
39+
GenericArray<string> attrs = new GenericArray<string> ();
40+
41+
Variant? bold_variant = state.lookup ("bold");
42+
if (bold_variant != null && bold_variant.get_boolean ()) {
43+
attrs.add (@"0 -1 weight bold");
44+
}
45+
46+
Variant? italic_variant = state.lookup ("italic");
47+
if (italic_variant != null && italic_variant.get_boolean ()) {
48+
attrs.add (@"0 -1 style italic");
49+
}
50+
51+
string color = state.lookup ("foreground").get_string ();
52+
if (color != null) {
53+
attrs.add (@"0 -1 foreground $color");
54+
}
55+
56+
foreach (string arr_attrb in attrs) {
57+
attr_string += arr_attrb + ", ";
58+
}
59+
return Pango.AttrList.from_string (attr_string);
60+
}

0 commit comments

Comments
 (0)