aboutsummaryrefslogtreecommitdiffstats
path: root/e-util/e-plugin.c
blob: 6167b1238f6565a91e59474319b12448c2afb895 (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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154

#include <sys/types.h>
#include <dirent.h>
#include <string.h>

#include <glib/gi18n.h>
#include <gconf/gconf-client.h>

#include "e-plugin.h"
#include "e-msgport.h"

/* plugin debug */
#define pd(x) x
/* plugin hook debug */
#define phd(x) x

/*
<camel-plugin
  class="org.gnome.camel.plugin.provider:1.0"
  id="org.gnome.camel.provider.imap:1.0"
  type="shlib"
  location="/opt/gnome2/lib/camel/1.0/libcamelimap.so"
  factory="camel_imap_provider_new">
 <name>imap</name>
 <description>IMAP4 and IMAP4v1 mail store</description>
 <class-data class="org.gnome.camel.plugin.provider:1.0"
   protocol="imap"
   domain="mail"
   flags="remote,source,storage,ssl"/>
</camel-plugin>

<camel-plugin
  class="org.gnome.camel.plugin.sasl:1.0"
  id="org.gnome.camel.sasl.plain:1.0"
  type="shlib"
  location="/opt/gnome2/lib/camel/1.0/libcamelsasl.so"
  factory="camel_sasl_plain_new">
 <name>PLAIN</name>
 <description>SASL PLAIN authentication mechanism</description>
</camel-plugin>
*/

/* EPlugin stuff */
static GObjectClass *ep_parent_class;

/* global table of plugin types by pluginclass.type */
static GHashTable *ep_types;
/* plugin load path */
static GSList *ep_path;
/* global table of plugins by plugin.id */
static GHashTable *ep_plugins;
/* a table of GSLists of plugins by hook class for hooks not loadable yet */
static GHashTable *ep_plugins_pending;
/* list of all cached xml docs:struct _plugin_doc's */
static EDList ep_plugin_docs = E_DLIST_INITIALISER(ep_plugin_docs);
/* gconf client */
static GConfClient *ep_gconf;
/* the list of disabled plugins from gconf */
static GSList *ep_disabled;

/* EPluginHook stuff */
static void *eph_parent_class;
/* All classes which implement EPluginHooks, by class.id */
static GHashTable *eph_types;

struct _plugin_doc {
    struct _plugin_doc *next;
    struct _plugin_doc *prev;

    xmlDocPtr doc;
    GSList *plugins;
};

static gboolean
ep_check_enabled(const char *id)
{
    GSList *l = ep_disabled;

    for (;l;l = g_slist_next(l))
        if (!strcmp((char *)l->data, id))
            return FALSE;

    return TRUE;
}

static void
ep_set_enabled(const char *id, int state)
{
    if ((state == 0) == ep_check_enabled(id) == 0)
        return;

    if (state) {
        GSList *l = ep_disabled;

        while (l) {
            GSList *n = l->next;

            if (!strcmp((char *)l->data, id)) {
                g_free(l->data);
                ep_disabled = g_slist_remove_link(ep_disabled, l);
            }
            l = n;
        }
    } else {
        ep_disabled = g_slist_prepend(ep_disabled, g_strdup(id));
    }

    gconf_client_set_list(ep_gconf, "/apps/evolution/eplugin/disabled", GCONF_VALUE_STRING, ep_disabled, NULL);
}

static int
ep_construct(EPlugin *ep, xmlNodePtr root)
{
    xmlNodePtr node;
    int res = -1;

    ep->domain = e_plugin_xml_prop(root, "domain");
    ep->name = e_plugin_xml_prop_domain(root, "name", ep->domain);

    printf("creating plugin '%s' '%s'\n", ep->name?ep->name:"un-named", ep->id);

    node = root->children;
    while (node) {
        if (strcmp(node->name, "hook") == 0) {
            struct _EPluginHook *hook;
            EPluginHookClass *type;
            char *class = e_plugin_xml_prop(node, "class");

            if (class == NULL) {
                g_warning("Plugin '%s' load failed in '%s', missing class property for hook", ep->id, ep->path);
                goto fail;
            }

            if (ep->enabled
                && eph_types != NULL
                && (type = g_hash_table_lookup(eph_types, class)) != NULL) {
                g_free(class);
                hook = g_object_new(G_OBJECT_CLASS_TYPE(type), NULL);
                res = type->construct(hook, ep, node);
                if (res == -1) {
                    g_warning("Plugin '%s' failed to load hook", ep->name);
                    g_object_unref(hook);
                    goto fail;
                } else {
                    ep->hooks = g_slist_append(ep->hooks, hook);
                }
            } else {
                GSList *l;
                char *oldclass;

                if (ep_plugins_pending == NULL)
                    ep_plugins_pending = g_hash_table_new(g_str_hash, g_str_equal);
                if (!g_hash_table_lookup_extended(ep_plugins_pending, class, (void **)&oldclass, (void **)&l)) {
                    oldclass = class;
                    l = NULL;
                }
                l = g_slist_prepend(l, ep);
                g_hash_table_insert(ep_plugins_pending, oldclass, l);
                ep->hooks_pending = g_slist_prepend(ep->hooks_pending, node);
            }
        } else if (strcmp(node->name, "description") == 0) {
            ep->description = e_plugin_xml_content_domain(node, ep->domain);
        } else if (strcmp(node->name, "author") == 0) {
            char *name = e_plugin_xml_prop(node, "name");
            char *email = e_plugin_xml_prop(node, "email");

            if (name || email) {
                EPluginAuthor *epa = g_malloc0(sizeof(*epa));

                epa->name = name;
                epa->email = email;
                ep->authors = g_slist_append(ep->authors, epa);
            }
        }
        node = node->next;
    }
    res = 0;
fail:
    return res;
}

static void
ep_enable(EPlugin *ep, int state)
{
    GSList *l;

    ep->enabled = state;
    for (l=ep->hooks;l;l = g_slist_next(l))
        e_plugin_hook_enable((EPluginHook *)l->data, state);

    ep_set_enabled(ep->id, state);
}

static void
ep_finalise(GObject *o)
{
    EPlugin *ep = (EPlugin *)o;

    g_free(ep->id);
    g_free(ep->description);
    g_free(ep->name);
    g_free(ep->domain);
    g_slist_free(ep->hooks_pending);

    g_slist_foreach(ep->hooks, (GFunc)g_object_unref, NULL);
    g_slist_free(ep->hooks);

    ((GObjectClass *)ep_parent_class)->finalize(o);
}

static void
ep_init(GObject *o)
{
    EPlugin *ep = (EPlugin *)o;

    ep->enabled = TRUE;
}

static void
ep_class_init(EPluginClass *klass)
{
    ((GObjectClass *)klass)->finalize = ep_finalise;
    klass->construct = ep_construct;
    klass->enable = ep_enable;
}

/**
 * e_plugin_get_type:
 * 
 * Standard GObject type function.  This is only an abstract class, so
 * you can only use this to subclass EPlugin.
 * 
 * Return value: The type.
 **/
GType
e_plugin_get_type(void)
{
    static GType type = 0;
    
    if (!type) {
        char *path, *col, *p;

        static const GTypeInfo info = {
            sizeof(EPluginClass), NULL, NULL, (GClassInitFunc)ep_class_init, NULL, NULL,
            sizeof(EPlugin), 0, (GInstanceInitFunc)ep_init,
        };

        ep_parent_class = g_type_class_ref(G_TYPE_OBJECT);
        type = g_type_register_static(G_TYPE_OBJECT, "EPlugin", &info, 0);

        /* Add paths in the environment variable or default global and user specific paths */
        path = g_strdup(getenv("EVOLUTION_PLUGIN_PATH"));
        if (path == NULL) {
            /* Add the global path */
            e_plugin_add_load_path(EVOLUTION_PLUGINDIR);

            path = g_build_filename(g_get_home_dir(), ".eplugins", NULL);
        }
        
        p = path;
        while ((col = strchr(p, ':'))) {
            *col++ = 0;
            e_plugin_add_load_path(p);
            p = col;
        }
        e_plugin_add_load_path(p);
        g_free(path);
    }
    
    return type;
}

static int
ep_load(const char *filename)
{
    xmlDocPtr doc;
    xmlNodePtr root;
    int res = -1;
    EPlugin *ep;
    int cache = FALSE;
    struct _plugin_doc *pdoc;

    doc = xmlParseFile(filename);
    if (doc == NULL) {
        return -1;
    }

    root = xmlDocGetRootElement(doc);
    if (strcmp(root->name, "e-plugin-list") != 0) {
        g_warning("No <e-plugin-list> root element: %s", filename);
        xmlFreeDoc(doc);
        return -1;
    }

    pdoc = g_malloc0(sizeof(*pdoc));
    pdoc->doc = doc;
    pdoc->plugins = NULL;

    for (root = root->children; root ; root = root->next) {
        if (strcmp(root->name, "e-plugin") == 0) {
            char *prop, *id;
            EPluginClass *klass;

            id = e_plugin_xml_prop(root, "id");
            if (id == NULL) {
                g_warning("Invalid e-plugin entry in '%s': no id", filename);
                goto fail;
            }

            if (g_hash_table_lookup(ep_plugins, id)) {
                g_warning("Plugin '%s' already defined", id);
                g_free(id);
                continue;
            }

            prop = xmlGetProp(root, "type");
            if (prop == NULL) {
                g_free(id);
                g_warning("Invalid e-plugin entry in '%s': no type", filename);
                goto fail;
            }

            klass = g_hash_table_lookup(ep_types, prop);
            if (klass == NULL) {
                g_warning("Can't find plugin type '%s' for plugin '%s'\n", prop, id);
                g_free(id);
                xmlFree(prop);
                continue;
            }
            xmlFree(prop);

            ep = g_object_new(G_TYPE_FROM_CLASS(klass), NULL);
            ep->id = id;
            ep->path = g_strdup(filename);
            ep->enabled = ep_check_enabled(id);
            if (e_plugin_construct(ep, root) == -1)
                e_plugin_enable(ep, FALSE);
            g_hash_table_insert(ep_plugins, ep->id, ep);
            pdoc->plugins = g_slist_prepend(pdoc->plugins, ep);
            cache |= (ep->hooks_pending != NULL);
        }
    }

    res = 0;
fail:
    if (cache) {
        printf("Caching plugin description '%s' for unknown future hooks\n", filename);
        e_dlist_addtail(&ep_plugin_docs, (EDListNode *)pdoc);
    } else {
        xmlFreeDoc(pdoc->doc);
        g_free(pdoc);
    }

    return res;
}

/* This loads a hook that was pending on a given plugin but the type wasn't registered yet */
/* This works in conjunction with ep_construct and e_plugin_hook_register_type to make sure
   everything works nicely together.  Apparently. */
static int
ep_load_pending(EPlugin *ep, EPluginHookClass *type)
{
    int res = 0;
    GSList *l, *p;

    printf("New hook type registered '%s', loading pending hooks on plugin '%s'\n", type->id, ep->id);

    l = ep->hooks_pending;
    p = NULL;
    while (l) {
        GSList *n = l->next;
        xmlNodePtr node = l->data;
        char *class = xmlGetProp(node, "class");
        EPluginHook *hook;

        printf(" checking pending hook '%s'\n", class?class:"<unknown>");

        if (class) {
            if (strcmp(class, type->id) == 0) {
                hook = g_object_new(G_OBJECT_CLASS_TYPE(type), NULL);
                res = type->construct(hook, ep, node);
                if (res == -1) {
                    g_warning("Plugin '%s' failed to load hook '%s'", ep->name, type->id);
                    g_object_unref(hook);
                } else {
                    ep->hooks = g_slist_append(ep->hooks, hook);
                }

                if (p)
                    p->next = n;
                else
                    ep->hooks_pending = n;
                g_slist_free_1(l);
                l = p;
            }

            xmlFree(class);
        }

        p = l;
        l = n;
    }

    return res;
}

/**
 * e_plugin_add_load_path:
 * @path: The path to add to search for plugins.
 * 
 * Add a path to be searched when e_plugin_load_plugins() is called.
 * By default the system plugin directory and ~/.eplugins is used as
 * the search path unless overriden by the environmental variable
 * %EVOLUTION_PLUGIN_PATH.
 *
 * %EVOLUTION_PLUGIN_PATH is a : separated list of paths to search for
 * plugin definitions in order.
 *
 * Plugin definitions are XML files ending in the extension ".eplug".
 **/
void
e_plugin_add_load_path(const char *path)
{
    ep_path = g_slist_append(ep_path, g_strdup(path));
}

/**
 * e_plugin_load_plugins:
 * 
 * Scan the search path, looking for plugin definitions, and load them
 * into memory.
 * 
 * Return value: Returns -1 if an error occured.
 **/
int
e_plugin_load_plugins(void)
{
    GSList *l;

    if (ep_types == NULL) {
        g_warning("no plugin types defined");
        return 0;
    }


    for (l = ep_path;l;l = g_slist_next(l)) {
        DIR *dir;
        struct dirent *d;
        char *path = l->data;

        printf("scanning plugin dir '%s'\n", path);

        dir = opendir(path);
        if (dir == NULL) {
            g_warning("Could not find plugin path: %s", path);
            continue;
        }

        while ( (d = readdir(dir)) ) {
            if (strlen(d->d_name) > 6
                && !strcmp(d->d_name + strlen(d->d_name) - 6, ".eplug")) {
                char * name = g_build_filename(path, d->d_name, NULL);

                ep_load(name);
                g_free(name);
            }
        }

        closedir(dir);
    }

    return 0;
}

/**
 * e_plugin_register_type:
 * @type: The GObject type of the plugin loader.
 * 
 * Register a new plugin type with the plugin system.  Each type must
 * subclass EPlugin and must override the type member of the
 * EPluginClass with a unique name.
 **/
void
e_plugin_register_type(GType type)
{
    EPluginClass *klass;

    if (ep_types == NULL) {
        ep_types = g_hash_table_new(g_str_hash, g_str_equal);
        ep_plugins = g_hash_table_new(g_str_hash, g_str_equal);
        /* TODO: notify listening */
        ep_gconf = gconf_client_get_default();
        ep_disabled = gconf_client_get_list(ep_gconf, "/apps/evolution/eplugin/disabled", GCONF_VALUE_STRING, NULL);
    }

    klass = g_type_class_ref(type);

    pd(printf("register plugin type '%s'\n", klass->type));

    g_hash_table_insert(ep_types, (void *)klass->type, klass);
}

static void
ep_list_plugin(void *key, void *val, void *dat)
{
    GSList **l = (GSList **)dat;

    *l = g_slist_prepend(*l, g_object_ref(val));
}

/**
 * e_plugin_list_plugins: List all plugins.
 * 
 * Static class method to retrieve a list of all current plugins.  They
 * are listed in no particular order.
 * 
 * Return value: A GSList of all plugins, they must be
 * g_object_unref'd and the list freed.
 **/
GSList *
e_plugin_list_plugins(void)
{
    GSList *l = NULL;

    if (ep_plugins)
        g_hash_table_foreach(ep_plugins, ep_list_plugin, &l);

    return l;
}

/**
 * e_plugin_construct:
 * @ep: An EPlugin derived object.
 * @root: The XML root node of the sub-tree containing the plugin
 * definition.
 * 
 * Helper to invoke the construct virtual method.
 * 
 * Return value: The return from the construct virtual method.
 **/
int
e_plugin_construct(EPlugin *ep, xmlNodePtr root)
{
    return ((EPluginClass *)G_OBJECT_GET_CLASS(ep))->construct(ep, root);
}

/**
 * e_plugin_invoke:
 * @ep: 
 * @name: The name of the function to invoke. The format of this name
 * will depend on the EPlugin type and its language conventions.
 * @data: The argument to the function. Its actual type depends on
 * the hook on which the function resides. It is up to the called
 * function to get this right.
 * 
 * Helper to invoke the invoke virtual method.
 * 
 * Return value: The return of the plugin invocation.
 **/
void *
e_plugin_invoke(EPlugin *ep, const char *name, void *data)
{
    if (!ep->enabled) {
        g_warning("Invoking method on disabled plugin, ignored");
        return NULL;
    }

    return ((EPluginClass *)G_OBJECT_GET_CLASS(ep))->invoke(ep, name, data);
}

/**
 * e_plugin_enable:
 * @ep: 
 * @state: 
 * 
 * Set the enable state of a plugin.
 *
 * THIS IS NOT FULLY IMPLEMENTED YET
 **/
void
e_plugin_enable(EPlugin *ep, int state)
{
    if ((ep->enabled == 0) == (state == 0))
        return;

    ((EPluginClass *)G_OBJECT_GET_CLASS(ep))->enable(ep, state);
}

/**
 * e_plugin_xml_prop:
 * @node: An XML node.
 * @id: The name of the property to retrieve.
 * 
 * A static helper function to look up a property on an XML node, and
 * ensure it is allocated in GLib system memory.  If GLib isn't using
 * the system malloc then it must copy the property value.
 * 
 * Return value: The property, allocated in GLib memory, or NULL if no
 * such property exists.
 **/
char *
e_plugin_xml_prop(xmlNodePtr node, const char *id)
{
    char *p = xmlGetProp(node, id);

    if (g_mem_is_system_malloc()) {
        return p;
    } else {
        char * out = g_strdup(p);

        if (p)
            xmlFree(p);
        return out;
    }
}

/**
 * e_plugin_xml_prop_domain:
 * @node: An XML node.
 * @id: The name of the property to retrieve.
 * @domain: The translation domain for this string.
 * 
 * A static helper function to look up a property on an XML node, and
 * translate it based on @domain.
 * 
 * Return value: The property, allocated in GLib memory, or NULL if no
 * such property exists.
 **/
char *
e_plugin_xml_prop_domain(xmlNodePtr node, const char *id, const char *domain)
{
    char *p, *out;

    p = xmlGetProp(node, id);
    if (p == NULL)
        return NULL;

    out = g_strdup(dgettext(domain, p));
    xmlFree(p);

    return out;
}

/**
 * e_plugin_xml_int:
 * @node: An XML node.
 * @id: The name of the property to retrieve.
 * @def: A default value if the property doesn't exist.  Can be used
 * to determine if the property isn't set.
 * 
 * A static helper function to look up a property on an XML node as an
 * integer.  If the property doesn't exist, then @def is returned as a
 * default value instead.
 * 
 * Return value: The value if set, or @def if not.
 **/
int
e_plugin_xml_int(xmlNodePtr node, const char *id, int def)
{
    char *p = xmlGetProp(node, id);

    if (p)
        return atoi(p);
    else
        return def;
}

/**
 * e_plugin_xml_content:
 * @node: 
 * 
 * A static helper function to retrieve the entire textual content of
 * an XML node, and ensure it is allocated in GLib system memory.  If
 * GLib isn't using the system malloc them it must copy the content.
 * 
 * Return value: The node content, allocated in GLib memory.
 **/
char *
e_plugin_xml_content(xmlNodePtr node)
{
    char *p = xmlNodeGetContent(node);

    if (g_mem_is_system_malloc()) {
        return p;
    } else {
        char * out = g_strdup(p);

        if (p)
            xmlFree(p);
        return out;
    }
}

/**
 * e_plugin_xml_content_domain:
 * @node: 
 * @domain:
 * 
 * A static helper function to retrieve the entire textual content of
 * an XML node, and ensure it is allocated in GLib system memory.  If
 * GLib isn't using the system malloc them it must copy the content.
 * 
 * Return value: The node content, allocated in GLib memory.
 **/
char *
e_plugin_xml_content_domain(xmlNodePtr node, const char *domain)
{
    char *p, *out;

    p = xmlNodeGetContent(node);
    if (p == NULL)
        return NULL;

    out = g_strdup(dgettext(domain, p));
    xmlFree(p);

    return out;
}

/* ********************************************************************** */
static void *epl_parent_class;

/* this looks weird, but it saves a lot of typing */
#define epl ((EPluginLib *)ep)

/* TODO:
   We need some way to manage lifecycle.
   We need some way to manage state.

   Maybe just the g module init method will do, or we could add
   another which returns context.

   There is also the question of per-instance context, e.g. for config
   pages.
*/

static int
epl_loadmodule(EPlugin *ep)
{
    if (epl->module == NULL) {
        EPluginLibEnableFunc enable;
        
        if ((epl->module = g_module_open(epl->location, 0)) == NULL) {
            g_warning("can't load plugin '%s'", g_module_error());
            return -1;
        }

        if (g_module_symbol(epl->module, "e_plugin_lib_enable", (void *)&enable)) {
            if (enable(epl, TRUE) != 0) {
                ep->enabled = FALSE;
                g_module_close(epl->module);
                epl->module = NULL;
                return -1;
            }
        }
    }

    return 0;
}

static void *
epl_invoke(EPlugin *ep, const char *name, void *data)
{
    EPluginLibFunc cb;

    if (!ep->enabled) {
        g_warning("trying to invoke '%s' on disabled plugin '%s'", name, ep->id);
        return NULL;
    }

    if (epl_loadmodule(ep) != 0)
        return NULL;

    if (!g_module_symbol(epl->module, name, (void *)&cb)) {
        g_warning("Cannot resolve symbol '%s' in plugin '%s' (not exported?)", name, epl->location);
        return NULL;
    }

    return cb(epl, data);
}

static int
epl_construct(EPlugin *ep, xmlNodePtr root)
{
    if (((EPluginClass *)epl_parent_class)->construct(ep, root) == -1)
        return -1;

    epl->location = e_plugin_xml_prop(root, "location");

    if (epl->location == NULL)
        return -1;

    /* If we're enabled, check for the load-on-startup property */
    if (ep->enabled) {
        xmlChar *tmp;

        tmp = xmlGetProp(root, "load-on-startup");
        if (tmp) {
            xmlFree(tmp);
            if (epl_loadmodule(ep) != 0)
                return -1;
        }
    }

    return 0;
}

static void
epl_enable(EPlugin *ep, int state)
{
    EPluginLibEnableFunc enable;

    ((EPluginClass *)epl_parent_class)->enable(ep, state);

    /* if we're disabling and it isn't loaded, nothing to do */
    if (!state && epl->module == NULL)
        return;

    /* this will noop if we're disabling since we tested it above */
    if (epl_loadmodule(ep) != 0)
        return;

    if (g_module_symbol(epl->module, "e_plugin_lib_enable", (void *)&enable)) {
        if (enable(epl, state) != 0)
            return;
    }
#if 0
    if (!state) {
        g_module_close(epl->module);
        epl->module = NULL;
    }
#endif
}

static void
epl_finalise(GObject *o)
{
    EPlugin *ep = (EPlugin *)o;

    g_free(epl->location);

    if (epl->module)
        g_module_close(epl->module);

    ((GObjectClass *)epl_parent_class)->finalize(o);
}

static void
epl_class_init(EPluginClass *klass)
{
    ((GObjectClass *)klass)->finalize = epl_finalise;
    klass->construct = epl_construct;
    klass->invoke = epl_invoke;
    klass->enable = epl_enable;
    klass->type = "shlib";
}

/**
 * e_plugin_lib_get_type:
 * 
 * Standard GObject function to retrieve the EPluginLib type.  Use to
 * register the type with the plugin system if you want to use shared
 * library plugins.
 * 
 * Return value: The EPluginLib type.
 **/
GType
e_plugin_lib_get_type(void)
{
    static GType type = 0;
    
    if (!type) {
        static const GTypeInfo info = {
            sizeof(EPluginLibClass), NULL, NULL, (GClassInitFunc) epl_class_init, NULL, NULL,
            sizeof(EPluginLib), 0, (GInstanceInitFunc) NULL,
        };

        epl_parent_class = g_type_class_ref(e_plugin_get_type());
        type = g_type_register_static(e_plugin_get_type(), "EPluginLib", &info, 0);
    }
    
    return type;
}

/* ********************************************************************** */

static int
eph_construct(EPluginHook *eph, EPlugin *ep, xmlNodePtr root)
{
    eph->plugin = ep;

    return 0;
}

static void
eph_enable(EPluginHook *eph, int state)
{
    /* NOOP */
}

static void
eph_finalise(GObject *o)
{
    ((GObjectClass *)eph_parent_class)->finalize((GObject *)o);
}

static void
eph_class_init(EPluginHookClass *klass)
{
    ((GObjectClass *)klass)->finalize = eph_finalise;
    klass->construct = eph_construct;
    klass->enable = eph_enable;
}

/**
 * e_plugin_hook_get_type:
 * 
 * Standard GObject function to retrieve the EPluginHook type.  Since
 * EPluginHook is an abstract class, this is only used to subclass it.
 * 
 * Return value: The EPluginHook type.
 **/
GType
e_plugin_hook_get_type(void)
{
    static GType type = 0;
    
    if (!type) {
        static const GTypeInfo info = {
            sizeof(EPluginHookClass), NULL, NULL, (GClassInitFunc) eph_class_init, NULL, NULL,
            sizeof(EPluginHook), 0, (GInstanceInitFunc) NULL,
        };

        eph_parent_class = g_type_class_ref(G_TYPE_OBJECT);
        type = g_type_register_static(G_TYPE_OBJECT, "EPluginHook", &info, 0);
    }
    
    return type;
}

/**
 * e_plugin_hook_enable: Set hook enabled state.
 * @eph: 
 * @state: 
 * 
 * Set the enabled state of the plugin hook.  This is called by the
 * plugin code.
 *
 * THIS IS NOT FULY IMEPLEMENTED YET
 **/
void
e_plugin_hook_enable(EPluginHook *eph, int state)
{
    ((EPluginHookClass *)G_OBJECT_GET_CLASS(eph))->enable(eph, state);
}

/**
 * e_plugin_hook_register_type:
 * @type: 
 * 
 * Register a new plugin hook type with the plugin system.  Each type
 * must subclass EPluginHook and must override the id member of the
 * EPluginHookClass with a unique identification string.
 **/
void
e_plugin_hook_register_type(GType type)
{
    EPluginHookClass *klass, *oldklass;
    GSList *l, *plugins;
    char *class;

    if (eph_types == NULL)
        eph_types = g_hash_table_new(g_str_hash, g_str_equal);

    klass = g_type_class_ref(type);

    oldklass = g_hash_table_lookup(eph_types, (void *)klass->id);
    if (oldklass == klass) {
        g_type_class_unref(klass);
        return;
    } else if (oldklass != NULL) {
        g_warning("Trying to re-register hook type '%s'", klass->id);
        return;
    }

    phd(printf("register plugin hook type '%s'\n", klass->id));
    g_hash_table_insert(eph_types, (void *)klass->id, klass);

    /* if we've already loaded a plugin that needed this hook but it didn't exist, re-load it now */

    if (ep_plugins_pending
        && g_hash_table_lookup_extended(ep_plugins_pending, klass->id, (void **)&class, (void **)&plugins)) {
        struct _plugin_doc *pdoc, *ndoc;

        g_hash_table_remove(ep_plugins_pending, class);
        g_free(class);
        for (l = plugins; l; l = g_slist_next(l)) {
            EPlugin *ep = l->data;

            ep_load_pending(ep, klass);
        }
        g_slist_free(plugins);

        /* See if we can now garbage collect the xml definition since its been fully loaded */

        /* This is all because libxml doesn't refcount! */

        pdoc = (struct _plugin_doc *)ep_plugin_docs.head;
        ndoc = pdoc->next;
        while (ndoc) {
            if (pdoc->doc) {
                int cache = FALSE;

                for (l=pdoc->plugins;l;l=g_slist_next(l))
                    cache |= (((EPlugin *)l->data)->hooks_pending != NULL);

                if (!cache) {
                    printf("Gargabe collecting plugin description\n");
                    e_dlist_remove((EDListNode *)pdoc);
                    xmlFreeDoc(pdoc->doc);
                    g_free(pdoc);
                }
            }

            pdoc = ndoc;
            ndoc = ndoc->next;
        }
    }
}

/**
 * e_plugin_hook_mask:
 * @root: An XML node.
 * @map: A zero-fill terminated array of EPluginHookTargeKeys used to
 * map a string with a bit value.
 * @prop: The property name.
 * 
 * This is a static helper function which looks up a property @prop on
 * the XML node @root, and then uses the @map table to convert it into
 * a bitmask.  The property value is a comma separated list of
 * enumeration strings which are indexed into the @map table.
 *
 * Return value: A bitmask representing the inclusive-or of all of the
 * integer values of the corresponding string id's stored in the @map.
 **/
guint32
e_plugin_hook_mask(xmlNodePtr root, const struct _EPluginHookTargetKey *map, const char *prop)
{
    char *val, *p, *start, c;
    guint32 mask = 0;

    val = xmlGetProp(root, prop);
    if (val == NULL)
        return 0;

    p = val;
    do {
        start = p;
        while (*p && *p != ',')
            p++;
        c = *p;
        *p = 0;
        if (start != p) {
            int i;

            for (i=0;map[i].key;i++) {
                if (!strcmp(map[i].key, start)) {
                    mask |= map[i].value;
                    break;
                }
            }
        }
        *p++ = c;
    } while (c);

    xmlFree(val);

    return mask;
}

/**
 * e_plugin_hook_id:
 * @root: 
 * @map: 
 * @prop: 
 * 
 * This is a static helper function which looks up a property @prop on
 * the XML node @root, and then uses the @map table to convert it into
 * an integer.
 *
 * This is used as a helper wherever you need to represent an
 * enumerated value in the XML.
 * 
 * Return value: If the @prop value is in @map, then the corresponding
 * integer value, if not, then ~0.
 **/
guint32
e_plugin_hook_id(xmlNodePtr root, const struct _EPluginHookTargetKey *map, const char *prop)
{
    char *val;
    int i;

    val = xmlGetProp(root, prop);
    if (val == NULL)
        return ~0;

    for (i=0;map[i].key;i++) {
        if (!strcmp(map[i].key, val)) {
            xmlFree(val);
            return map[i].value;
        }
    }

    xmlFree(val);

    return ~0;
}

#if 0
/*
  e-mail-format-handler
    mime_type
    target
*/
struct _EMFormatPlugin {
    EPlugin plugin;

    char *target;
    char *mime_type;
    struct _EMFormatHandler *(*get_handler)(void);
};

struct _EMFormatPluginClass {
    EPluginClass plugin_class;
};

#endif

#if 0
void em_setup_plugins(void);

void
em_setup_plugins(void)
{
    GType *e_plugin_mono_get_type(void);

    e_plugin_register_type(e_plugin_lib_get_type());
    e_plugin_register_type(e_plugin_mono_get_type());

    e_plugin_hook_register_type(em_popup_hook_get_type());

    e_plugin_load_plugins(".");
}
#endif