如何在 gjs 中从 Gtk.Context 中搜索窗口按钮



我正在尝试从当前的gtk活动主题中提取窗口按钮,并将其渲染在gjs的开罗上下文中,以便在Gnome-Global-Menu(https://gitlab.com/lestcape/Gnome-Global-AppMenu(中使用。例如,我有一个代码用于提取关闭按钮。

this.actor = new St.DrawingArea();
this.actor.connect('repaint', Lang.bind(this, this._onRepaint));
_onRepaint: function(area) {
let cr = area.get_context();
let [width, height] = area.get_surface_size();
let provider = Gtk.CssProvider.get_default();
let path = new Gtk.WidgetPath();
let pos1 = path.append_type(Gtk.HeaderBar);
let pos2 = path.append_type(Gtk.Button);
path.iter_add_class(pos1, 'titlebar');
path.iter_add_class(pos2, 'titlebutton');
path.iter_add_class(pos2, 'close');
let context = new Gtk.StyleContext();
context.set_screen(Gdk.Screen.get_default());
context.set_path(path);
context.save();
context.set_state(Gtk.StateFlags.NORMAL);
Gtk.render_background(context, cr, 0, 0, width, height);
Gtk.render_frame(context, cr, 0, 0, width, height);
context.restore();
},

这是我的第一次接近,但它不起作用。我检测到 Ambiance 主题中的 css 是这样的:

.titlebar button.titlebutton.close {
border-color: #333333;
color: #323112;
-gtk-icon-shadow: 0 1px rgba(255, 255, 255, 0.25);
background-image: -gtk-scaled(url("assets/windowbutton-close.png"),
url("assets/windowbutton-close@2.png"),
url("assets/windowbutton-close@3.png"),
url("assets/windowbutton-close@4.png"));
}

生成我的代码的路径具有以下格式:

.titlebar GtkButton.titlebutton.close

发生这种情况是因为 gjs 中 Gtk.Button 的 GType 返回我 GtkButton 而不是按钮,就像主题中一样。因此,我创建了一个帮助程序类:

const GtkButton = new GObject.Class({
Name: 'button',
GTypeName: 'button',
Extends: Gtk.Button,
_init: function(params) {
this.parent(params);
},
});

然后代替:

let pos2 = path.append_type(Gtk.Button);

我补充:

let pos2 = path.append_type(GtkButton);

然后我的路径和 css 属性匹配,但在我的开罗上下文中也没有显示任何内容。绘图区域的宽度和高度是侏儒外壳面板的大小为27像素。

那么,这里缺少什么呢?

另一方面,如果我直接从 Gtk.widgets 获取我想要的上下文,那就是工作:

let headerWidget = new Gtk.HeaderBar();
let buttonWidget = new Gtk.Button();
let context = headerWidget.get_style_context();
context.add_class('titlebar');
headerWidget.add(buttonWidget);
context = buttonWidget.get_style_context();
context.add_class('titlebutton');
context.add_class('close');

使用最后一个代码实现的示例如下:https://gitlab.com/lestcape/metacity-buttons 和显示其工作的视频可以在此处查看:https://www.youtube.com/watch?v=7CnoMEM44Do&t=18s

CSS中元素的名称是"CSS name",而不是类名。您可以在类序言中设置 CSS 名称:

const GtkButton = new GObject.Class({
Name: 'button',
CssName: 'button',
Extends: Gtk.Button,
});

或者,在新式课程中,

const GtkButton = GObject.registerClass({
CssName: 'button',
}, class MyButton extends Gtk.Button {
});

最新更新