summaryrefslogtreecommitdiff
path: root/node/src/application.ts
blob: 552f2a9ffc096e31f1189479c0674ec30f0d4c95 (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
import gi from "node-gtk"
const Astal = gi.require("Astal", "0.1")

type RequestHandler = {
    (request: string, res: (response: string) => void): void
}

type Config = Partial<{
    instanceName: string
    gtkTheme: string
    iconTheme: string
    cursorTheme: string
    css: string
    requestHandler: RequestHandler
    hold: boolean
}>

class AstalJS extends Astal.Application {
    static GTypeName = "AstalJS"
    static { gi.registerClass(this) }

    eval(body: string): Promise<any> {
        return new Promise((res, rej) => {
            try {
                const fn = Function(`return (async function() {
                    ${body.includes(";") ? body : `return ${body};`}
                })`)
                fn()()
                    .then(res)
                    .catch(rej)
            } catch (error) {
                rej(error)
            }
        })
    }

    requestHandler?: RequestHandler

    vfunc_request(msg: string, conn: any): void {
        if (typeof this.requestHandler === "function") {
            this.requestHandler(msg, response => {
                Astal.writeSock(conn, String(response), (_, res) =>
                    Astal.writeSockFinish(res),
                )
            })
        } else {
            // @ts-expect-error missing type
            super.vfunc_request(msg, conn)
        }
    }

    start(
        { requestHandler, css, ...cfg }: Omit<Config, "hold"> = {},
        callback?: (args: string[]) => any,
    ) {
        Object.assign(this, cfg)

        this.requestHandler = requestHandler
        this.on("activate", () => {
            callback?.(process.argv)
        })

        if (!this.acquireSocket()) {
            console.error(`Astal instance "${this.instanceName}" already running`)
            process.exit()
        }

        if (css)
            this.applyCss(css, false)

        // FIXME: promises never resolve
        // https://github.com/romgrk/node-gtk/issues/121
        // https://gitlab.gnome.org/GNOME/gjs/-/issues/468
        App.run([])
    }
}

export const App = new AstalJS