Merge pull request #1133 from techee/readme_rst
[geany-mirror.git] / src / plugins.c
blob938f03dc61378e263c58352b0bbcecf0fd445fdc
1 /*
2 * plugins.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2007-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2007-2012 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 /* Code to manage, load and unload plugins. */
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
28 #ifdef HAVE_PLUGINS
30 #include "plugins.h"
32 #include "app.h"
33 #include "dialogs.h"
34 #include "encodings.h"
35 #include "geanyobject.h"
36 #include "geanywraplabel.h"
37 #include "highlighting.h"
38 #include "keybindingsprivate.h"
39 #include "keyfile.h"
40 #include "main.h"
41 #include "msgwindow.h"
42 #include "navqueue.h"
43 #include "plugindata.h"
44 #include "pluginprivate.h"
45 #include "pluginutils.h"
46 #include "prefs.h"
47 #include "sciwrappers.h"
48 #include "stash.h"
49 #include "support.h"
50 #include "symbols.h"
51 #include "templates.h"
52 #include "toolbar.h"
53 #include "ui_utils.h"
54 #include "utils.h"
55 #include "win32.h"
57 #include "gtkcompat.h"
59 #include <string.h>
62 GList *active_plugin_list = NULL; /* list of only actually loaded plugins, always valid */
65 static gboolean want_plugins = FALSE;
67 /* list of all available, loadable plugins, only valid as long as the plugin manager dialog is
68 * opened, afterwards it will be destroyed */
69 static GList *plugin_list = NULL;
70 static gchar **active_plugins_pref = NULL; /* list of plugin filenames to load at startup */
71 static GList *failed_plugins_list = NULL; /* plugins the user wants active but can't be used */
73 static GtkWidget *menu_separator = NULL;
75 static gchar *get_plugin_path(void);
76 static void pm_show_dialog(GtkMenuItem *menuitem, gpointer user_data);
78 typedef struct {
79 gchar extension[8];
80 Plugin *plugin; /* &builtin_so_proxy_plugin for native plugins */
81 } PluginProxy;
84 static gpointer plugin_load_gmodule(GeanyPlugin *proxy, GeanyPlugin *plugin, const gchar *filename, gpointer pdata);
85 static void plugin_unload_gmodule(GeanyPlugin *proxy, GeanyPlugin *plugin, gpointer load_data, gpointer pdata);
87 static Plugin builtin_so_proxy_plugin = {
88 .proxy_cbs = {
89 .load = plugin_load_gmodule,
90 .unload = plugin_unload_gmodule,
92 /* rest of Plugin can be NULL/0 */
95 static PluginProxy builtin_so_proxy = {
96 .extension = G_MODULE_SUFFIX,
97 .plugin = &builtin_so_proxy_plugin,
100 static GQueue active_proxies = G_QUEUE_INIT;
102 static void plugin_free(Plugin *plugin);
104 static GeanyData geany_data;
106 static void
107 geany_data_init(void)
109 GeanyData gd = {
110 app,
111 &main_widgets,
112 documents_array,
113 filetypes_array,
114 &prefs,
115 &interface_prefs,
116 &toolbar_prefs,
117 &editor_prefs,
118 &file_prefs,
119 &search_prefs,
120 &tool_prefs,
121 &template_prefs,
122 NULL, /* Remove field on next ABI break (abi-todo) */
123 filetypes_by_title,
124 geany_object,
127 geany_data = gd;
131 /* In order to have nested proxies work the count of dependent plugins must propagate up.
132 * This prevents that any plugin in the tree is unloaded while a leaf plugin is active. */
133 static void proxied_count_inc(Plugin *proxy)
137 proxy->proxied_count += 1;
138 proxy = proxy->proxy;
139 } while (proxy != NULL);
143 static void proxied_count_dec(Plugin *proxy)
145 g_warn_if_fail(proxy->proxied_count > 0);
149 proxy->proxied_count -= 1;
150 proxy = proxy->proxy;
151 } while (proxy != NULL);
155 /* Prevent the same plugin filename being loaded more than once.
156 * Note: g_module_name always returns the .so name, even when Plugin::filename is a .la file. */
157 static gboolean
158 plugin_loaded(Plugin *plugin)
160 gchar *basename_module, *basename_loaded;
161 GList *item;
163 basename_module = g_path_get_basename(plugin->filename);
164 for (item = plugin_list; item != NULL; item = g_list_next(item))
166 basename_loaded = g_path_get_basename(((Plugin*)item->data)->filename);
168 if (utils_str_equal(basename_module, basename_loaded))
170 g_free(basename_loaded);
171 g_free(basename_module);
172 return TRUE;
174 g_free(basename_loaded);
176 /* Look also through the list of active plugins. This prevents problems when we have the same
177 * plugin in libdir/geany/ AND in configdir/plugins/ and the one in libdir/geany/ is loaded
178 * as active plugin. The plugin manager list would only take the one in configdir/geany/ and
179 * the plugin manager would list both plugins. Additionally, unloading the active plugin
180 * would cause a crash. */
181 for (item = active_plugin_list; item != NULL; item = g_list_next(item))
183 basename_loaded = g_path_get_basename(((Plugin*)item->data)->filename);
185 if (utils_str_equal(basename_module, basename_loaded))
187 g_free(basename_loaded);
188 g_free(basename_module);
189 return TRUE;
191 g_free(basename_loaded);
193 g_free(basename_module);
194 return FALSE;
198 static Plugin *find_active_plugin_by_name(const gchar *filename)
200 GList *item;
202 g_return_val_if_fail(filename, FALSE);
204 for (item = active_plugin_list; item != NULL; item = g_list_next(item))
206 if (utils_str_equal(filename, ((Plugin*)item->data)->filename))
207 return item->data;
210 return NULL;
214 /* Mimics plugin_version_check() of legacy plugins for use with plugin_check_version() below */
215 #define PLUGIN_VERSION_CODE(api, abi) ((abi) != GEANY_ABI_VERSION ? -1 : (api))
217 static gboolean
218 plugin_check_version(Plugin *plugin, int plugin_version_code)
220 gboolean ret = TRUE;
221 if (plugin_version_code < 0)
223 gchar *name = g_path_get_basename(plugin->filename);
224 msgwin_status_add(_("The plugin \"%s\" is not binary compatible with this "
225 "release of Geany - please recompile it."), name);
226 geany_debug("Plugin \"%s\" is not binary compatible with this "
227 "release of Geany - recompile it.", name);
228 ret = FALSE;
229 g_free(name);
231 else if (plugin_version_code > GEANY_API_VERSION)
233 gchar *name = g_path_get_basename(plugin->filename);
234 geany_debug("Plugin \"%s\" requires a newer version of Geany (API >= v%d).",
235 name, plugin_version_code);
236 ret = FALSE;
237 g_free(name);
240 return ret;
244 static void add_callbacks(Plugin *plugin, PluginCallback *callbacks)
246 PluginCallback *cb;
247 guint i, len = 0;
249 while (TRUE)
251 cb = &callbacks[len];
252 if (!cb->signal_name || !cb->callback)
253 break;
254 len++;
256 if (len == 0)
257 return;
259 for (i = 0; i < len; i++)
261 cb = &callbacks[i];
263 /* Pass the callback data as default user_data if none was set by the plugin itself */
264 plugin_signal_connect(&plugin->public, NULL, cb->signal_name, cb->after,
265 cb->callback, cb->user_data ? cb->user_data : plugin->cb_data);
270 static void read_key_group(Plugin *plugin)
272 GeanyKeyGroupInfo *p_key_info;
273 GeanyKeyGroup **p_key_group;
274 GModule *module = plugin->proxy_data;
276 g_module_symbol(module, "plugin_key_group_info", (void *) &p_key_info);
277 g_module_symbol(module, "plugin_key_group", (void *) &p_key_group);
278 if (p_key_info && p_key_group)
280 GeanyKeyGroupInfo *key_info = p_key_info;
282 if (*p_key_group)
283 geany_debug("Ignoring plugin_key_group symbol for plugin '%s' - "
284 "use plugin_set_key_group() instead to allocate keybindings dynamically.",
285 plugin->info.name);
286 else
288 if (key_info->count)
290 GeanyKeyGroup *key_group =
291 plugin_set_key_group(&plugin->public, key_info->name, key_info->count, NULL);
292 if (key_group)
293 *p_key_group = key_group;
295 else
296 geany_debug("Ignoring plugin_key_group_info symbol for plugin '%s' - "
297 "count field is zero. Maybe use plugin_set_key_group() instead?",
298 plugin->info.name);
301 else if (p_key_info || p_key_group)
302 geany_debug("Ignoring only one of plugin_key_group[_info] symbols defined for plugin '%s'. "
303 "Maybe use plugin_set_key_group() instead?",
304 plugin->info.name);
308 static gint cmp_plugin_names(gconstpointer a, gconstpointer b)
310 const Plugin *pa = a;
311 const Plugin *pb = b;
313 return strcmp(pa->info.name, pb->info.name);
317 /** Register a plugin to Geany.
319 * The plugin will show up in the plugin manager. The user can interact with
320 * it based on the functions it provides and installed GUI elements.
322 * You must initialize the info and funcs fields of @ref GeanyPlugin
323 * appropriately prior to calling this, otherwise registration will fail. For
324 * info at least a valid name must be set (possibly localized). For funcs,
325 * at least init() and cleanup() functions must be implemented and set.
327 * The return value must be checked. It may be FALSE if the plugin failed to register which can
328 * mainly happen for two reasons (future Geany versions may add new failure conditions):
329 * - Not all mandatory fields of GeanyPlugin have been set.
330 * - The ABI or API versions reported by the plugin are incompatible with the running Geany.
332 * Do not call this directly. Use GEANY_PLUGIN_REGISTER() instead which automatically
333 * handles @a api_version and @a abi_version.
335 * @param plugin The plugin provided by Geany
336 * @param api_version The API version the plugin is compiled against (pass GEANY_API_VERSION)
337 * @param min_api_version The minimum API version required by the plugin
338 * @param abi_version The exact ABI version the plugin is compiled against (pass GEANY_ABI_VERSION)
340 * @return TRUE if the plugin was successfully registered. Otherwise FALSE.
342 * @since 1.26 (API 225)
343 * @see GEANY_PLUGIN_REGISTER()
345 GEANY_API_SYMBOL
346 gboolean geany_plugin_register(GeanyPlugin *plugin, gint api_version, gint min_api_version,
347 gint abi_version)
349 Plugin *p;
350 GeanyPluginFuncs *cbs = plugin->funcs;
352 g_return_val_if_fail(plugin != NULL, FALSE);
354 p = plugin->priv;
355 /* already registered successfully */
356 g_return_val_if_fail(!PLUGIN_LOADED_OK(p), FALSE);
358 /* Prevent registering incompatible plugins. */
359 if (! plugin_check_version(p, PLUGIN_VERSION_CODE(api_version, abi_version)))
360 return FALSE;
362 /* Only init and cleanup callbacks are truly mandatory. */
363 if (! cbs->init || ! cbs->cleanup)
365 gchar *name = g_path_get_basename(p->filename);
366 geany_debug("Plugin '%s' has no %s function - ignoring plugin!", name,
367 cbs->init ? "cleanup" : "init");
368 g_free(name);
370 else
372 /* Yes, name is checked again later on, however we want return FALSE here
373 * to signal the error back to the plugin (but we don't print the message twice) */
374 if (! EMPTY(p->info.name))
375 p->flags = LOADED_OK;
378 /* If it ever becomes necessary we can save the api version in Plugin
379 * and apply compat code on a per-plugin basis, because we learn about
380 * the requested API version here. For now it's not necessary. */
382 return PLUGIN_LOADED_OK(p);
386 /** Register a plugin to Geany, with plugin-defined data.
388 * This is a variant of geany_plugin_register() that also allows to set the plugin-defined data.
389 * Refer to that function for more details on registering in general.
391 * @p pdata is the pointer going to be passed to the individual plugin callbacks
392 * of GeanyPlugin::funcs. When the plugin module is unloaded, @p free_func is invoked on
393 * @p pdata, which connects the data to the plugin's module life time.
395 * You cannot use geany_plugin_set_data() after registering with this function. Use
396 * geany_plugin_register() if you need to.
398 * Do not call this directly. Use GEANY_PLUGIN_REGISTER_FULL() instead which automatically
399 * handles @p api_version and @p abi_version.
401 * @param plugin The plugin provided by Geany.
402 * @param api_version The API version the plugin is compiled against (pass GEANY_API_VERSION).
403 * @param min_api_version The minimum API version required by the plugin.
404 * @param abi_version The exact ABI version the plugin is compiled against (pass GEANY_ABI_VERSION).
405 * @param pdata Pointer to the plugin-defined data. Must not be @c NULL.
406 * @param free_func Function used to deallocate @a pdata, may be @c NULL.
408 * @return TRUE if the plugin was successfully registered. Otherwise FALSE.
410 * @since 1.26 (API 225)
411 * @see GEANY_PLUGIN_REGISTER_FULL()
412 * @see geany_plugin_register()
414 GEANY_API_SYMBOL
415 gboolean geany_plugin_register_full(GeanyPlugin *plugin, gint api_version, gint min_api_version,
416 gint abi_version, gpointer pdata, GDestroyNotify free_func)
418 if (geany_plugin_register(plugin, api_version, min_api_version, abi_version))
420 geany_plugin_set_data(plugin, pdata, free_func);
421 /* We use LOAD_DATA to indicate that pdata cb_data was set during loading/registration
422 * as opposed to during GeanyPluginFuncs::init(). In the latter case we call free_func
423 * after GeanyPluginFuncs::cleanup() */
424 plugin->priv->flags |= LOAD_DATA;
425 return TRUE;
427 return FALSE;
430 struct LegacyRealFuncs
432 void (*init) (GeanyData *data);
433 GtkWidget* (*configure) (GtkDialog *dialog);
434 void (*help) (void);
435 void (*cleanup) (void);
438 /* Wrappers to support legacy plugins are below */
439 static gboolean legacy_init(GeanyPlugin *plugin, gpointer pdata)
441 struct LegacyRealFuncs *h = pdata;
442 h->init(plugin->geany_data);
443 return TRUE;
446 static void legacy_cleanup(GeanyPlugin *plugin, gpointer pdata)
448 struct LegacyRealFuncs *h = pdata;
449 /* Can be NULL because it's optional for legacy plugins */
450 if (h->cleanup)
451 h->cleanup();
454 static void legacy_help(GeanyPlugin *plugin, gpointer pdata)
456 struct LegacyRealFuncs *h = pdata;
457 h->help();
460 static GtkWidget *legacy_configure(GeanyPlugin *plugin, GtkDialog *parent, gpointer pdata)
462 struct LegacyRealFuncs *h = pdata;
463 return h->configure(parent);
466 static void free_legacy_cbs(gpointer data)
468 g_slice_free(struct LegacyRealFuncs, data);
471 /* This function is the equivalent of geany_plugin_register() for legacy-style
472 * plugins which we continue to load for the time being. */
473 static void register_legacy_plugin(Plugin *plugin, GModule *module)
475 gint (*p_version_check) (gint abi_version);
476 void (*p_set_info) (PluginInfo *info);
477 void (*p_init) (GeanyData *geany_data);
478 GeanyData **p_geany_data;
479 struct LegacyRealFuncs *h;
481 #define CHECK_FUNC(__x) \
482 if (! g_module_symbol(module, "plugin_" #__x, (void *) (&p_##__x))) \
484 geany_debug("Plugin \"%s\" has no plugin_" #__x "() function - ignoring plugin!", \
485 g_module_name(module)); \
486 return; \
488 CHECK_FUNC(version_check);
489 CHECK_FUNC(set_info);
490 CHECK_FUNC(init);
491 #undef CHECK_FUNC
493 /* We must verify the version first. If the plugin has become incompatible any
494 * further actions should be considered invalid and therefore skipped. */
495 if (! plugin_check_version(plugin, p_version_check(GEANY_ABI_VERSION)))
496 return;
498 h = g_slice_new(struct LegacyRealFuncs);
500 /* Since the version check passed we can proceed with setting basic fields and
501 * calling its set_info() (which might want to call Geany functions already). */
502 g_module_symbol(module, "geany_data", (void *) &p_geany_data);
503 if (p_geany_data)
504 *p_geany_data = &geany_data;
505 /* Read plugin name, etc. name is mandatory but that's enforced in the common code. */
506 p_set_info(&plugin->info);
508 /* If all went well we can set the remaining callbacks and let it go for good. */
509 h->init = p_init;
510 g_module_symbol(module, "plugin_configure", (void *) &h->configure);
511 g_module_symbol(module, "plugin_configure_single", (void *) &plugin->configure_single);
512 g_module_symbol(module, "plugin_help", (void *) &h->help);
513 g_module_symbol(module, "plugin_cleanup", (void *) &h->cleanup);
514 /* pointer to callbacks struct can be stored directly, no wrapper necessary */
515 g_module_symbol(module, "plugin_callbacks", (void *) &plugin->cbs.callbacks);
516 if (app->debug_mode)
518 if (h->configure && plugin->configure_single)
519 g_warning("Plugin '%s' implements plugin_configure_single() unnecessarily - "
520 "only plugin_configure() will be used!",
521 plugin->info.name);
522 if (h->cleanup == NULL)
523 g_warning("Plugin '%s' has no plugin_cleanup() function - there may be memory leaks!",
524 plugin->info.name);
527 plugin->cbs.init = legacy_init;
528 plugin->cbs.cleanup = legacy_cleanup;
529 plugin->cbs.configure = h->configure ? legacy_configure : NULL;
530 plugin->cbs.help = h->help ? legacy_help : NULL;
532 plugin->flags = LOADED_OK | IS_LEGACY;
533 geany_plugin_set_data(&plugin->public, h, free_legacy_cbs);
537 static gboolean
538 plugin_load(Plugin *plugin)
540 gboolean init_ok = TRUE;
542 /* Start the plugin. Legacy plugins require additional cruft. */
543 if (PLUGIN_IS_LEGACY(plugin) && plugin->proxy == &builtin_so_proxy_plugin)
545 GeanyPlugin **p_geany_plugin;
546 PluginInfo **p_info;
547 PluginFields **plugin_fields;
548 GModule *module = plugin->proxy_data;
549 /* set these symbols before plugin_init() is called
550 * we don't set geany_data since it is set directly by plugin_new() */
551 g_module_symbol(module, "geany_plugin", (void *) &p_geany_plugin);
552 if (p_geany_plugin)
553 *p_geany_plugin = &plugin->public;
554 g_module_symbol(module, "plugin_info", (void *) &p_info);
555 if (p_info)
556 *p_info = &plugin->info;
557 g_module_symbol(module, "plugin_fields", (void *) &plugin_fields);
558 if (plugin_fields)
559 *plugin_fields = &plugin->fields;
560 read_key_group(plugin);
562 /* Legacy plugin_init() cannot fail. */
563 plugin->cbs.init(&plugin->public, plugin->cb_data);
565 /* now read any plugin-owned data that might have been set in plugin_init() */
566 if (plugin->fields.flags & PLUGIN_IS_DOCUMENT_SENSITIVE)
568 ui_add_document_sensitive(plugin->fields.menu_item);
571 else
573 init_ok = plugin->cbs.init(&plugin->public, plugin->cb_data);
576 if (! init_ok)
577 return FALSE;
579 /* new-style plugins set their callbacks in geany_load_module() */
580 if (plugin->cbs.callbacks)
581 add_callbacks(plugin, plugin->cbs.callbacks);
583 /* remember which plugins are active.
584 * keep list sorted so tools menu items and plugin preference tabs are
585 * sorted by plugin name */
586 active_plugin_list = g_list_insert_sorted(active_plugin_list, plugin, cmp_plugin_names);
587 proxied_count_inc(plugin->proxy);
589 geany_debug("Loaded: %s (%s)", plugin->filename, plugin->info.name);
590 return TRUE;
594 static gpointer plugin_load_gmodule(GeanyPlugin *proxy, GeanyPlugin *subplugin, const gchar *fname, gpointer pdata)
596 GModule *module;
597 void (*p_geany_load_module)(GeanyPlugin *);
599 g_return_val_if_fail(g_module_supported(), NULL);
600 /* Don't use G_MODULE_BIND_LAZY otherwise we can get unresolved symbols at runtime,
601 * causing a segfault. Without that flag the module will safely fail to load.
602 * G_MODULE_BIND_LOCAL also helps find undefined symbols e.g. app when it would
603 * otherwise not be detected due to the shadowing of Geany's app variable.
604 * Also without G_MODULE_BIND_LOCAL calling public functions e.g. the old info()
605 * function from a plugin will be shadowed. */
606 module = g_module_open(fname, G_MODULE_BIND_LOCAL);
607 if (!module)
609 geany_debug("Can't load plugin: %s", g_module_error());
610 return NULL;
613 /*geany_debug("Initializing plugin '%s'", plugin->info.name);*/
614 g_module_symbol(module, "geany_load_module", (void *) &p_geany_load_module);
615 if (p_geany_load_module)
617 /* set this here already so plugins can call i.e. plugin_module_make_resident()
618 * right from their geany_load_module() */
619 subplugin->priv->proxy_data = module;
621 /* This is a new style plugin. It should fill in plugin->info and then call
622 * geany_plugin_register() in its geany_load_module() to successfully load.
623 * The ABI and API checks are performed by geany_plugin_register() (i.e. by us).
624 * We check the LOADED_OK flag separately to protect us against buggy plugins
625 * who ignore the result of geany_plugin_register() and register anyway */
626 p_geany_load_module(subplugin);
628 else
630 /* This is the legacy / deprecated code path. It does roughly the same as
631 * geany_load_module() and geany_plugin_register() together for the new ones */
632 register_legacy_plugin(subplugin->priv, module);
634 /* We actually check the LOADED_OK flag later */
635 return module;
639 static void plugin_unload_gmodule(GeanyPlugin *proxy, GeanyPlugin *subplugin, gpointer load_data, gpointer pdata)
641 GModule *module = (GModule *) load_data;
643 g_return_if_fail(module != NULL);
645 if (! g_module_close(module))
646 g_warning("%s: %s", subplugin->priv->filename, g_module_error());
650 /* Load and optionally init a plugin.
651 * load_plugin decides whether the plugin's plugin_init() function should be called or not. If it is
652 * called, the plugin will be started, if not the plugin will be read only (for the list of
653 * available plugins in the plugin manager).
654 * When add_to_list is set, the plugin will be added to the plugin manager's plugin_list. */
655 static Plugin*
656 plugin_new(Plugin *proxy, const gchar *fname, gboolean load_plugin, gboolean add_to_list)
658 Plugin *plugin;
660 g_return_val_if_fail(fname, NULL);
661 g_return_val_if_fail(proxy, NULL);
663 /* find the plugin in the list of already loaded, active plugins and use it, otherwise
664 * load the module */
665 plugin = find_active_plugin_by_name(fname);
666 if (plugin != NULL)
668 geany_debug("Plugin \"%s\" already loaded.", fname);
669 if (add_to_list)
671 /* do not add to the list twice */
672 if (g_list_find(plugin_list, plugin) != NULL)
673 return NULL;
675 plugin_list = g_list_prepend(plugin_list, plugin);
677 return plugin;
680 plugin = g_new0(Plugin, 1);
681 plugin->filename = g_strdup(fname);
682 plugin->proxy = proxy;
683 plugin->public.geany_data = &geany_data;
684 plugin->public.priv = plugin;
685 /* Fields of plugin->info/funcs must to be initialized by the plugin */
686 plugin->public.info = &plugin->info;
687 plugin->public.funcs = &plugin->cbs;
688 plugin->public.proxy_funcs = &plugin->proxy_cbs;
690 if (plugin_loaded(plugin))
692 geany_debug("Plugin \"%s\" already loaded.", fname);
693 goto err;
696 /* Load plugin, this should read its name etc. It must also call
697 * geany_plugin_register() for the following PLUGIN_LOADED_OK condition */
698 plugin->proxy_data = proxy->proxy_cbs.load(&proxy->public, &plugin->public, fname, proxy->cb_data);
700 if (! PLUGIN_LOADED_OK(plugin))
702 geany_debug("Failed to load \"%s\" - ignoring plugin!", fname);
703 goto err;
706 /* The proxy assumes success, therefore we have to call unload from here
707 * on in case of errors */
708 if (EMPTY(plugin->info.name))
710 geany_debug("No plugin name set for \"%s\" - ignoring plugin!", fname);
711 goto err_unload;
714 /* cb_data_destroy() frees plugin->cb_data. If that pointer also passed to unload() afterwards
715 * then that would become a use-after-free. Disallow this combination. If a proxy
716 * needs the same pointer it must not use a destroy func but free manually in its unload(). */
717 if (plugin->proxy_data == proxy->cb_data && plugin->cb_data_destroy)
719 geany_debug("Proxy of plugin \"%s\" specified invalid data - ignoring plugin!", fname);
720 plugin->proxy_data = NULL;
721 goto err_unload;
724 if (load_plugin && !plugin_load(plugin))
726 /* Handle failing init same as failing to load for now. In future we
727 * could present a informational UI or something */
728 geany_debug("Plugin failed to initialize \"%s\" - ignoring plugin!", fname);
729 goto err_unload;
732 if (add_to_list)
733 plugin_list = g_list_prepend(plugin_list, plugin);
735 return plugin;
737 err_unload:
738 if (plugin->cb_data_destroy)
739 plugin->cb_data_destroy(plugin->cb_data);
740 proxy->proxy_cbs.unload(&proxy->public, &plugin->public, plugin->proxy_data, proxy->cb_data);
741 err:
742 g_free(plugin->filename);
743 g_free(plugin);
744 return NULL;
748 static void on_object_weak_notify(gpointer data, GObject *old_ptr)
750 Plugin *plugin = data;
751 guint i = 0;
753 g_return_if_fail(plugin && plugin->signal_ids);
755 for (i = 0; i < plugin->signal_ids->len; i++)
757 SignalConnection *sc = &g_array_index(plugin->signal_ids, SignalConnection, i);
759 if (sc->object == old_ptr)
761 g_array_remove_index_fast(plugin->signal_ids, i);
762 /* we can break the loop right after finding the first match,
763 * because we will get one notification per connected signal */
764 break;
770 /* add an object to watch for destruction, and release pointers to it when destroyed.
771 * this should only be used by plugin_signal_connect() to add a watch on
772 * the object lifetime and nuke out references to it in plugin->signal_ids */
773 void plugin_watch_object(Plugin *plugin, gpointer object)
775 g_object_weak_ref(object, on_object_weak_notify, plugin);
779 static void remove_callbacks(Plugin *plugin)
781 GArray *signal_ids = plugin->signal_ids;
782 SignalConnection *sc;
784 if (signal_ids == NULL)
785 return;
787 foreach_array(SignalConnection, sc, signal_ids)
789 g_signal_handler_disconnect(sc->object, sc->handler_id);
790 g_object_weak_unref(sc->object, on_object_weak_notify, plugin);
793 g_array_free(signal_ids, TRUE);
797 static void remove_sources(Plugin *plugin)
799 GList *item;
801 item = plugin->sources;
802 while (item != NULL)
804 GList *next = item->next; /* cache the next pointer because current item will be freed */
806 g_source_destroy(item->data);
807 item = next;
809 /* don't free the list here, it is allocated inside each source's data */
813 /* Make the GModule backing plugin resident (if it's GModule-backed at all) */
814 void plugin_make_resident(Plugin *plugin)
816 if (plugin->proxy == &builtin_so_proxy_plugin)
818 g_return_if_fail(plugin->proxy_data != NULL);
819 g_module_make_resident(plugin->proxy_data);
821 else
822 g_warning("Skipping g_module_make_resident() for non-native plugin");
826 /* Retrieve the address of a symbol sym located in plugin, if it's GModule-backed */
827 gpointer plugin_get_module_symbol(Plugin *plugin, const gchar *sym)
829 gpointer symbol;
831 if (plugin->proxy == &builtin_so_proxy_plugin)
833 g_return_val_if_fail(plugin->proxy_data != NULL, NULL);
834 if (g_module_symbol(plugin->proxy_data, sym, &symbol))
835 return symbol;
836 else
837 g_warning("Failed to locate signal handler for '%s': %s",
838 sym, g_module_error());
840 else /* TODO: Could possibly support this via a new proxy hook */
841 g_warning("Failed to locate signal handler for '%s': Not supported for non-native plugins",
842 sym);
843 return NULL;
847 static gboolean is_active_plugin(Plugin *plugin)
849 return (g_list_find(active_plugin_list, plugin) != NULL);
853 /* Clean up anything used by an active plugin */
854 static void
855 plugin_cleanup(Plugin *plugin)
857 GtkWidget *widget;
859 /* With geany_register_plugin cleanup is mandatory */
860 plugin->cbs.cleanup(&plugin->public, plugin->cb_data);
862 remove_callbacks(plugin);
863 remove_sources(plugin);
865 if (plugin->key_group)
866 keybindings_free_group(plugin->key_group);
868 widget = plugin->toolbar_separator.widget;
869 if (widget)
870 gtk_widget_destroy(widget);
872 if (!PLUGIN_HAS_LOAD_DATA(plugin) && plugin->cb_data_destroy)
874 /* If the plugin has used geany_plugin_set_data(), destroy the data here. But don't
875 * if it was already set through geany_plugin_register_full() because we couldn't call
876 * its init() anymore (not without completely reloading it anyway). */
877 plugin->cb_data_destroy(plugin->cb_data);
878 plugin->cb_data = NULL;
879 plugin->cb_data_destroy = NULL;
882 proxied_count_dec(plugin->proxy);
883 geany_debug("Unloaded: %s", plugin->filename);
887 /* Remove all plugins that proxy is a proxy for from plugin_list (and free) */
888 static void free_subplugins(Plugin *proxy)
890 GList *item;
892 item = plugin_list;
893 while (item)
895 GList *next = g_list_next(item);
896 if (proxy == ((Plugin *) item->data)->proxy)
898 /* plugin_free modifies plugin_list */
899 plugin_free((Plugin *) item->data);
901 item = next;
906 /* Returns true if the removal was successful (=> never for non-proxies) */
907 static gboolean unregister_proxy(Plugin *proxy)
909 gboolean is_proxy = FALSE;
910 GList *node;
912 /* Remove the proxy from the proxy list first. It might appear more than once (once
913 * for each extension), but if it doesn't appear at all it's not actually a proxy */
914 foreach_list_safe(node, active_proxies.head)
916 PluginProxy *p = node->data;
917 if (p->plugin == proxy)
919 is_proxy = TRUE;
920 g_queue_delete_link(&active_proxies, node);
923 return is_proxy;
927 /* Cleanup a plugin and free all resources allocated on behalf of it.
929 * If the plugin is a proxy then this also takes special care to unload all
930 * subplugin loaded through it (make sure none of them is active!) */
931 static void
932 plugin_free(Plugin *plugin)
934 Plugin *proxy;
936 g_return_if_fail(plugin);
937 g_return_if_fail(plugin->proxy);
938 g_return_if_fail(plugin->proxied_count == 0);
940 proxy = plugin->proxy;
941 /* If this a proxy remove all depending subplugins. We can assume none of them is *activated*
942 * (but potentially loaded). Note that free_subplugins() might call us through recursion */
943 if (is_active_plugin(plugin))
945 if (unregister_proxy(plugin))
946 free_subplugins(plugin);
947 plugin_cleanup(plugin);
950 active_plugin_list = g_list_remove(active_plugin_list, plugin);
951 plugin_list = g_list_remove(plugin_list, plugin);
953 /* cb_data_destroy might be plugin code and must be called before unloading the module. */
954 if (plugin->cb_data_destroy)
955 plugin->cb_data_destroy(plugin->cb_data);
956 proxy->proxy_cbs.unload(&proxy->public, &plugin->public, plugin->proxy_data, proxy->cb_data);
958 g_free(plugin->filename);
959 g_free(plugin);
963 static gchar *get_custom_plugin_path(const gchar *plugin_path_config,
964 const gchar *plugin_path_system)
966 gchar *plugin_path_custom;
968 if (EMPTY(prefs.custom_plugin_path))
969 return NULL;
971 plugin_path_custom = utils_get_locale_from_utf8(prefs.custom_plugin_path);
972 utils_tidy_path(plugin_path_custom);
974 /* check whether the custom plugin path is one of the system or user plugin paths
975 * and abort if so */
976 if (utils_str_equal(plugin_path_custom, plugin_path_config) ||
977 utils_str_equal(plugin_path_custom, plugin_path_system))
979 g_free(plugin_path_custom);
980 return NULL;
982 return plugin_path_custom;
986 /* all 3 paths Geany looks for plugins in can change (even system path on Windows)
987 * so we need to check active plugins are in the right place before loading */
988 static gboolean check_plugin_path(const gchar *fname)
990 gchar *plugin_path_config;
991 gchar *plugin_path_system;
992 gchar *plugin_path_custom;
993 gboolean ret = FALSE;
995 plugin_path_config = g_build_filename(app->configdir, "plugins", NULL);
996 if (g_str_has_prefix(fname, plugin_path_config))
997 ret = TRUE;
999 plugin_path_system = get_plugin_path();
1000 if (g_str_has_prefix(fname, plugin_path_system))
1001 ret = TRUE;
1003 plugin_path_custom = get_custom_plugin_path(plugin_path_config, plugin_path_system);
1004 if (plugin_path_custom)
1006 if (g_str_has_prefix(fname, plugin_path_custom))
1007 ret = TRUE;
1009 g_free(plugin_path_custom);
1011 g_free(plugin_path_config);
1012 g_free(plugin_path_system);
1013 return ret;
1017 /* Returns NULL if this ain't a plugin,
1018 * otherwise it returns the appropriate PluginProxy instance to load it */
1019 static PluginProxy* is_plugin(const gchar *file)
1021 GList *node;
1022 const gchar *ext;
1024 /* extract file extension to avoid g_str_has_suffix() in the loop */
1025 ext = (const gchar *)strrchr(file, '.');
1026 if (ext == NULL)
1027 return FALSE;
1028 /* ensure the dot is really part of the filename */
1029 else if (strchr(ext, G_DIR_SEPARATOR) != NULL)
1030 return FALSE;
1032 ext += 1;
1033 /* O(n*m), (m being extensions per proxy) doesn't scale very well in theory
1034 * but not a problem in practice yet */
1035 foreach_list(node, active_proxies.head)
1037 PluginProxy *proxy = node->data;
1038 if (utils_str_casecmp(ext, proxy->extension) == 0)
1040 Plugin *p = proxy->plugin;
1041 gint ret = PROXY_MATCHED;
1043 if (p->proxy_cbs.probe)
1044 ret = p->proxy_cbs.probe(&p->public, file, p->cb_data);
1045 switch (ret)
1047 case PROXY_MATCHED:
1048 return proxy;
1049 case PROXY_MATCHED|PROXY_NOLOAD:
1050 return NULL;
1051 default:
1052 if (ret != PROXY_IGNORED)
1053 g_warning("Ignoring bogus return from proxy probe!\n");
1054 continue;
1058 return NULL;
1062 /* load active plugins at startup */
1063 static void
1064 load_active_plugins(void)
1066 guint i, len, proxies;
1068 if (active_plugins_pref == NULL || (len = g_strv_length(active_plugins_pref)) == 0)
1069 return;
1071 /* If proxys are loaded we have to restart to load plugins that sort before their proxy */
1074 proxies = active_proxies.length;
1075 g_list_free_full(failed_plugins_list, (GDestroyNotify) g_free);
1076 failed_plugins_list = NULL;
1077 for (i = 0; i < len; i++)
1079 gchar *fname = active_plugins_pref[i];
1081 #ifdef G_OS_WIN32
1082 /* ensure we have canonical paths */
1083 gchar *p = fname;
1084 while ((p = strchr(p, '/')) != NULL)
1085 *p = G_DIR_SEPARATOR;
1086 #endif
1088 if (!EMPTY(fname) && g_file_test(fname, G_FILE_TEST_EXISTS))
1090 PluginProxy *proxy = NULL;
1091 if (check_plugin_path(fname))
1092 proxy = is_plugin(fname);
1093 if (proxy == NULL || plugin_new(proxy->plugin, fname, TRUE, FALSE) == NULL)
1094 failed_plugins_list = g_list_prepend(failed_plugins_list, g_strdup(fname));
1097 } while (proxies != active_proxies.length);
1101 static void
1102 load_plugins_from_path(const gchar *path)
1104 GSList *list, *item;
1105 gint count = 0;
1107 list = utils_get_file_list(path, NULL, NULL);
1109 for (item = list; item != NULL; item = g_slist_next(item))
1111 gchar *fname = g_build_filename(path, item->data, NULL);
1112 PluginProxy *proxy = is_plugin(fname);
1114 if (proxy != NULL && plugin_new(proxy->plugin, fname, FALSE, TRUE))
1115 count++;
1117 g_free(fname);
1120 g_slist_foreach(list, (GFunc) g_free, NULL);
1121 g_slist_free(list);
1123 if (count)
1124 geany_debug("Added %d plugin(s) in '%s'.", count, path);
1128 static gchar *get_plugin_path(void)
1130 return g_strdup(utils_resource_dir(RESOURCE_DIR_PLUGIN));
1134 /* See load_all_plugins(), this simply sorts items with lower hierarchy level first
1135 * (where hierarchy level == number of intermediate proxies before the builtin so loader) */
1136 static gint cmp_plugin_by_proxy(gconstpointer a, gconstpointer b)
1138 const Plugin *pa = a;
1139 const Plugin *pb = b;
1141 while (TRUE)
1143 if (pa->proxy == pb->proxy)
1144 return 0;
1145 else if (pa->proxy == &builtin_so_proxy_plugin)
1146 return -1;
1147 else if (pb->proxy == &builtin_so_proxy_plugin)
1148 return 1;
1150 pa = pa->proxy;
1151 pb = pb->proxy;
1156 /* Load (but don't initialize) all plugins for the Plugin Manager dialog */
1157 static void load_all_plugins(void)
1159 gchar *plugin_path_config;
1160 gchar *plugin_path_system;
1161 gchar *plugin_path_custom;
1163 plugin_path_config = g_build_filename(app->configdir, "plugins", NULL);
1164 plugin_path_system = get_plugin_path();
1166 /* first load plugins in ~/.config/geany/plugins/ */
1167 load_plugins_from_path(plugin_path_config);
1169 /* load plugins from a custom path */
1170 plugin_path_custom = get_custom_plugin_path(plugin_path_config, plugin_path_system);
1171 if (plugin_path_custom)
1173 load_plugins_from_path(plugin_path_custom);
1174 g_free(plugin_path_custom);
1177 /* finally load plugins from $prefix/lib/geany */
1178 load_plugins_from_path(plugin_path_system);
1180 /* It is important to sort any plugins that are proxied after their proxy because
1181 * pm_populate() needs the proxy to be loaded and active (if selected by user) in order
1182 * to properly set the value for the PLUGIN_COLUMN_CAN_UNCHECK column. The order between
1183 * sub-plugins does not matter, only between sub-plugins and their proxy, thus
1184 * sorting by hierarchy level is perfectly sufficient */
1185 plugin_list = g_list_sort(plugin_list, cmp_plugin_by_proxy);
1187 g_free(plugin_path_config);
1188 g_free(plugin_path_system);
1192 static void on_tools_menu_show(GtkWidget *menu_item, G_GNUC_UNUSED gpointer user_data)
1194 GList *item, *list = gtk_container_get_children(GTK_CONTAINER(menu_item));
1195 guint i = 0;
1196 gboolean have_plugin_menu_items = FALSE;
1198 for (item = list; item != NULL; item = g_list_next(item))
1200 if (item->data == menu_separator)
1202 if (i < g_list_length(list) - 1)
1204 have_plugin_menu_items = TRUE;
1205 break;
1208 i++;
1210 g_list_free(list);
1212 ui_widget_show_hide(menu_separator, have_plugin_menu_items);
1216 /* Calling this starts up plugin support */
1217 void plugins_load_active(void)
1219 GtkWidget *widget;
1221 want_plugins = TRUE;
1223 geany_data_init();
1225 widget = gtk_separator_menu_item_new();
1226 gtk_widget_show(widget);
1227 gtk_container_add(GTK_CONTAINER(main_widgets.tools_menu), widget);
1229 widget = gtk_menu_item_new_with_mnemonic(_("_Plugin Manager"));
1230 gtk_container_add(GTK_CONTAINER(main_widgets.tools_menu), widget);
1231 gtk_widget_show(widget);
1232 g_signal_connect(widget, "activate", G_CALLBACK(pm_show_dialog), NULL);
1234 menu_separator = gtk_separator_menu_item_new();
1235 gtk_container_add(GTK_CONTAINER(main_widgets.tools_menu), menu_separator);
1236 g_signal_connect(main_widgets.tools_menu, "show", G_CALLBACK(on_tools_menu_show), NULL);
1238 load_active_plugins();
1242 /* Update the global active plugins list so it's up-to-date when configuration
1243 * is saved. Called in response to GeanyObject's "save-settings" signal. */
1244 static void update_active_plugins_pref(void)
1246 gint i = 0;
1247 GList *list;
1248 gsize count;
1250 /* if plugins are disabled, don't clear list of active plugins */
1251 if (!want_plugins)
1252 return;
1254 count = g_list_length(active_plugin_list) + g_list_length(failed_plugins_list);
1256 g_strfreev(active_plugins_pref);
1258 if (count == 0)
1260 active_plugins_pref = NULL;
1261 return;
1264 active_plugins_pref = g_new0(gchar*, count + 1);
1266 for (list = g_list_first(active_plugin_list); list != NULL; list = list->next)
1268 Plugin *plugin = list->data;
1270 active_plugins_pref[i] = g_strdup(plugin->filename);
1271 i++;
1273 for (list = g_list_first(failed_plugins_list); list != NULL; list = list->next)
1275 const gchar *fname = list->data;
1277 active_plugins_pref[i] = g_strdup(fname);
1278 i++;
1280 active_plugins_pref[i] = NULL;
1284 /* called even if plugin support is disabled */
1285 void plugins_init(void)
1287 StashGroup *group;
1288 gchar *path;
1290 path = get_plugin_path();
1291 geany_debug("System plugin path: %s", path);
1292 g_free(path);
1294 group = stash_group_new("plugins");
1295 configuration_add_pref_group(group, TRUE);
1297 stash_group_add_toggle_button(group, &prefs.load_plugins,
1298 "load_plugins", TRUE, "check_plugins");
1299 stash_group_add_entry(group, &prefs.custom_plugin_path,
1300 "custom_plugin_path", "", "extra_plugin_path_entry");
1302 g_signal_connect(geany_object, "save-settings", G_CALLBACK(update_active_plugins_pref), NULL);
1303 stash_group_add_string_vector(group, &active_plugins_pref, "active_plugins", NULL);
1305 g_queue_push_head(&active_proxies, &builtin_so_proxy);
1309 /* Same as plugin_free(), except it does nothing for proxies-in-use, to be called on
1310 * finalize in a loop */
1311 static void plugin_free_leaf(Plugin *p)
1313 if (p->proxied_count == 0)
1314 plugin_free(p);
1318 /* called even if plugin support is disabled */
1319 void plugins_finalize(void)
1321 if (failed_plugins_list != NULL)
1323 g_list_foreach(failed_plugins_list, (GFunc) g_free, NULL);
1324 g_list_free(failed_plugins_list);
1326 /* Have to loop because proxys cannot be unloaded until after all their
1327 * plugins are unloaded as well (the second loop should should catch all the remaining ones) */
1328 while (active_plugin_list != NULL)
1329 g_list_foreach(active_plugin_list, (GFunc) plugin_free_leaf, NULL);
1331 g_strfreev(active_plugins_pref);
1335 /* Check whether there are any plugins loaded which provide a configure symbol */
1336 gboolean plugins_have_preferences(void)
1338 GList *item;
1340 if (active_plugin_list == NULL)
1341 return FALSE;
1343 foreach_list(item, active_plugin_list)
1345 Plugin *plugin = item->data;
1346 if (plugin->configure_single != NULL || plugin->cbs.configure != NULL)
1347 return TRUE;
1350 return FALSE;
1354 /* Plugin Manager */
1356 enum
1358 PLUGIN_COLUMN_CHECK = 0,
1359 PLUGIN_COLUMN_CAN_UNCHECK,
1360 PLUGIN_COLUMN_PLUGIN,
1361 PLUGIN_N_COLUMNS,
1362 PM_BUTTON_KEYBINDINGS,
1363 PM_BUTTON_CONFIGURE,
1364 PM_BUTTON_HELP
1367 typedef struct
1369 GtkWidget *dialog;
1370 GtkWidget *tree;
1371 GtkTreeStore *store;
1372 GtkWidget *filter_entry;
1373 GtkWidget *configure_button;
1374 GtkWidget *keybindings_button;
1375 GtkWidget *help_button;
1376 GtkWidget *popup_menu;
1377 GtkWidget *popup_configure_menu_item;
1378 GtkWidget *popup_keybindings_menu_item;
1379 GtkWidget *popup_help_menu_item;
1381 PluginManagerWidgets;
1383 static PluginManagerWidgets pm_widgets;
1386 static void pm_update_buttons(Plugin *p)
1388 gboolean has_configure = FALSE;
1389 gboolean has_help = FALSE;
1390 gboolean has_keybindings = FALSE;
1392 if (p != NULL && is_active_plugin(p))
1394 has_configure = p->cbs.configure || p->configure_single;
1395 has_help = p->cbs.help != NULL;
1396 has_keybindings = p->key_group && p->key_group->plugin_key_count;
1399 gtk_widget_set_sensitive(pm_widgets.configure_button, has_configure);
1400 gtk_widget_set_sensitive(pm_widgets.help_button, has_help);
1401 gtk_widget_set_sensitive(pm_widgets.keybindings_button, has_keybindings);
1403 gtk_widget_set_sensitive(pm_widgets.popup_configure_menu_item, has_configure);
1404 gtk_widget_set_sensitive(pm_widgets.popup_help_menu_item, has_help);
1405 gtk_widget_set_sensitive(pm_widgets.popup_keybindings_menu_item, has_keybindings);
1409 static void pm_selection_changed(GtkTreeSelection *selection, gpointer user_data)
1411 GtkTreeIter iter;
1412 GtkTreeModel *model;
1413 Plugin *p;
1415 if (gtk_tree_selection_get_selected(selection, &model, &iter))
1417 gtk_tree_model_get(model, &iter, PLUGIN_COLUMN_PLUGIN, &p, -1);
1419 if (p != NULL)
1420 pm_update_buttons(p);
1425 static gboolean find_iter_for_plugin(Plugin *p, GtkTreeModel *model, GtkTreeIter *iter)
1427 Plugin *pp;
1428 gboolean valid;
1430 for (valid = gtk_tree_model_get_iter_first(model, iter);
1431 valid;
1432 valid = gtk_tree_model_iter_next(model, iter))
1434 gtk_tree_model_get(model, iter, PLUGIN_COLUMN_PLUGIN, &pp, -1);
1435 if (p == pp)
1436 return TRUE;
1439 return FALSE;
1443 static void pm_populate(GtkTreeStore *store);
1446 static void pm_plugin_toggled(GtkCellRendererToggle *cell, gchar *pth, gpointer data)
1448 gboolean old_state, state;
1449 gchar *file_name;
1450 GtkTreeIter iter;
1451 GtkTreeIter store_iter;
1452 GtkTreePath *path = gtk_tree_path_new_from_string(pth);
1453 GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(pm_widgets.tree));
1454 Plugin *p;
1455 Plugin *proxy;
1456 guint prev_num_proxies;
1458 gtk_tree_model_get_iter(model, &iter, path);
1460 gtk_tree_model_get(model, &iter,
1461 PLUGIN_COLUMN_CHECK, &old_state,
1462 PLUGIN_COLUMN_PLUGIN, &p, -1);
1464 /* no plugins item */
1465 if (p == NULL)
1467 gtk_tree_path_free(path);
1468 return;
1471 gtk_tree_model_filter_convert_iter_to_child_iter(
1472 GTK_TREE_MODEL_FILTER(model), &store_iter, &iter);
1474 state = ! old_state; /* toggle the state */
1476 /* save the filename and proxy of the plugin */
1477 file_name = g_strdup(p->filename);
1478 proxy = p->proxy;
1479 prev_num_proxies = active_proxies.length;
1481 /* unload plugin module */
1482 if (!state)
1483 /* save shortcuts (only need this group, but it doesn't take long) */
1484 keybindings_write_to_file();
1486 /* plugin_new() below may cause a tree view refresh with invalid p - set to NULL */
1487 gtk_tree_store_set(pm_widgets.store, &store_iter,
1488 PLUGIN_COLUMN_PLUGIN, NULL, -1);
1489 plugin_free(p);
1491 /* reload plugin module and initialize it if item is checked */
1492 p = plugin_new(proxy, file_name, state, TRUE);
1493 if (!p)
1495 /* plugin file may no longer be on disk, or is now incompatible */
1496 gtk_tree_store_remove(pm_widgets.store, &store_iter);
1498 else
1500 if (state)
1501 keybindings_load_keyfile(); /* load shortcuts */
1503 /* update model */
1504 gtk_tree_store_set(pm_widgets.store, &store_iter,
1505 PLUGIN_COLUMN_CHECK, state,
1506 PLUGIN_COLUMN_PLUGIN, p, -1);
1508 /* set again the sensitiveness of the configure and help buttons */
1509 pm_update_buttons(p);
1511 /* Depending on the state disable the checkbox for the proxy of this plugin, and
1512 * only re-enable if the proxy is not used by any other plugin */
1513 if (p->proxy != &builtin_so_proxy_plugin)
1515 GtkTreeIter parent;
1516 gboolean can_uncheck;
1517 GtkTreePath *store_path = gtk_tree_model_filter_convert_path_to_child_path(
1518 GTK_TREE_MODEL_FILTER(model), path);
1520 g_warn_if_fail(store_path != NULL);
1521 if (gtk_tree_path_up(store_path))
1523 gtk_tree_model_get_iter(GTK_TREE_MODEL(pm_widgets.store), &parent, store_path);
1525 if (state)
1526 can_uncheck = FALSE;
1527 else
1528 can_uncheck = p->proxy->proxied_count == 0;
1530 gtk_tree_store_set(pm_widgets.store, &parent,
1531 PLUGIN_COLUMN_CAN_UNCHECK, can_uncheck, -1);
1533 gtk_tree_path_free(store_path);
1536 /* We need to find out if a proxy was added or removed because that affects the plugin list
1537 * presented by the plugin manager */
1538 if (prev_num_proxies != active_proxies.length)
1540 /* Rescan the plugin list as we now support more. Gives some "already loaded" warnings
1541 * they are unproblematic */
1542 if (prev_num_proxies < active_proxies.length)
1543 load_all_plugins();
1545 pm_populate(pm_widgets.store);
1546 gtk_tree_view_expand_row(GTK_TREE_VIEW(pm_widgets.tree), path, FALSE);
1549 gtk_tree_path_free(path);
1550 g_free(file_name);
1553 static void pm_populate(GtkTreeStore *store)
1555 GtkTreeIter iter;
1556 GList *list;
1558 gtk_tree_store_clear(store);
1559 list = g_list_first(plugin_list);
1560 if (list == NULL)
1562 gtk_tree_store_append(store, &iter, NULL);
1563 gtk_tree_store_set(store, &iter, PLUGIN_COLUMN_CHECK, FALSE,
1564 PLUGIN_COLUMN_PLUGIN, NULL, -1);
1566 else
1568 for (; list != NULL; list = list->next)
1570 Plugin *p = list->data;
1571 GtkTreeIter parent;
1573 if (p->proxy != &builtin_so_proxy_plugin
1574 && find_iter_for_plugin(p->proxy, GTK_TREE_MODEL(pm_widgets.store), &parent))
1575 gtk_tree_store_append(store, &iter, &parent);
1576 else
1577 gtk_tree_store_append(store, &iter, NULL);
1579 gtk_tree_store_set(store, &iter,
1580 PLUGIN_COLUMN_CHECK, is_active_plugin(p),
1581 PLUGIN_COLUMN_PLUGIN, p,
1582 PLUGIN_COLUMN_CAN_UNCHECK, (p->proxied_count == 0),
1583 -1);
1588 static gboolean pm_treeview_query_tooltip(GtkWidget *widget, gint x, gint y,
1589 gboolean keyboard_mode, GtkTooltip *tooltip, gpointer user_data)
1591 GtkTreeModel *model;
1592 GtkTreeIter iter;
1593 GtkTreePath *path;
1594 Plugin *p = NULL;
1595 gboolean can_uncheck = TRUE;
1597 if (! gtk_tree_view_get_tooltip_context(GTK_TREE_VIEW(widget), &x, &y, keyboard_mode,
1598 &model, &path, &iter))
1599 return FALSE;
1601 gtk_tree_model_get(model, &iter, PLUGIN_COLUMN_PLUGIN, &p, PLUGIN_COLUMN_CAN_UNCHECK, &can_uncheck, -1);
1602 if (p != NULL)
1604 gchar *prefix, *suffix, *details, *markup;
1605 const gchar *uchk;
1607 uchk = can_uncheck ?
1608 "" : _("\n<i>Other plugins depend on this. Disable them first to allow deactivation.</i>\n");
1609 /* Four allocations is less than ideal but meh */
1610 details = g_strdup_printf(_("Version:\t%s\nAuthor(s):\t%s\nFilename:\t%s"),
1611 p->info.version, p->info.author, p->filename);
1612 prefix = g_markup_printf_escaped("<b>%s</b>\n%s\n", p->info.name, p->info.description);
1613 suffix = g_markup_printf_escaped("<small><i>\n%s</i></small>", details);
1614 markup = g_strconcat(prefix, uchk, suffix, NULL);
1616 gtk_tooltip_set_markup(tooltip, markup);
1617 gtk_tree_view_set_tooltip_row(GTK_TREE_VIEW(widget), tooltip, path);
1619 g_free(details);
1620 g_free(suffix);
1621 g_free(prefix);
1622 g_free(markup);
1624 gtk_tree_path_free(path);
1626 return p != NULL;
1630 static void pm_treeview_text_cell_data_func(GtkTreeViewColumn *column, GtkCellRenderer *cell,
1631 GtkTreeModel *model, GtkTreeIter *iter, gpointer data)
1633 Plugin *p;
1635 gtk_tree_model_get(model, iter, PLUGIN_COLUMN_PLUGIN, &p, -1);
1637 if (p == NULL)
1638 g_object_set(cell, "text", _("No plugins available."), NULL);
1639 else
1641 gchar *markup = g_markup_printf_escaped("<b>%s</b>\n%s", p->info.name, p->info.description);
1643 g_object_set(cell, "markup", markup, NULL);
1644 g_free(markup);
1649 static gboolean pm_treeview_button_press_cb(GtkWidget *widget, GdkEventButton *event,
1650 G_GNUC_UNUSED gpointer user_data)
1652 if (event->button == 3)
1654 gtk_menu_popup(GTK_MENU(pm_widgets.popup_menu), NULL, NULL, NULL, NULL,
1655 event->button, event->time);
1657 return FALSE;
1661 static gint pm_tree_sort_func(GtkTreeModel *model, GtkTreeIter *a, GtkTreeIter *b,
1662 gpointer user_data)
1664 Plugin *pa, *pb;
1666 gtk_tree_model_get(model, a, PLUGIN_COLUMN_PLUGIN, &pa, -1);
1667 gtk_tree_model_get(model, b, PLUGIN_COLUMN_PLUGIN, &pb, -1);
1669 if (pa && pb)
1670 return strcmp(pa->info.name, pb->info.name);
1671 else
1672 return pa - pb;
1676 static gboolean pm_tree_search(const gchar *key, const gchar *haystack)
1678 gchar *normalized_string = NULL;
1679 gchar *normalized_key = NULL;
1680 gchar *case_normalized_string = NULL;
1681 gchar *case_normalized_key = NULL;
1682 gboolean matched = TRUE;
1684 normalized_string = g_utf8_normalize(haystack, -1, G_NORMALIZE_ALL);
1685 normalized_key = g_utf8_normalize(key, -1, G_NORMALIZE_ALL);
1687 if (normalized_string != NULL && normalized_key != NULL)
1689 GString *stripped_key;
1690 gchar **subkey, **subkeys;
1692 case_normalized_string = g_utf8_casefold(normalized_string, -1);
1693 case_normalized_key = g_utf8_casefold(normalized_key, -1);
1694 stripped_key = g_string_new(case_normalized_key);
1695 do {} while (utils_string_replace_all(stripped_key, " ", " "));
1696 subkeys = g_strsplit(stripped_key->str, " ", -1);
1697 g_string_free(stripped_key, TRUE);
1698 foreach_strv(subkey, subkeys)
1700 if (strstr(case_normalized_string, *subkey) == NULL)
1702 matched = FALSE;
1703 break;
1706 g_strfreev(subkeys);
1709 g_free(normalized_key);
1710 g_free(normalized_string);
1711 g_free(case_normalized_key);
1712 g_free(case_normalized_string);
1714 return matched;
1718 static gboolean pm_tree_filter_func(GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data)
1720 Plugin *plugin;
1721 gboolean matched;
1722 const gchar *key;
1723 gchar *haystack, *filename;
1725 gtk_tree_model_get(model, iter, PLUGIN_COLUMN_PLUGIN, &plugin, -1);
1727 if (!plugin)
1728 return FALSE;
1729 key = gtk_entry_get_text(GTK_ENTRY(pm_widgets.filter_entry));
1731 filename = g_path_get_basename(plugin->filename);
1732 haystack = g_strjoin(" ", plugin->info.name, plugin->info.description,
1733 plugin->info.author, filename, NULL);
1734 matched = pm_tree_search(key, haystack);
1735 g_free(haystack);
1736 g_free(filename);
1738 return matched;
1742 static void on_pm_tree_filter_entry_changed_cb(GtkEntry *entry, gpointer user_data)
1744 GtkTreeModel *filter_model = gtk_tree_view_get_model(GTK_TREE_VIEW(pm_widgets.tree));
1745 gtk_tree_model_filter_refilter(GTK_TREE_MODEL_FILTER(filter_model));
1749 static void on_pm_tree_filter_entry_icon_release_cb(GtkEntry *entry, GtkEntryIconPosition icon_pos,
1750 GdkEvent *event, gpointer user_data)
1752 if (event->button.button == 1 && icon_pos == GTK_ENTRY_ICON_PRIMARY)
1753 on_pm_tree_filter_entry_changed_cb(entry, user_data);
1757 static void pm_prepare_treeview(GtkWidget *tree, GtkTreeStore *store)
1759 GtkCellRenderer *text_renderer, *checkbox_renderer;
1760 GtkTreeViewColumn *column;
1761 GtkTreeModel *filter_model;
1762 GtkTreeSelection *sel;
1764 g_signal_connect(tree, "query-tooltip", G_CALLBACK(pm_treeview_query_tooltip), NULL);
1765 gtk_widget_set_has_tooltip(tree, TRUE);
1766 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree), FALSE);
1768 checkbox_renderer = gtk_cell_renderer_toggle_new();
1769 column = gtk_tree_view_column_new_with_attributes(
1770 _("Active"), checkbox_renderer,
1771 "active", PLUGIN_COLUMN_CHECK, "activatable", PLUGIN_COLUMN_CAN_UNCHECK, NULL);
1772 gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);
1773 g_signal_connect(checkbox_renderer, "toggled", G_CALLBACK(pm_plugin_toggled), NULL);
1775 text_renderer = gtk_cell_renderer_text_new();
1776 g_object_set(text_renderer, "ellipsize", PANGO_ELLIPSIZE_END, NULL);
1777 column = gtk_tree_view_column_new_with_attributes(_("Plugin"), text_renderer, NULL);
1778 gtk_tree_view_column_set_cell_data_func(column, text_renderer,
1779 pm_treeview_text_cell_data_func, NULL, NULL);
1780 gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);
1782 gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(tree), TRUE);
1783 gtk_tree_view_set_enable_search(GTK_TREE_VIEW(tree), FALSE);
1784 gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(store), PLUGIN_COLUMN_PLUGIN,
1785 pm_tree_sort_func, NULL, NULL);
1786 gtk_tree_sortable_set_sort_column_id(
1787 GTK_TREE_SORTABLE(store), PLUGIN_COLUMN_PLUGIN, GTK_SORT_ASCENDING);
1789 /* selection handling */
1790 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree));
1791 gtk_tree_selection_set_mode(sel, GTK_SELECTION_SINGLE);
1792 g_signal_connect(sel, "changed", G_CALLBACK(pm_selection_changed), NULL);
1794 g_signal_connect(tree, "button-press-event", G_CALLBACK(pm_treeview_button_press_cb), NULL);
1796 /* filter */
1797 filter_model = gtk_tree_model_filter_new(GTK_TREE_MODEL(store), NULL);
1798 gtk_tree_model_filter_set_visible_func(
1799 GTK_TREE_MODEL_FILTER(filter_model), pm_tree_filter_func, NULL, NULL);
1801 /* set model to tree view */
1802 gtk_tree_view_set_model(GTK_TREE_VIEW(tree), filter_model);
1803 g_object_unref(filter_model);
1805 pm_populate(store);
1809 static void pm_on_plugin_button_clicked(G_GNUC_UNUSED GtkButton *button, gpointer user_data)
1811 GtkTreeModel *model;
1812 GtkTreeSelection *selection;
1813 GtkTreeIter iter;
1814 Plugin *p;
1816 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(pm_widgets.tree));
1817 if (gtk_tree_selection_get_selected(selection, &model, &iter))
1819 gtk_tree_model_get(model, &iter, PLUGIN_COLUMN_PLUGIN, &p, -1);
1821 if (p != NULL)
1823 if (GPOINTER_TO_INT(user_data) == PM_BUTTON_CONFIGURE)
1824 plugin_show_configure(&p->public);
1825 else if (GPOINTER_TO_INT(user_data) == PM_BUTTON_HELP)
1826 p->cbs.help(&p->public, p->cb_data);
1827 else if (GPOINTER_TO_INT(user_data) == PM_BUTTON_KEYBINDINGS && p->key_group && p->key_group->plugin_key_count > 0)
1828 keybindings_dialog_show_prefs_scroll(p->info.name);
1834 static void
1835 free_non_active_plugin(gpointer data, gpointer user_data)
1837 Plugin *plugin = data;
1839 /* don't do anything when closing the plugin manager and it is an active plugin */
1840 if (is_active_plugin(plugin))
1841 return;
1843 plugin_free(plugin);
1847 /* Callback when plugin manager dialog closes, responses GTK_RESPONSE_CLOSE and
1848 * GTK_RESPONSE_DELETE_EVENT are treated the same. */
1849 static void pm_dialog_response(GtkDialog *dialog, gint response, gpointer user_data)
1851 switch (response)
1853 case GTK_RESPONSE_CLOSE:
1854 case GTK_RESPONSE_DELETE_EVENT:
1855 if (plugin_list != NULL)
1857 /* remove all non-active plugins from the list */
1858 g_list_foreach(plugin_list, free_non_active_plugin, NULL);
1859 g_list_free(plugin_list);
1860 plugin_list = NULL;
1862 gtk_widget_destroy(GTK_WIDGET(dialog));
1864 configuration_save();
1865 break;
1866 case PM_BUTTON_CONFIGURE:
1867 case PM_BUTTON_HELP:
1868 case PM_BUTTON_KEYBINDINGS:
1869 /* forward event to the generic handler */
1870 pm_on_plugin_button_clicked(NULL, GINT_TO_POINTER(response));
1871 break;
1876 static void pm_show_dialog(GtkMenuItem *menuitem, gpointer user_data)
1878 GtkWidget *vbox, *vbox2, *swin, *label, *menu_item, *filter_entry;
1880 /* before showing the dialog, we need to create the list of available plugins */
1881 load_all_plugins();
1883 pm_widgets.dialog = gtk_dialog_new();
1884 gtk_window_set_title(GTK_WINDOW(pm_widgets.dialog), _("Plugins"));
1885 gtk_window_set_transient_for(GTK_WINDOW(pm_widgets.dialog), GTK_WINDOW(main_widgets.window));
1886 gtk_window_set_destroy_with_parent(GTK_WINDOW(pm_widgets.dialog), TRUE);
1888 vbox = ui_dialog_vbox_new(GTK_DIALOG(pm_widgets.dialog));
1889 gtk_widget_set_name(pm_widgets.dialog, "GeanyDialog");
1890 gtk_box_set_spacing(GTK_BOX(vbox), 6);
1892 gtk_window_set_default_size(GTK_WINDOW(pm_widgets.dialog), 500, 450);
1894 pm_widgets.help_button = gtk_dialog_add_button(
1895 GTK_DIALOG(pm_widgets.dialog), GTK_STOCK_HELP, PM_BUTTON_HELP);
1896 pm_widgets.configure_button = gtk_dialog_add_button(
1897 GTK_DIALOG(pm_widgets.dialog), GTK_STOCK_PREFERENCES, PM_BUTTON_CONFIGURE);
1898 pm_widgets.keybindings_button = gtk_dialog_add_button(
1899 GTK_DIALOG(pm_widgets.dialog), _("Keybindings"), PM_BUTTON_KEYBINDINGS);
1900 gtk_dialog_add_button(GTK_DIALOG(pm_widgets.dialog), GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE);
1901 gtk_dialog_set_default_response(GTK_DIALOG(pm_widgets.dialog), GTK_RESPONSE_CLOSE);
1903 /* filter */
1904 pm_widgets.filter_entry = filter_entry = gtk_entry_new();
1905 gtk_entry_set_icon_from_stock(GTK_ENTRY(filter_entry), GTK_ENTRY_ICON_PRIMARY, GTK_STOCK_FIND);
1906 ui_entry_add_clear_icon(GTK_ENTRY(filter_entry));
1907 g_signal_connect(filter_entry, "changed", G_CALLBACK(on_pm_tree_filter_entry_changed_cb), NULL);
1908 g_signal_connect(filter_entry, "icon-release",
1909 G_CALLBACK(on_pm_tree_filter_entry_icon_release_cb), NULL);
1911 /* prepare treeview */
1912 pm_widgets.tree = gtk_tree_view_new();
1913 pm_widgets.store = gtk_tree_store_new(
1914 PLUGIN_N_COLUMNS, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_POINTER);
1915 pm_prepare_treeview(pm_widgets.tree, pm_widgets.store);
1916 gtk_tree_view_expand_all(GTK_TREE_VIEW(pm_widgets.tree));
1917 g_object_unref(pm_widgets.store);
1919 swin = gtk_scrolled_window_new(NULL, NULL);
1920 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(swin),
1921 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
1922 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(swin), GTK_SHADOW_IN);
1923 gtk_container_add(GTK_CONTAINER(swin), pm_widgets.tree);
1925 label = geany_wrap_label_new(_("Choose which plugins should be loaded at startup:"));
1927 /* plugin popup menu */
1928 pm_widgets.popup_menu = gtk_menu_new();
1930 menu_item = gtk_image_menu_item_new_from_stock(GTK_STOCK_PREFERENCES, NULL);
1931 gtk_container_add(GTK_CONTAINER(pm_widgets.popup_menu), menu_item);
1932 g_signal_connect(menu_item, "activate",
1933 G_CALLBACK(pm_on_plugin_button_clicked), GINT_TO_POINTER(PM_BUTTON_CONFIGURE));
1934 pm_widgets.popup_configure_menu_item = menu_item;
1936 menu_item = gtk_image_menu_item_new_with_mnemonic(_("Keybindings"));
1937 gtk_container_add(GTK_CONTAINER(pm_widgets.popup_menu), menu_item);
1938 g_signal_connect(menu_item, "activate",
1939 G_CALLBACK(pm_on_plugin_button_clicked), GINT_TO_POINTER(PM_BUTTON_KEYBINDINGS));
1940 pm_widgets.popup_keybindings_menu_item = menu_item;
1942 menu_item = gtk_image_menu_item_new_from_stock(GTK_STOCK_HELP, NULL);
1943 gtk_container_add(GTK_CONTAINER(pm_widgets.popup_menu), menu_item);
1944 g_signal_connect(menu_item, "activate",
1945 G_CALLBACK(pm_on_plugin_button_clicked), GINT_TO_POINTER(PM_BUTTON_HELP));
1946 pm_widgets.popup_help_menu_item = menu_item;
1948 /* put it together */
1949 vbox2 = gtk_vbox_new(FALSE, 6);
1950 gtk_box_pack_start(GTK_BOX(vbox2), label, FALSE, FALSE, 0);
1951 gtk_box_pack_start(GTK_BOX(vbox2), filter_entry, FALSE, FALSE, 0);
1952 gtk_box_pack_start(GTK_BOX(vbox2), swin, TRUE, TRUE, 0);
1954 g_signal_connect(pm_widgets.dialog, "response", G_CALLBACK(pm_dialog_response), NULL);
1956 gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
1957 gtk_widget_show_all(pm_widgets.dialog);
1958 gtk_widget_show_all(pm_widgets.popup_menu);
1960 /* set initial plugin buttons state, pass NULL as no plugin is selected by default */
1961 pm_update_buttons(NULL);
1962 gtk_widget_grab_focus(pm_widgets.filter_entry);
1966 /** Register the plugin as a proxy for other plugins
1968 * Proxy plugins register a list of file extensions and a set of callbacks that are called
1969 * appropriately. A plugin can be a proxy for multiple types of sub-plugins by handling
1970 * separate file extensions, however they must share the same set of hooks, because this
1971 * function can only be called at most once per plugin.
1973 * Each callback receives the plugin-defined data as parameter (see geany_plugin_register()). The
1974 * callbacks must be set prior to calling this, by assigning to @a plugin->proxy_funcs.
1975 * GeanyProxyFuncs::load and GeanyProxyFuncs::unload must be implemented.
1977 * Nested proxies are unsupported at this point (TODO).
1979 * @note It is entirely up to the proxy to provide access to Geany's plugin API. Native code
1980 * can naturally call Geany's API directly, for interpreted languages the proxy has to
1981 * implement some kind of bindings that the plugin can use.
1983 * @see proxy for detailed documentation and an example.
1985 * @param plugin The pointer to the plugin's GeanyPlugin instance
1986 * @param extensions A @c NULL-terminated string array of file extensions, excluding the dot.
1987 * @return @c TRUE if the proxy was successfully registered, otherwise @c FALSE
1989 * @since 1.26 (API 226)
1991 GEANY_API_SYMBOL
1992 gboolean geany_plugin_register_proxy(GeanyPlugin *plugin, const gchar **extensions)
1994 Plugin *p;
1995 const gchar **ext;
1996 PluginProxy *proxy;
1997 GList *node;
1999 g_return_val_if_fail(plugin != NULL, FALSE);
2000 g_return_val_if_fail(extensions != NULL, FALSE);
2001 g_return_val_if_fail(*extensions != NULL, FALSE);
2002 g_return_val_if_fail(plugin->proxy_funcs->load != NULL, FALSE);
2003 g_return_val_if_fail(plugin->proxy_funcs->unload != NULL, FALSE);
2005 p = plugin->priv;
2006 /* Check if this was called already. We want to reserve for the use case of calling
2007 * this again to set new supported extensions (for example, based on proxy configuration). */
2008 foreach_list(node, active_proxies.head)
2010 proxy = node->data;
2011 g_return_val_if_fail(p != proxy->plugin, FALSE);
2014 foreach_strv(ext, extensions)
2016 proxy = g_new(PluginProxy, 1);
2017 g_strlcpy(proxy->extension, *ext, sizeof(proxy->extension));
2018 proxy->plugin = p;
2019 /* prepend, so that plugins automatically override core providers for a given extension */
2020 g_queue_push_head(&active_proxies, proxy);
2023 return TRUE;
2026 #endif