summaryrefslogtreecommitdiff
path: root/lang/gjs/src/gtk3/astalify.ts
blob: 9e6f022150dc40cfa0588903fc2b54e7f467a502 (plain)
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
import Astal from "gi://Astal?version=3.0"
import Gtk from "gi://Gtk?version=3.0"
import Gdk from "gi://Gdk?version=3.0"
import GObject from "gi://GObject"
import { execAsync } from "../process.js"
import Variable from "../variable.js"
import Binding, { kebabify, snakeify, type Connectable, type Subscribable } from "../binding.js"

export function mergeBindings(array: any[]) {
    function getValues(...args: any[]) {
        let i = 0
        return array.map(value => value instanceof Binding
            ? args[i++]
            : value,
        )
    }

    const bindings = array.filter(i => i instanceof Binding)

    if (bindings.length === 0)
        return array

    if (bindings.length === 1)
        return bindings[0].as(getValues)

    return Variable.derive(bindings, getValues)()
}

function setProp(obj: any, prop: string, value: any) {
    try {
        // the setter method has to be used because
        // array like properties are not bound correctly as props
        const setter = `set_${snakeify(prop)}`
        if (typeof obj[setter] === "function")
            return obj[setter](value)

        return (obj[prop] = value)
    }
    catch (error) {
        console.error(`could not set property "${prop}" on ${obj}:`, error)
    }
}

export default function astalify<
    C extends { new(...args: any[]): Gtk.Widget },
>(cls: C, clsName = cls.name) {
    class Widget extends cls {
        get css(): string { return Astal.widget_get_css(this) }
        set css(css: string) { Astal.widget_set_css(this, css) }
        get_css(): string { return this.css }
        set_css(css: string) { this.css = css }

        get className(): string { return Astal.widget_get_class_names(this).join(" ") }
        set className(className: string) { Astal.widget_set_class_names(this, className.split(/\s+/)) }
        get_class_name(): string { return this.className }
        set_class_name(className: string) { this.className = className }

        get cursor(): Cursor { return Astal.widget_get_cursor(this) as Cursor }
        set cursor(cursor: Cursor) { Astal.widget_set_cursor(this, cursor) }
        get_cursor(): Cursor { return this.cursor }
        set_cursor(cursor: Cursor) { this.cursor = cursor }

        get clickThrough(): boolean { return Astal.widget_get_click_through(this) }
        set clickThrough(clickThrough: boolean) { Astal.widget_set_click_through(this, clickThrough) }
        get_click_through(): boolean { return this.clickThrough }
        set_click_through(clickThrough: boolean) { this.clickThrough = clickThrough }

        declare private __no_implicit_destroy: boolean
        get noImplicitDestroy(): boolean { return this.__no_implicit_destroy }
        set noImplicitDestroy(value: boolean) { this.__no_implicit_destroy = value }

        set actionGroup([prefix, group]: ActionGroup) { this.insert_action_group(prefix, group) }
        set_action_group(actionGroup: ActionGroup) { this.actionGroup = actionGroup }

        _setChildren(children: Gtk.Widget[]) {
            children = children.flat(Infinity).map(ch => ch instanceof Gtk.Widget
                ? ch
                : new Gtk.Label({ visible: true, label: String(ch) }))

            // remove
            if (this instanceof Gtk.Bin) {
                const ch = this.get_child()
                if (ch)
                    this.remove(ch)
                if (ch && !children.includes(ch) && !this.noImplicitDestroy)
                    ch?.destroy()
            }
            else if (this instanceof Gtk.Container) {
                for (const ch of this.get_children()) {
                    this.remove(ch)
                    if (!children.includes(ch) && !this.noImplicitDestroy)
                        ch?.destroy()
                }
            }

            // TODO: add more container types
            if (this instanceof Astal.Box) {
                this.set_children(children)
            }

            else if (this instanceof Astal.Stack) {
                this.set_children(children)
            }

            else if (this instanceof Astal.CenterBox) {
                this.startWidget = children[0]
                this.centerWidget = children[1]
                this.endWidget = children[2]
            }

            else if (this instanceof Astal.Overlay) {
                const [child, ...overlays] = children
                this.set_child(child)
                this.set_overlays(overlays)
            }

            else if (this instanceof Gtk.Container) {
                for (const ch of children)
                    this.add(ch)
            }

            else {
                throw Error(`can not add children to ${this.constructor.name}, it is not a container widget`)
            }
        }

        toggleClassName(cn: string, cond = true) {
            Astal.widget_toggle_class_name(this, cn, cond)
        }

        hook(
            object: Connectable,
            signal: string,
            callback: (self: this, ...args: any[]) => void,
        ): this
        hook(
            object: Subscribable,
            callback: (self: this, ...args: any[]) => void,
        ): this
        hook(
            object: Connectable | Subscribable,
            signalOrCallback: string | ((self: this, ...args: any[]) => void),
            callback?: (self: this, ...args: any[]) => void,
        ) {
            if (typeof object.connect === "function" && callback) {
                const id = object.connect(signalOrCallback, (_: any, ...args: unknown[]) => {
                    callback(this, ...args)
                })
                this.connect("destroy", () => {
                    (object.disconnect as Connectable["disconnect"])(id)
                })
            }

            else if (typeof object.subscribe === "function" && typeof signalOrCallback === "function") {
                const unsub = object.subscribe((...args: unknown[]) => {
                    signalOrCallback(this, ...args)
                })
                this.connect("destroy", unsub)
            }

            return this
        }

        constructor(...params: any[]) {
            super()
            const [config] = params

            const { setup, child, children = [], ...props } = config
            props.visible ??= true

            // remove undefined values
            for (const [key, value] of Object.entries(props)) {
                if (value === undefined) {
                    delete props[key]
                }
            }

            if (child)
                children.unshift(child)

            // collect bindings
            const bindings = Object.keys(props).reduce((acc: any, prop) => {
                if (props[prop] instanceof Binding) {
                    const binding = props[prop]
                    delete props[prop]
                    return [...acc, [prop, binding]]
                }
                return acc
            }, [])

            // collect signal handlers
            const onHandlers = Object.keys(props).reduce((acc: any, key) => {
                if (key.startsWith("on")) {
                    const sig = kebabify(key).split("-").slice(1).join("-")
                    const handler = props[key]
                    delete props[key]
                    return [...acc, [sig, handler]]
                }
                return acc
            }, [])

            // set children
            const mergedChildren = mergeBindings(children.flat(Infinity))
            if (mergedChildren instanceof Binding) {
                this._setChildren(mergedChildren.get())
                this.connect("destroy", mergedChildren.subscribe((v) => {
                    this._setChildren(v)
                }))
            }
            else {
                if (mergedChildren.length > 0) {
                    this._setChildren(mergedChildren)
                }
            }

            // setup signal handlers
            for (const [signal, callback] of onHandlers) {
                if (typeof callback === "function") {
                    this.connect(signal, callback)
                }
                else {
                    this.connect(signal, () => execAsync(callback)
                        .then(print).catch(console.error))
                }
            }

            // setup bindings handlers
            for (const [prop, binding] of bindings) {
                if (prop === "child" || prop === "children") {
                    this.connect("destroy", binding.subscribe((v: any) => {
                        this._setChildren(v)
                    }))
                }
                this.connect("destroy", binding.subscribe((v: any) => {
                    setProp(this, prop, v)
                }))
                setProp(this, prop, binding.get())
            }

            Object.assign(this, props)
            setup?.(this)
        }
    }

    GObject.registerClass({
        GTypeName: `Astal_${clsName}`,
        Properties: {
            "class-name": GObject.ParamSpec.string(
                "class-name", "", "", GObject.ParamFlags.READWRITE, "",
            ),
            "css": GObject.ParamSpec.string(
                "css", "", "", GObject.ParamFlags.READWRITE, "",
            ),
            "cursor": GObject.ParamSpec.string(
                "cursor", "", "", GObject.ParamFlags.READWRITE, "default",
            ),
            "click-through": GObject.ParamSpec.boolean(
                "click-through", "", "", GObject.ParamFlags.READWRITE, false,
            ),
            "no-implicit-destroy": GObject.ParamSpec.boolean(
                "no-implicit-destroy", "", "", GObject.ParamFlags.READWRITE, false,
            ),
        },
    }, Widget)

    return Widget
}

