aboutsummaryrefslogtreecommitdiff
path: root/libdino/src/plugin/loader.vala
blob: 43ce08013079ebf8ed9400a8dfb0a733d1b034f5 (plain) (blame)
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
namespace Dino.Plugins {

public errordomain Error {
	NOT_SUPPORTED,
	UNEXPECTED_TYPE,
	NO_REGISTRATION_FUNCTION,
	FAILED
}

private class Info : Object {
    public Module module;
    public Type gtype;

    public Info(Type type, owned Module module) {
        this.module = (owned) module;
        this.gtype = type;
    }
}

public class Loader : Object {
    [CCode (has_target = false)]
    private delegate Type RegisterPluginFunction (Module module);

    private RootInterface[] plugins = new RootInterface[0];
    private Info[] infos = new Info[0];

    public RootInterface load(string name, Dino.Application app) throws Error {
        if (Module.supported () == false) {
            throw new Error.NOT_SUPPORTED ("Plugins are not supported");
        }

        Module module = Module.open ("plugins/" + name, ModuleFlags.BIND_LAZY);
        if (module == null) {
            throw new Error.FAILED (Module.error ());
        }

        void* function;
        module.symbol ("register_plugin", out function);
        if (function == null) {
            throw new Error.NO_REGISTRATION_FUNCTION ("register_plugin () not found");
        }

        RegisterPluginFunction register_plugin = (RegisterPluginFunction) function;
        Type type = register_plugin (module);
        if (type.is_a (typeof (RootInterface)) == false) {
            throw new Error.UNEXPECTED_TYPE ("Unexpected type");
        }

        Info info = new Plugins.Info (type, (owned) module);
        infos += info;

        RootInterface plugin = (RootInterface) Object.new (type);
        plugins += plugin;
        plugin.registered (app);

        return plugin;
    }

    public void shutdown() {
        foreach (RootInterface p in plugins) {
            p.shutdown();
        }
    }
}

}