export type BindableProps<T> = {
    [K in keyof T]: Binding<T[K]> | T[K];
}

type SigHandler<
    W extends InstanceType<typeof Gtk.Widget>,
    Args extends Array<unknown>,
> = ((self: W, ...args: Args) => unknown) | string | string[]

export type ConstructProps<
    Self extends InstanceType<typeof Gtk.Widget>,
    Props extends Gtk.Widget.ConstructorProps,
    Signals extends Record<`on${string}`, Array<unknown>> = Record<`on${string}`, any[]>,
> = Partial<{
    // @ts-expect-error can't assign to unknown, but it works as expected though
    [S in keyof Signals]: SigHandler<Self, Signals[S]>
}> & Partial<{
    [Key in `on${string}`]: SigHandler<Self, any[]>
}> & BindableProps<Partial<Props> & {
    className?: string
    css?: string
    cursor?: string
    clickThrough?: boolean
}> & {
    onDestroy?: (self: Self) => unknown
    onDraw?: (self: Self) => unknown
    onKeyPressEvent?: (self: Self, event: Gdk.Event) => unknown
    onKeyReleaseEvent?: (self: Self, event: Gdk.Event) => unknown
    onButtonPressEvent?: (self: Self, event: Gdk.Event) => unknown
    onButtonReleaseEvent?: (self: Self, event: Gdk.Event) => unknown
    onRealize?: (self: Self) => unknown
    setup?: (self: Self) => void
}

export type BindableChild = Gtk.Widget | Binding<Gtk.Widget>

type Cursor =
    | "default"
    | "help"
    | "pointer"
    | "context-menu"
    | "progress"
    | "wait"
    | "cell"
    | "crosshair"
    | "text"
    | "vertical-text"
    | "alias"
    | "copy"
    | "no-drop"
    | "move"
    | "not-allowed"
    | "grab"
    | "grabbing"
    | "all-scroll"
    | "col-resize"
    | "row-resize"
    | "n-resize"
    | "e-resize"
    | "s-resize"
    | "w-resize"
    | "ne-resize"
    | "nw-resize"
    | "sw-resize"
    | "se-resize"
    | "ew-resize"
    | "ns-resize"
    | "nesw-resize"
    | "nwse-resize"
    | "zoom-in"
    | "zoom-out"

type ActionGroup = [prefix: string, actionGroup: Gtk.ActionGroup]