Use g_*list_free_full() instead of g_*list_foreach()
[geany-mirror.git] / src / plugins.c
blobb9c2324fe70f413ad46658c068b3e25853694a49
1 /*
2 * plugins.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2007 The Geany contributors
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 /* Code to manage, load and unload plugins. */
23 #ifdef HAVE_CONFIG_H
24 # include "config.h"
25 #endif
27 #ifdef HAVE_PLUGINS
29 #include "plugins.h"
31 #include "app.h"
32 #include "dialogs.h"
33 #include "documentprivate.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 <gtk/gtk.h>
58 #include <string.h>
61 typedef struct
63 gchar *prefix;
64 GeanyDocument *document;
66 ForEachDocData;
69 GList *active_plugin_list = NULL; /* list of only actually loaded plugins, always valid */
72 static gboolean want_plugins = FALSE;
74 /* list of all available, loadable plugins, only valid as long as the plugin manager dialog is
75 * opened, afterwards it will be destroyed */
76 static GList *plugin_list = NULL;
77 static gchar **active_plugins_pref = NULL; /* list of plugin filenames to load at startup */
78 static GList *failed_plugins_list = NULL; /* plugins the user wants active but can't be used */
80 static GtkWidget *menu_separator = NULL;
82 static gchar *get_plugin_path(void);
83 static void pm_show_dialog(GtkMenuItem *menuitem, gpointer user_data);
85 typedef struct {
86 gchar extension[8];
87 Plugin *plugin; /* &builtin_so_proxy_plugin for native plugins */
88 } PluginProxy;
91 static gpointer plugin_load_gmodule(GeanyPlugin *proxy, GeanyPlugin *plugin, const gchar *filename, gpointer pdata);
92 static void plugin_unload_gmodule(GeanyPlugin *proxy, GeanyPlugin *plugin, gpointer load_data, gpointer pdata);
94 static Plugin builtin_so_proxy_plugin = {
95 .proxy_cbs = {
96 .load = plugin_load_gmodule,
97 .unload = plugin_unload_gmodule,
99 /* rest of Plugin can be NULL/0 */
102 static PluginProxy builtin_so_proxy = {
103 .extension = G_MODULE_SUFFIX,
104 .plugin = &builtin_so_proxy_plugin,
107 static GQueue active_proxies = G_QUEUE_INIT;
109 static void plugin_free(Plugin *plugin);
111 static GeanyData geany_data;
113 static void
114 geany_data_init(void)
116 GeanyData gd = {
117 app,
118 &main_widgets,
119 documents_array,
120 filetypes_array,
121 &prefs,
122 &interface_prefs,
123 &toolbar_prefs,
124 &editor_prefs,
125 &file_prefs,
126 &search_prefs,
127 &tool_prefs,
128 &template_prefs,
129 NULL, /* Remove field on next ABI break (abi-todo) */
130 filetypes_by_title,
131 geany_object,
134 geany_data = gd;
138 /* In order to have nested proxies work the count of dependent plugins must propagate up.
139 * This prevents that any plugin in the tree is unloaded while a leaf plugin is active. */
140 static void proxied_count_inc(Plugin *proxy)
144 proxy->proxied_count += 1;
145 proxy = proxy->proxy;
146 } while (proxy != NULL);
150 static void proxied_count_dec(Plugin *proxy)
152 g_warn_if_fail(proxy->proxied_count > 0);
156 proxy->proxied_count -= 1;
157 proxy = proxy->proxy;
158 } while (proxy != NULL);
162 /* Prevent the same plugin filename being loaded more than once.
163 * Note: g_module_name always returns the .so name, even when Plugin::filename is a .la file. */
164 static gboolean
165 plugin_loaded(Plugin *plugin)
167 gchar *basename_module, *basename_loaded;
168 GList *item;
170 basename_module = g_path_get_basename(plugin->filename);
171 for (item = plugin_list; item != NULL; item = g_list_next(item))
173 basename_loaded = g_path_get_basename(((Plugin*)item->data)->filename);
175 if (utils_str_equal(basename_module, basename_loaded))
177 g_free(basename_loaded);
178 g_free(basename_module);
179 return TRUE;
181 g_free(basename_loaded);
183 /* Look also through the list of active plugins. This prevents problems when we have the same
184 * plugin in libdir/geany/ AND in configdir/plugins/ and the one in libdir/geany/ is loaded
185 * as active plugin. The plugin manager list would only take the one in configdir/geany/ and
186 * the plugin manager would list both plugins. Additionally, unloading the active plugin
187 * would cause a crash. */
188 for (item = active_plugin_list; item != NULL; item = g_list_next(item))
190 basename_loaded = g_path_get_basename(((Plugin*)item->data)->filename);
192 if (utils_str_equal(basename_module, basename_loaded))
194 g_free(basename_loaded);
195 g_free(basename_module);
196 return TRUE;
198 g_free(basename_loaded);
200 g_free(basename_module);
201 return FALSE;
205 static Plugin *find_active_plugin_by_name(const gchar *filename)
207 GList *item;
209 g_return_val_if_fail(filename, FALSE);
211 for (item = active_plugin_list; item != NULL; item = g_list_next(item))
213 if (utils_str_equal(filename, ((Plugin*)item->data)->filename))
214 return item->data;
217 return NULL;
221 /* Mimics plugin_version_check() of legacy plugins for use with plugin_check_version() below */
222 #define PLUGIN_VERSION_CODE(api, abi) ((abi) != GEANY_ABI_VERSION ? -1 : (api))
224 static gboolean
225 plugin_check_version(Plugin *plugin, int plugin_version_code)
227 gboolean ret = TRUE;
228 if (plugin_version_code < 0)
230 gchar *name = g_path_get_basename(plugin->filename);
231 msgwin_status_add(_("The plugin \"%s\" is not binary compatible with this "
232 "release of Geany - please recompile it."), name);
233 geany_debug("Plugin \"%s\" is not binary compatible with this "
234 "release of Geany - recompile it.", name);
235 ret = FALSE;
236 g_free(name);
238 else if (plugin_version_code > GEANY_API_VERSION)
240 gchar *name = g_path_get_basename(plugin->filename);
241 geany_debug("Plugin \"%s\" requires a newer version of Geany (API >= v%d).",
242 name, plugin_version_code);
243 ret = FALSE;
244 g_free(name);
247 return ret;
251 static void add_callbacks(Plugin *plugin, PluginCallback *callbacks)
253 PluginCallback *cb;
254 guint i, len = 0;
256 while (TRUE)
258 cb = &callbacks[len];
259 if (!cb->signal_name || !cb->callback)
260 break;
261 len++;
263 if (len == 0)
264 return;
266 for (i = 0; i < len; i++)
268 cb = &callbacks[i];
270 /* Pass the callback data as default user_data if none was set by the plugin itself */
271 plugin_signal_connect(&plugin->public, NULL, cb->signal_name, cb->after,
272 cb->callback, cb->user_data ? cb->user_data : plugin->cb_data);
277 static gint cmp_plugin_names(gconstpointer a, gconstpointer b)
279 const Plugin *pa = a;
280 const Plugin *pb = b;
282 return strcmp(pa->info.name, pb->info.name);
286 /** Register a plugin to Geany.
288 * The plugin will show up in the plugin manager. The user can interact with
289 * it based on the functions it provides and installed GUI elements.
291 * You must initialize the info and funcs fields of @ref GeanyPlugin
292 * appropriately prior to calling this, otherwise registration will fail. For
293 * info at least a valid name must be set (possibly localized). For funcs,
294 * at least init() and cleanup() functions must be implemented and set.
296 * The return value must be checked. It may be FALSE if the plugin failed to register which can
297 * mainly happen for two reasons (future Geany versions may add new failure conditions):
298 * - Not all mandatory fields of GeanyPlugin have been set.
299 * - The ABI or API versions reported by the plugin are incompatible with the running Geany.
301 * Do not call this directly. Use GEANY_PLUGIN_REGISTER() instead which automatically
302 * handles @a api_version and @a abi_version.
304 * @param plugin The plugin provided by Geany
305 * @param api_version The API version the plugin is compiled against (pass GEANY_API_VERSION)
306 * @param min_api_version The minimum API version required by the plugin
307 * @param abi_version The exact ABI version the plugin is compiled against (pass GEANY_ABI_VERSION)
309 * @return TRUE if the plugin was successfully registered. Otherwise FALSE.
311 * @since 1.26 (API 225)
312 * @see GEANY_PLUGIN_REGISTER()
314 GEANY_API_SYMBOL
315 gboolean geany_plugin_register(GeanyPlugin *plugin, gint api_version, gint min_api_version,
316 gint abi_version)
318 Plugin *p;
319 GeanyPluginFuncs *cbs = plugin->funcs;
321 g_return_val_if_fail(plugin != NULL, FALSE);
323 p = plugin->priv;
324 /* already registered successfully */
325 g_return_val_if_fail(!PLUGIN_LOADED_OK(p), FALSE);
327 /* Prevent registering incompatible plugins. */
328 if (! plugin_check_version(p, PLUGIN_VERSION_CODE(api_version, abi_version)))
329 return FALSE;
331 /* Only init and cleanup callbacks are truly mandatory. */
332 if (! cbs->init || ! cbs->cleanup)
334 gchar *name = g_path_get_basename(p->filename);
335 geany_debug("Plugin '%s' has no %s function - ignoring plugin!", name,
336 cbs->init ? "cleanup" : "init");
337 g_free(name);
339 else
341 /* Yes, name is checked again later on, however we want return FALSE here
342 * to signal the error back to the plugin (but we don't print the message twice) */
343 if (! EMPTY(p->info.name))
344 p->flags = LOADED_OK;
347 /* If it ever becomes necessary we can save the api version in Plugin
348 * and apply compat code on a per-plugin basis, because we learn about
349 * the requested API version here. For now it's not necessary. */
351 return PLUGIN_LOADED_OK(p);
355 /** Register a plugin to Geany, with plugin-defined data.
357 * This is a variant of geany_plugin_register() that also allows to set the plugin-defined data.
358 * Refer to that function for more details on registering in general.
360 * @p pdata is the pointer going to be passed to the individual plugin callbacks
361 * of GeanyPlugin::funcs. When the plugin module is unloaded, @p free_func is invoked on
362 * @p pdata, which connects the data to the plugin's module life time.
364 * You cannot use geany_plugin_set_data() after registering with this function. Use
365 * geany_plugin_register() if you need to.
367 * Do not call this directly. Use GEANY_PLUGIN_REGISTER_FULL() instead which automatically
368 * handles @p api_version and @p abi_version.
370 * @param plugin The plugin provided by Geany.
371 * @param api_version The API version the plugin is compiled against (pass GEANY_API_VERSION).
372 * @param min_api_version The minimum API version required by the plugin.
373 * @param abi_version The exact ABI version the plugin is compiled against (pass GEANY_ABI_VERSION).
374 * @param pdata Pointer to the plugin-defined data. Must not be @c NULL.
375 * @param free_func Function used to deallocate @a pdata, may be @c NULL.
377 * @return TRUE if the plugin was successfully registered. Otherwise FALSE.
379 * @since 1.26 (API 225)
380 * @see GEANY_PLUGIN_REGISTER_FULL()
381 * @see geany_plugin_register()
383 GEANY_API_SYMBOL
384 gboolean geany_plugin_register_full(GeanyPlugin *plugin, gint api_version, gint min_api_version,
385 gint abi_version, gpointer pdata, GDestroyNotify free_func)
387 if (geany_plugin_register(plugin, api_version, min_api_version, abi_version))
389 geany_plugin_set_data(plugin, pdata, free_func);
390 /* We use LOAD_DATA to indicate that pdata cb_data was set during loading/registration
391 * as opposed to during GeanyPluginFuncs::init(). In the latter case we call free_func
392 * after GeanyPluginFuncs::cleanup() */
393 plugin->priv->flags |= LOAD_DATA;
394 return TRUE;
396 return FALSE;
399 struct LegacyRealFuncs
401 void (*init) (GeanyData *data);
402 GtkWidget* (*configure) (GtkDialog *dialog);
403 void (*help) (void);
404 void (*cleanup) (void);
407 /* Wrappers to support legacy plugins are below */
408 static gboolean legacy_init(GeanyPlugin *plugin, gpointer pdata)
410 struct LegacyRealFuncs *h = pdata;
411 h->init(plugin->geany_data);
412 return TRUE;
415 static void legacy_cleanup(GeanyPlugin *plugin, gpointer pdata)
417 struct LegacyRealFuncs *h = pdata;
418 /* Can be NULL because it's optional for legacy plugins */
419 if (h->cleanup)
420 h->cleanup();
423 static void legacy_help(GeanyPlugin *plugin, gpointer pdata)
425 struct LegacyRealFuncs *h = pdata;
426 h->help();
429 static GtkWidget *legacy_configure(GeanyPlugin *plugin, GtkDialog *parent, gpointer pdata)
431 struct LegacyRealFuncs *h = pdata;
432 return h->configure(parent);
435 static void free_legacy_cbs(gpointer data)
437 g_slice_free(struct LegacyRealFuncs, data);
440 /* This function is the equivalent of geany_plugin_register() for legacy-style
441 * plugins which we continue to load for the time being. */
442 static void register_legacy_plugin(Plugin *plugin, GModule *module)
444 gint (*p_version_check) (gint abi_version);
445 void (*p_set_info) (PluginInfo *info);
446 void (*p_init) (GeanyData *geany_data);
447 GeanyData **p_geany_data;
448 struct LegacyRealFuncs *h;
450 #define CHECK_FUNC(__x) \
451 if (! g_module_symbol(module, "plugin_" #__x, (void *) (&p_##__x))) \
453 geany_debug("Plugin \"%s\" has no plugin_" #__x "() function - ignoring plugin!", \
454 g_module_name(module)); \
455 return; \
457 CHECK_FUNC(version_check);
458 CHECK_FUNC(set_info);
459 CHECK_FUNC(init);
460 #undef CHECK_FUNC
462 /* We must verify the version first. If the plugin has become incompatible any
463 * further actions should be considered invalid and therefore skipped. */
464 if (! plugin_check_version(plugin, p_version_check(GEANY_ABI_VERSION)))
465 return;
467 h = g_slice_new(struct LegacyRealFuncs);
469 /* Since the version check passed we can proceed with setting basic fields and
470 * calling its set_info() (which might want to call Geany functions already). */
471 g_module_symbol(module, "geany_data", (void *) &p_geany_data);
472 if (p_geany_data)
473 *p_geany_data = &geany_data;
474 /* Read plugin name, etc. name is mandatory but that's enforced in the common code. */
475 p_set_info(&plugin->info);
477 /* If all went well we can set the remaining callbacks and let it go for good. */
478 h->init = p_init;
479 g_module_symbol(module, "plugin_configure", (void *) &h->configure);
480 g_module_symbol(module, "plugin_configure_single", (void *) &plugin->configure_single);
481 g_module_symbol(module, "plugin_help", (void *) &h->help);
482 g_module_symbol(module, "plugin_cleanup", (void *) &h->cleanup);
483 /* pointer to callbacks struct can be stored directly, no wrapper necessary */
484 g_module_symbol(module, "plugin_callbacks", (void *) &plugin->cbs.callbacks);
485 if (app->debug_mode)
487 if (h->configure && plugin->configure_single)
488 g_warning("Plugin '%s' implements plugin_configure_single() unnecessarily - "
489 "only plugin_configure() will be used!",
490 plugin->info.name);
491 if (h->cleanup == NULL)
492 g_warning("Plugin '%s' has no plugin_cleanup() function - there may be memory leaks!",
493 plugin->info.name);
496 plugin->cbs.init = legacy_init;
497 plugin->cbs.cleanup = legacy_cleanup;
498 plugin->cbs.configure = h->configure ? legacy_configure : NULL;
499 plugin->cbs.help = h->help ? legacy_help : NULL;
501 plugin->flags = LOADED_OK | IS_LEGACY;
502 geany_plugin_set_data(&plugin->public, h, free_legacy_cbs);
506 static gboolean
507 plugin_load(Plugin *plugin)
509 gboolean init_ok = TRUE;
511 /* Start the plugin. Legacy plugins require additional cruft. */
512 if (PLUGIN_IS_LEGACY(plugin) && plugin->proxy == &builtin_so_proxy_plugin)
514 GeanyPlugin **p_geany_plugin;
515 PluginInfo **p_info;
516 GModule *module = plugin->proxy_data;
517 /* set these symbols before plugin_init() is called
518 * we don't set geany_data since it is set directly by plugin_new() */
519 g_module_symbol(module, "geany_plugin", (void *) &p_geany_plugin);
520 if (p_geany_plugin)
521 *p_geany_plugin = &plugin->public;
522 g_module_symbol(module, "plugin_info", (void *) &p_info);
523 if (p_info)
524 *p_info = &plugin->info;
526 /* Legacy plugin_init() cannot fail. */
527 plugin->cbs.init(&plugin->public, plugin->cb_data);
529 else
531 init_ok = plugin->cbs.init(&plugin->public, plugin->cb_data);
534 if (! init_ok)
535 return FALSE;
537 /* new-style plugins set their callbacks in geany_load_module() */
538 if (plugin->cbs.callbacks)
539 add_callbacks(plugin, plugin->cbs.callbacks);
541 /* remember which plugins are active.
542 * keep list sorted so tools menu items and plugin preference tabs are
543 * sorted by plugin name */
544 active_plugin_list = g_list_insert_sorted(active_plugin_list, plugin, cmp_plugin_names);
545 proxied_count_inc(plugin->proxy);
547 geany_debug("Loaded: %s (%s)", plugin->filename, plugin->info.name);
548 return TRUE;
552 static gpointer plugin_load_gmodule(GeanyPlugin *proxy, GeanyPlugin *subplugin, const gchar *fname, gpointer pdata)
554 GModule *module;
555 void (*p_geany_load_module)(GeanyPlugin *);
557 g_return_val_if_fail(g_module_supported(), NULL);
558 /* Don't use G_MODULE_BIND_LAZY otherwise we can get unresolved symbols at runtime,
559 * causing a segfault. Without that flag the module will safely fail to load.
560 * G_MODULE_BIND_LOCAL also helps find undefined symbols e.g. app when it would
561 * otherwise not be detected due to the shadowing of Geany's app variable.
562 * Also without G_MODULE_BIND_LOCAL calling public functions e.g. the old info()
563 * function from a plugin will be shadowed. */
564 module = g_module_open(fname, G_MODULE_BIND_LOCAL);
565 if (!module)
567 geany_debug("Can't load plugin: %s", g_module_error());
568 return NULL;
571 /*geany_debug("Initializing plugin '%s'", plugin->info.name);*/
572 g_module_symbol(module, "geany_load_module", (void *) &p_geany_load_module);
573 if (p_geany_load_module)
575 /* set this here already so plugins can call i.e. plugin_module_make_resident()
576 * right from their geany_load_module() */
577 subplugin->priv->proxy_data = module;
579 /* This is a new style plugin. It should fill in plugin->info and then call
580 * geany_plugin_register() in its geany_load_module() to successfully load.
581 * The ABI and API checks are performed by geany_plugin_register() (i.e. by us).
582 * We check the LOADED_OK flag separately to protect us against buggy plugins
583 * who ignore the result of geany_plugin_register() and register anyway */
584 p_geany_load_module(subplugin);
586 else
588 /* This is the legacy / deprecated code path. It does roughly the same as
589 * geany_load_module() and geany_plugin_register() together for the new ones */
590 register_legacy_plugin(subplugin->priv, module);
592 /* We actually check the LOADED_OK flag later */
593 return module;
597 static void plugin_unload_gmodule(GeanyPlugin *proxy, GeanyPlugin *subplugin, gpointer load_data, gpointer pdata)
599 GModule *module = (GModule *) load_data;
601 g_return_if_fail(module != NULL);
603 if (! g_module_close(module))
604 g_warning("%s: %s", subplugin->priv->filename, g_module_error());
608 /* Load and optionally init a plugin.
609 * load_plugin decides whether the plugin's plugin_init() function should be called or not. If it is
610 * called, the plugin will be started, if not the plugin will be read only (for the list of
611 * available plugins in the plugin manager).
612 * When add_to_list is set, the plugin will be added to the plugin manager's plugin_list. */
613 static Plugin*
614 plugin_new(Plugin *proxy, const gchar *fname, gboolean load_plugin, gboolean add_to_list)
616 Plugin *plugin;
618 g_return_val_if_fail(fname, NULL);
619 g_return_val_if_fail(proxy, NULL);
621 /* find the plugin in the list of already loaded, active plugins and use it, otherwise
622 * load the module */
623 plugin = find_active_plugin_by_name(fname);
624 if (plugin != NULL)
626 geany_debug("Plugin \"%s\" already loaded.", fname);
627 if (add_to_list)
629 /* do not add to the list twice */
630 if (g_list_find(plugin_list, plugin) != NULL)
631 return NULL;
633 plugin_list = g_list_prepend(plugin_list, plugin);
635 return plugin;
638 plugin = g_new0(Plugin, 1);
639 plugin->filename = g_strdup(fname);
640 plugin->proxy = proxy;
641 plugin->public.geany_data = &geany_data;
642 plugin->public.priv = plugin;
643 /* Fields of plugin->info/funcs must to be initialized by the plugin */
644 plugin->public.info = &plugin->info;
645 plugin->public.funcs = &plugin->cbs;
646 plugin->public.proxy_funcs = &plugin->proxy_cbs;
648 if (plugin_loaded(plugin))
650 geany_debug("Plugin \"%s\" already loaded.", fname);
651 goto err;
654 /* Load plugin, this should read its name etc. It must also call
655 * geany_plugin_register() for the following PLUGIN_LOADED_OK condition */
656 plugin->proxy_data = proxy->proxy_cbs.load(&proxy->public, &plugin->public, fname, proxy->cb_data);
658 if (! PLUGIN_LOADED_OK(plugin))
660 geany_debug("Failed to load \"%s\" - ignoring plugin!", fname);
661 goto err;
664 /* The proxy assumes success, therefore we have to call unload from here
665 * on in case of errors */
666 if (EMPTY(plugin->info.name))
668 geany_debug("No plugin name set for \"%s\" - ignoring plugin!", fname);
669 goto err_unload;
672 /* cb_data_destroy() frees plugin->cb_data. If that pointer also passed to unload() afterwards
673 * then that would become a use-after-free. Disallow this combination. If a proxy
674 * needs the same pointer it must not use a destroy func but free manually in its unload(). */
675 if (plugin->proxy_data == proxy->cb_data && plugin->cb_data_destroy)
677 geany_debug("Proxy of plugin \"%s\" specified invalid data - ignoring plugin!", fname);
678 plugin->proxy_data = NULL;
679 goto err_unload;
682 if (load_plugin && !plugin_load(plugin))
684 /* Handle failing init same as failing to load for now. In future we
685 * could present a informational UI or something */
686 geany_debug("Plugin failed to initialize \"%s\" - ignoring plugin!", fname);
687 goto err_unload;
690 if (add_to_list)
691 plugin_list = g_list_prepend(plugin_list, plugin);
693 return plugin;
695 err_unload:
696 if (plugin->cb_data_destroy)
697 plugin->cb_data_destroy(plugin->cb_data);
698 proxy->proxy_cbs.unload(&proxy->public, &plugin->public, plugin->proxy_data, proxy->cb_data);
699 err:
700 g_free(plugin->filename);
701 g_free(plugin);
702 return NULL;
706 static void on_object_weak_notify(gpointer data, GObject *old_ptr)
708 Plugin *plugin = data;
709 guint i = 0;
711 g_return_if_fail(plugin && plugin->signal_ids);
713 for (i = 0; i < plugin->signal_ids->len; i++)
715 SignalConnection *sc = &g_array_index(plugin->signal_ids, SignalConnection, i);
717 if (sc->object == old_ptr)
719 g_array_remove_index_fast(plugin->signal_ids, i);
720 /* we can break the loop right after finding the first match,
721 * because we will get one notification per connected signal */
722 break;
728 /* add an object to watch for destruction, and release pointers to it when destroyed.
729 * this should only be used by plugin_signal_connect() to add a watch on
730 * the object lifetime and nuke out references to it in plugin->signal_ids */
731 void plugin_watch_object(Plugin *plugin, gpointer object)
733 g_object_weak_ref(object, on_object_weak_notify, plugin);
737 static void remove_callbacks(Plugin *plugin)
739 GArray *signal_ids = plugin->signal_ids;
740 SignalConnection *sc;
742 if (signal_ids == NULL)
743 return;
745 foreach_array(SignalConnection, sc, signal_ids)
747 g_signal_handler_disconnect(sc->object, sc->handler_id);
748 g_object_weak_unref(sc->object, on_object_weak_notify, plugin);
751 g_array_free(signal_ids, TRUE);
755 static void remove_sources(Plugin *plugin)
757 GList *item;
759 item = plugin->sources;
760 while (item != NULL)
762 GList *next = item->next; /* cache the next pointer because current item will be freed */
764 g_source_destroy(item->data);
765 item = next;
767 /* don't free the list here, it is allocated inside each source's data */
771 /* Make the GModule backing plugin resident (if it's GModule-backed at all) */
772 void plugin_make_resident(Plugin *plugin)
774 if (plugin->proxy == &builtin_so_proxy_plugin)
776 g_return_if_fail(plugin->proxy_data != NULL);
777 g_module_make_resident(plugin->proxy_data);
779 else
780 g_warning("Skipping g_module_make_resident() for non-native plugin");
784 /* Retrieve the address of a symbol sym located in plugin, if it's GModule-backed */
785 gpointer plugin_get_module_symbol(Plugin *plugin, const gchar *sym)
787 gpointer symbol;
789 if (plugin->proxy == &builtin_so_proxy_plugin)
791 g_return_val_if_fail(plugin->proxy_data != NULL, NULL);
792 if (g_module_symbol(plugin->proxy_data, sym, &symbol))
793 return symbol;
794 else
795 g_warning("Failed to locate signal handler for '%s': %s",
796 sym, g_module_error());
798 else /* TODO: Could possibly support this via a new proxy hook */
799 g_warning("Failed to locate signal handler for '%s': Not supported for non-native plugins",
800 sym);
801 return NULL;
805 static gboolean is_active_plugin(Plugin *plugin)
807 return (g_list_find(active_plugin_list, plugin) != NULL);
811 static void remove_each_doc_data(GQuark key_id, gpointer data, gpointer user_data)
813 const ForEachDocData *doc_data = user_data;
814 const gchar *key = g_quark_to_string(key_id);
815 if (g_str_has_prefix(key, doc_data->prefix))
816 g_datalist_remove_data(&doc_data->document->priv->data, key);
820 static void remove_doc_data(Plugin *plugin)
822 ForEachDocData data;
824 data.prefix = g_strdup_printf("geany/plugins/%s/", plugin->public.info->name);
826 for (guint i = 0; i < documents_array->len; i++)
828 GeanyDocument *doc = documents_array->pdata[i];
829 if (DOC_VALID(doc))
831 data.document = doc;
832 g_datalist_foreach(&doc->priv->data, remove_each_doc_data, &data);
836 g_free(data.prefix);
840 /* Clean up anything used by an active plugin */
841 static void
842 plugin_cleanup(Plugin *plugin)
844 GtkWidget *widget;
846 /* With geany_register_plugin cleanup is mandatory */
847 plugin->cbs.cleanup(&plugin->public, plugin->cb_data);
849 remove_doc_data(plugin);
850 remove_callbacks(plugin);
851 remove_sources(plugin);
853 if (plugin->key_group)
854 keybindings_free_group(plugin->key_group);
856 widget = plugin->toolbar_separator.widget;
857 if (widget)
858 gtk_widget_destroy(widget);
860 if (!PLUGIN_HAS_LOAD_DATA(plugin) && plugin->cb_data_destroy)
862 /* If the plugin has used geany_plugin_set_data(), destroy the data here. But don't
863 * if it was already set through geany_plugin_register_full() because we couldn't call
864 * its init() anymore (not without completely reloading it anyway). */
865 plugin->cb_data_destroy(plugin->cb_data);
866 plugin->cb_data = NULL;
867 plugin->cb_data_destroy = NULL;
870 proxied_count_dec(plugin->proxy);
871 geany_debug("Unloaded: %s", plugin->filename);
875 /* Remove all plugins that proxy is a proxy for from plugin_list (and free) */
876 static void free_subplugins(Plugin *proxy)
878 GList *item;
880 item = plugin_list;
881 while (item)
883 GList *next = g_list_next(item);
884 if (proxy == ((Plugin *) item->data)->proxy)
886 /* plugin_free modifies plugin_list */
887 plugin_free((Plugin *) item->data);
889 item = next;
894 /* Returns true if the removal was successful (=> never for non-proxies) */
895 static gboolean unregister_proxy(Plugin *proxy)
897 gboolean is_proxy = FALSE;
898 GList *node;
900 /* Remove the proxy from the proxy list first. It might appear more than once (once
901 * for each extension), but if it doesn't appear at all it's not actually a proxy */
902 foreach_list_safe(node, active_proxies.head)
904 PluginProxy *p = node->data;
905 if (p->plugin == proxy)
907 is_proxy = TRUE;
908 g_queue_delete_link(&active_proxies, node);
911 return is_proxy;
915 /* Cleanup a plugin and free all resources allocated on behalf of it.
917 * If the plugin is a proxy then this also takes special care to unload all
918 * subplugin loaded through it (make sure none of them is active!) */
919 static void
920 plugin_free(Plugin *plugin)
922 Plugin *proxy;
924 g_return_if_fail(plugin);
925 g_return_if_fail(plugin->proxy);
926 g_return_if_fail(plugin->proxied_count == 0);
928 proxy = plugin->proxy;
929 /* If this a proxy remove all depending subplugins. We can assume none of them is *activated*
930 * (but potentially loaded). Note that free_subplugins() might call us through recursion */
931 if (is_active_plugin(plugin))
933 if (unregister_proxy(plugin))
934 free_subplugins(plugin);
935 plugin_cleanup(plugin);
938 active_plugin_list = g_list_remove(active_plugin_list, plugin);
939 plugin_list = g_list_remove(plugin_list, plugin);
941 /* cb_data_destroy might be plugin code and must be called before unloading the module. */
942 if (plugin->cb_data_destroy)
943 plugin->cb_data_destroy(plugin->cb_data);
944 proxy->proxy_cbs.unload(&proxy->public, &plugin->public, plugin->proxy_data, proxy->cb_data);
946 g_free(plugin->filename);
947 g_free(plugin);
951 static gchar *get_custom_plugin_path(const gchar *plugin_path_config,
952 const gchar *plugin_path_system)
954 gchar *plugin_path_custom;
956 if (EMPTY(prefs.custom_plugin_path))
957 return NULL;
959 plugin_path_custom = utils_get_locale_from_utf8(prefs.custom_plugin_path);
960 utils_tidy_path(plugin_path_custom);
962 /* check whether the custom plugin path is one of the system or user plugin paths
963 * and abort if so */
964 if (utils_str_equal(plugin_path_custom, plugin_path_config) ||
965 utils_str_equal(plugin_path_custom, plugin_path_system))
967 g_free(plugin_path_custom);
968 return NULL;
970 return plugin_path_custom;
974 /* all 3 paths Geany looks for plugins in can change (even system path on Windows)
975 * so we need to check active plugins are in the right place before loading */
976 static gboolean check_plugin_path(const gchar *fname)
978 gchar *plugin_path_config;
979 gchar *plugin_path_system;
980 gchar *plugin_path_custom;
981 gboolean ret = FALSE;
983 plugin_path_config = g_build_filename(app->configdir, "plugins", NULL);
984 if (g_str_has_prefix(fname, plugin_path_config))
985 ret = TRUE;
987 plugin_path_system = get_plugin_path();
988 if (g_str_has_prefix(fname, plugin_path_system))
989 ret = TRUE;
991 plugin_path_custom = get_custom_plugin_path(plugin_path_config, plugin_path_system);
992 if (plugin_path_custom)
994 if (g_str_has_prefix(fname, plugin_path_custom))
995 ret = TRUE;
997 g_free(plugin_path_custom);
999 g_free(plugin_path_config);
1000 g_free(plugin_path_system);
1001 return ret;
1005 /* Returns NULL if this ain't a plugin,
1006 * otherwise it returns the appropriate PluginProxy instance to load it */
1007 static PluginProxy* is_plugin(const gchar *file)
1009 GList *node;
1010 const gchar *ext;
1012 /* extract file extension to avoid g_str_has_suffix() in the loop */
1013 ext = (const gchar *)strrchr(file, '.');
1014 if (ext == NULL)
1015 return FALSE;
1016 /* ensure the dot is really part of the filename */
1017 else if (strchr(ext, G_DIR_SEPARATOR) != NULL)
1018 return FALSE;
1020 ext += 1;
1021 /* O(n*m), (m being extensions per proxy) doesn't scale very well in theory
1022 * but not a problem in practice yet */
1023 foreach_list(node, active_proxies.head)
1025 PluginProxy *proxy = node->data;
1026 if (utils_str_casecmp(ext, proxy->extension) == 0)
1028 Plugin *p = proxy->plugin;
1029 gint ret = GEANY_PROXY_MATCH;
1031 if (p->proxy_cbs.probe)
1032 ret = p->proxy_cbs.probe(&p->public, file, p->cb_data);
1033 switch (ret)
1035 case GEANY_PROXY_MATCH:
1036 return proxy;
1037 case GEANY_PROXY_RELATED:
1038 return NULL;
1039 case GEANY_PROXY_IGNORE:
1040 continue;
1041 default:
1042 g_warning("Ignoring bogus return value '%d' from "
1043 "proxy plugin '%s' probe() function!", ret,
1044 proxy->plugin->info.name);
1045 continue;
1049 return NULL;
1053 /* load active plugins at startup */
1054 static void
1055 load_active_plugins(void)
1057 guint i, len, proxies;
1059 if (active_plugins_pref == NULL || (len = g_strv_length(active_plugins_pref)) == 0)
1060 return;
1062 /* If proxys are loaded we have to restart to load plugins that sort before their proxy */
1065 proxies = active_proxies.length;
1066 g_list_free_full(failed_plugins_list, (GDestroyNotify) g_free);
1067 failed_plugins_list = NULL;
1068 for (i = 0; i < len; i++)
1070 gchar *fname = active_plugins_pref[i];
1072 #ifdef G_OS_WIN32
1073 /* ensure we have canonical paths */
1074 gchar *p = fname;
1075 while ((p = strchr(p, '/')) != NULL)
1076 *p = G_DIR_SEPARATOR;
1077 #endif
1079 if (!EMPTY(fname) && g_file_test(fname, G_FILE_TEST_EXISTS))
1081 PluginProxy *proxy = NULL;
1082 if (check_plugin_path(fname))
1083 proxy = is_plugin(fname);
1084 if (proxy == NULL || plugin_new(proxy->plugin, fname, TRUE, FALSE) == NULL)
1085 failed_plugins_list = g_list_prepend(failed_plugins_list, g_strdup(fname));
1088 } while (proxies != active_proxies.length);
1092 static void
1093 load_plugins_from_path(const gchar *path)
1095 GSList *list, *item;
1096 gint count = 0;
1098 list = utils_get_file_list(path, NULL, NULL);
1100 for (item = list; item != NULL; item = g_slist_next(item))
1102 gchar *fname = g_build_filename(path, item->data, NULL);
1103 PluginProxy *proxy = is_plugin(fname);
1105 if (proxy != NULL && plugin_new(proxy->plugin, fname, FALSE, TRUE))
1106 count++;
1108 g_free(fname);
1111 g_slist_free_full(list, g_free);
1113 if (count)
1114 geany_debug("Added %d plugin(s) in '%s'.", count, path);
1118 static gchar *get_plugin_path(void)
1120 return g_strdup(utils_resource_dir(RESOURCE_DIR_PLUGIN));
1124 /* See load_all_plugins(), this simply sorts items with lower hierarchy level first
1125 * (where hierarchy level == number of intermediate proxies before the builtin so loader) */
1126 static gint cmp_plugin_by_proxy(gconstpointer a, gconstpointer b)
1128 const Plugin *pa = a;
1129 const Plugin *pb = b;
1131 while (TRUE)
1133 if (pa->proxy == pb->proxy)
1134 return 0;
1135 else if (pa->proxy == &builtin_so_proxy_plugin)
1136 return -1;
1137 else if (pb->proxy == &builtin_so_proxy_plugin)
1138 return 1;
1140 pa = pa->proxy;
1141 pb = pb->proxy;
1146 /* Load (but don't initialize) all plugins for the Plugin Manager dialog */
1147 static void load_all_plugins(void)
1149 gchar *plugin_path_config;
1150 gchar *plugin_path_system;
1151 gchar *plugin_path_custom;
1153 plugin_path_config = g_build_filename(app->configdir, "plugins", NULL);
1154 plugin_path_system = get_plugin_path();
1156 /* first load plugins in ~/.config/geany/plugins/ */
1157 load_plugins_from_path(plugin_path_config);
1159 /* load plugins from a custom path */
1160 plugin_path_custom = get_custom_plugin_path(plugin_path_config, plugin_path_system);
1161 if (plugin_path_custom)
1163 load_plugins_from_path(plugin_path_custom);
1164 g_free(plugin_path_custom);
1167 /* finally load plugins from $prefix/lib/geany */
1168 load_plugins_from_path(plugin_path_system);
1170 /* It is important to sort any plugins that are proxied after their proxy because
1171 * pm_populate() needs the proxy to be loaded and active (if selected by user) in order
1172 * to properly set the value for the PLUGIN_COLUMN_CAN_UNCHECK column. The order between
1173 * sub-plugins does not matter, only between sub-plugins and their proxy, thus
1174 * sorting by hierarchy level is perfectly sufficient */
1175 plugin_list = g_list_sort(plugin_list, cmp_plugin_by_proxy);
1177 g_free(plugin_path_config);
1178 g_free(plugin_path_system);
1182 static void on_tools_menu_show(GtkWidget *menu_item, G_GNUC_UNUSED gpointer user_data)
1184 GList *item, *list = gtk_container_get_children(GTK_CONTAINER(menu_item));
1185 guint i = 0;
1186 gboolean have_plugin_menu_items = FALSE;
1188 for (item = list; item != NULL; item = g_list_next(item))
1190 if (item->data == menu_separator)
1192 if (i < g_list_length(list) - 1)
1194 have_plugin_menu_items = TRUE;
1195 break;
1198 i++;
1200 g_list_free(list);
1202 ui_widget_show_hide(menu_separator, have_plugin_menu_items);
1206 /* Calling this starts up plugin support */
1207 void plugins_load_active(void)
1209 GtkWidget *widget;
1211 want_plugins = TRUE;
1213 geany_data_init();
1215 widget = gtk_separator_menu_item_new();
1216 gtk_widget_show(widget);
1217 gtk_container_add(GTK_CONTAINER(main_widgets.tools_menu), widget);
1219 widget = gtk_menu_item_new_with_mnemonic(_("_Plugin Manager"));
1220 gtk_container_add(GTK_CONTAINER(main_widgets.tools_menu), widget);
1221 gtk_widget_show(widget);
1222 g_signal_connect(widget, "activate", G_CALLBACK(pm_show_dialog), NULL);
1224 menu_separator = gtk_separator_menu_item_new();
1225 gtk_container_add(GTK_CONTAINER(main_widgets.tools_menu), menu_separator);
1226 g_signal_connect(main_widgets.tools_menu, "show", G_CALLBACK(on_tools_menu_show), NULL);
1228 load_active_plugins();
1232 /* Update the global active plugins list so it's up-to-date when configuration
1233 * is saved. Called in response to GeanyObject's "save-settings" signal. */
1234 static void update_active_plugins_pref(void)
1236 gint i = 0;
1237 GList *list;
1238 gsize count;
1240 /* if plugins are disabled, don't clear list of active plugins */
1241 if (!want_plugins)
1242 return;
1244 count = g_list_length(active_plugin_list) + g_list_length(failed_plugins_list);
1246 g_strfreev(active_plugins_pref);
1248 if (count == 0)
1250 active_plugins_pref = NULL;
1251 return;
1254 active_plugins_pref = g_new0(gchar*, count + 1);
1256 for (list = g_list_first(active_plugin_list); list != NULL; list = list->next)
1258 Plugin *plugin = list->data;
1260 active_plugins_pref[i] = g_strdup(plugin->filename);
1261 i++;
1263 for (list = g_list_first(failed_plugins_list); list != NULL; list = list->next)
1265 const gchar *fname = list->data;
1267 active_plugins_pref[i] = g_strdup(fname);
1268 i++;
1270 active_plugins_pref[i] = NULL;
1274 /* called even if plugin support is disabled */
1275 void plugins_init(void)
1277 StashGroup *group;
1278 gchar *path;
1280 path = get_plugin_path();
1281 geany_debug("System plugin path: %s", path);
1282 g_free(path);
1284 group = stash_group_new("plugins");
1285 configuration_add_session_group(group, TRUE);
1287 stash_group_add_toggle_button(group, &prefs.load_plugins,
1288 "load_plugins", TRUE, "check_plugins");
1289 stash_group_add_entry(group, &prefs.custom_plugin_path,
1290 "custom_plugin_path", "", "extra_plugin_path_entry");
1292 g_signal_connect(geany_object, "save-settings", G_CALLBACK(update_active_plugins_pref), NULL);
1293 stash_group_add_string_vector(group, &active_plugins_pref, "active_plugins", NULL);
1295 g_queue_push_head(&active_proxies, &builtin_so_proxy);
1299 /* Same as plugin_free(), except it does nothing for proxies-in-use, to be called on
1300 * finalize in a loop */
1301 static void plugin_free_leaf(Plugin *p)
1303 if (p->proxied_count == 0)
1304 plugin_free(p);
1308 /* called even if plugin support is disabled */
1309 void plugins_finalize(void)
1311 if (failed_plugins_list != NULL)
1313 g_list_free_full(failed_plugins_list, g_free);
1315 /* Have to loop because proxys cannot be unloaded until after all their
1316 * plugins are unloaded as well (the second loop should should catch all the remaining ones) */
1317 while (active_plugin_list != NULL)
1318 g_list_foreach(active_plugin_list, (GFunc) plugin_free_leaf, NULL);
1320 g_strfreev(active_plugins_pref);
1324 /* Check whether there are any plugins loaded which provide a configure symbol */
1325 gboolean plugins_have_preferences(void)
1327 GList *item;
1329 if (active_plugin_list == NULL)
1330 return FALSE;
1332 foreach_list(item, active_plugin_list)
1334 Plugin *plugin = item->data;
1335 if (plugin->configure_single != NULL || plugin->cbs.configure != NULL)
1336 return TRUE;
1339 return FALSE;
1343 /* Plugin Manager */
1345 enum
1347 PLUGIN_COLUMN_CHECK = 0,
1348 PLUGIN_COLUMN_CAN_UNCHECK,
1349 PLUGIN_COLUMN_PLUGIN,
1350 PLUGIN_N_COLUMNS,
1351 PM_BUTTON_KEYBINDINGS,
1352 PM_BUTTON_CONFIGURE,
1353 PM_BUTTON_HELP
1356 typedef struct
1358 GtkWidget *dialog;
1359 GtkWidget *tree;
1360 GtkTreeStore *store;
1361 GtkWidget *filter_entry;
1362 GtkWidget *configure_button;
1363 GtkWidget *keybindings_button;
1364 GtkWidget *help_button;
1365 GtkWidget *popup_menu;
1366 GtkWidget *popup_configure_menu_item;
1367 GtkWidget *popup_keybindings_menu_item;
1368 GtkWidget *popup_help_menu_item;
1370 PluginManagerWidgets;
1372 static PluginManagerWidgets pm_widgets;
1375 static void pm_update_buttons(Plugin *p)
1377 gboolean has_configure = FALSE;
1378 gboolean has_help = FALSE;
1379 gboolean has_keybindings = FALSE;
1381 if (p != NULL && is_active_plugin(p))
1383 has_configure = p->cbs.configure || p->configure_single;
1384 has_help = p->cbs.help != NULL;
1385 has_keybindings = p->key_group && p->key_group->plugin_key_count;
1388 gtk_widget_set_sensitive(pm_widgets.configure_button, has_configure);
1389 gtk_widget_set_sensitive(pm_widgets.help_button, has_help);
1390 gtk_widget_set_sensitive(pm_widgets.keybindings_button, has_keybindings);
1392 gtk_widget_set_sensitive(pm_widgets.popup_configure_menu_item, has_configure);
1393 gtk_widget_set_sensitive(pm_widgets.popup_help_menu_item, has_help);
1394 gtk_widget_set_sensitive(pm_widgets.popup_keybindings_menu_item, has_keybindings);
1398 static void pm_selection_changed(GtkTreeSelection *selection, gpointer user_data)
1400 GtkTreeIter iter;
1401 GtkTreeModel *model;
1402 Plugin *p;
1404 if (gtk_tree_selection_get_selected(selection, &model, &iter))
1406 gtk_tree_model_get(model, &iter, PLUGIN_COLUMN_PLUGIN, &p, -1);
1408 if (p != NULL)
1409 pm_update_buttons(p);
1414 static gboolean find_iter_for_plugin(Plugin *p, GtkTreeModel *model, GtkTreeIter *iter)
1416 Plugin *pp;
1417 gboolean valid;
1419 for (valid = gtk_tree_model_get_iter_first(model, iter);
1420 valid;
1421 valid = gtk_tree_model_iter_next(model, iter))
1423 gtk_tree_model_get(model, iter, PLUGIN_COLUMN_PLUGIN, &pp, -1);
1424 if (p == pp)
1425 return TRUE;
1428 return FALSE;
1432 static void pm_populate(GtkTreeStore *store);
1435 static void pm_plugin_toggled(GtkCellRendererToggle *cell, gchar *pth, gpointer data)
1437 gboolean old_state, state;
1438 gchar *file_name;
1439 GtkTreeIter iter;
1440 GtkTreeIter store_iter;
1441 GtkTreePath *path = gtk_tree_path_new_from_string(pth);
1442 GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(pm_widgets.tree));
1443 Plugin *p;
1444 Plugin *proxy;
1445 guint prev_num_proxies;
1447 gtk_tree_model_get_iter(model, &iter, path);
1449 gtk_tree_model_get(model, &iter,
1450 PLUGIN_COLUMN_CHECK, &old_state,
1451 PLUGIN_COLUMN_PLUGIN, &p, -1);
1453 /* no plugins item */
1454 if (p == NULL)
1456 gtk_tree_path_free(path);
1457 return;
1460 gtk_tree_model_filter_convert_iter_to_child_iter(
1461 GTK_TREE_MODEL_FILTER(model), &store_iter, &iter);
1463 state = ! old_state; /* toggle the state */
1465 /* save the filename and proxy of the plugin */
1466 file_name = g_strdup(p->filename);
1467 proxy = p->proxy;
1468 prev_num_proxies = active_proxies.length;
1470 /* unload plugin module */
1471 if (!state)
1472 /* save shortcuts (only need this group, but it doesn't take long) */
1473 keybindings_write_to_file();
1475 /* plugin_new() below may cause a tree view refresh with invalid p - set to NULL */
1476 gtk_tree_store_set(pm_widgets.store, &store_iter,
1477 PLUGIN_COLUMN_PLUGIN, NULL, -1);
1478 plugin_free(p);
1480 /* reload plugin module and initialize it if item is checked */
1481 p = plugin_new(proxy, file_name, state, TRUE);
1482 if (!p)
1484 /* plugin file may no longer be on disk, or is now incompatible */
1485 gtk_tree_store_remove(pm_widgets.store, &store_iter);
1487 else
1489 if (state)
1490 keybindings_load_keyfile(); /* load shortcuts */
1492 /* update model */
1493 gtk_tree_store_set(pm_widgets.store, &store_iter,
1494 PLUGIN_COLUMN_CHECK, state,
1495 PLUGIN_COLUMN_PLUGIN, p, -1);
1497 /* set again the sensitiveness of the configure and help buttons */
1498 pm_update_buttons(p);
1500 /* Depending on the state disable the checkbox for the proxy of this plugin, and
1501 * only re-enable if the proxy is not used by any other plugin */
1502 if (p->proxy != &builtin_so_proxy_plugin)
1504 GtkTreeIter parent;
1505 gboolean can_uncheck;
1506 GtkTreePath *store_path = gtk_tree_model_filter_convert_path_to_child_path(
1507 GTK_TREE_MODEL_FILTER(model), path);
1509 g_warn_if_fail(store_path != NULL);
1510 if (gtk_tree_path_up(store_path))
1512 gtk_tree_model_get_iter(GTK_TREE_MODEL(pm_widgets.store), &parent, store_path);
1514 if (state)
1515 can_uncheck = FALSE;
1516 else
1517 can_uncheck = p->proxy->proxied_count == 0;
1519 gtk_tree_store_set(pm_widgets.store, &parent,
1520 PLUGIN_COLUMN_CAN_UNCHECK, can_uncheck, -1);
1522 gtk_tree_path_free(store_path);
1525 /* We need to find out if a proxy was added or removed because that affects the plugin list
1526 * presented by the plugin manager */
1527 if (prev_num_proxies != active_proxies.length)
1529 /* Rescan the plugin list as we now support more. Gives some "already loaded" warnings
1530 * they are unproblematic */
1531 if (prev_num_proxies < active_proxies.length)
1532 load_all_plugins();
1534 pm_populate(pm_widgets.store);
1535 gtk_tree_view_expand_row(GTK_TREE_VIEW(pm_widgets.tree), path, FALSE);
1538 gtk_tree_path_free(path);
1539 g_free(file_name);
1542 static void pm_populate(GtkTreeStore *store)
1544 GtkTreeIter iter;
1545 GList *list;
1547 gtk_tree_store_clear(store);
1548 list = g_list_first(plugin_list);
1549 if (list == NULL)
1551 gtk_tree_store_append(store, &iter, NULL);
1552 gtk_tree_store_set(store, &iter, PLUGIN_COLUMN_CHECK, FALSE,
1553 PLUGIN_COLUMN_PLUGIN, NULL, -1);
1555 else
1557 for (; list != NULL; list = list->next)
1559 Plugin *p = list->data;
1560 GtkTreeIter parent;
1562 if (p->proxy != &builtin_so_proxy_plugin
1563 && find_iter_for_plugin(p->proxy, GTK_TREE_MODEL(pm_widgets.store), &parent))
1564 gtk_tree_store_append(store, &iter, &parent);
1565 else
1566 gtk_tree_store_append(store, &iter, NULL);
1568 gtk_tree_store_set(store, &iter,
1569 PLUGIN_COLUMN_CHECK, is_active_plugin(p),
1570 PLUGIN_COLUMN_PLUGIN, p,
1571 PLUGIN_COLUMN_CAN_UNCHECK, (p->proxied_count == 0),
1572 -1);
1577 static gboolean pm_treeview_query_tooltip(GtkWidget *widget, gint x, gint y,
1578 gboolean keyboard_mode, GtkTooltip *tooltip, gpointer user_data)
1580 GtkTreeModel *model;
1581 GtkTreeIter iter;
1582 GtkTreePath *path;
1583 Plugin *p = NULL;
1584 gboolean can_uncheck = TRUE;
1586 if (! gtk_tree_view_get_tooltip_context(GTK_TREE_VIEW(widget), &x, &y, keyboard_mode,
1587 &model, &path, &iter))
1588 return FALSE;
1590 gtk_tree_model_get(model, &iter, PLUGIN_COLUMN_PLUGIN, &p, PLUGIN_COLUMN_CAN_UNCHECK, &can_uncheck, -1);
1591 if (p != NULL)
1593 gchar *prefix, *suffix, *details, *markup;
1594 const gchar *uchk;
1596 uchk = can_uncheck ?
1597 "" : _("\n<i>Other plugins depend on this. Disable them first to allow deactivation.</i>\n");
1598 /* Four allocations is less than ideal but meh */
1599 details = g_strdup_printf(_("Version:\t%s\nAuthor(s):\t%s\nFilename:\t%s"),
1600 p->info.version, p->info.author, p->filename);
1601 prefix = g_markup_printf_escaped("<b>%s</b>\n%s\n", p->info.name, p->info.description);
1602 suffix = g_markup_printf_escaped("<small><i>\n%s</i></small>", details);
1603 markup = g_strconcat(prefix, uchk, suffix, NULL);
1605 gtk_tooltip_set_markup(tooltip, markup);
1606 gtk_tree_view_set_tooltip_row(GTK_TREE_VIEW(widget), tooltip, path);
1608 g_free(details);
1609 g_free(suffix);
1610 g_free(prefix);
1611 g_free(markup);
1613 gtk_tree_path_free(path);
1615 return p != NULL;
1619 static void pm_treeview_text_cell_data_func(GtkTreeViewColumn *column, GtkCellRenderer *cell,
1620 GtkTreeModel *model, GtkTreeIter *iter, gpointer data)
1622 Plugin *p;
1624 gtk_tree_model_get(model, iter, PLUGIN_COLUMN_PLUGIN, &p, -1);
1626 if (p == NULL)
1627 g_object_set(cell, "text", _("No plugins available."), NULL);
1628 else
1630 gchar *markup = g_markup_printf_escaped("<b>%s</b>\n%s", p->info.name, p->info.description);
1632 g_object_set(cell, "markup", markup, NULL);
1633 g_free(markup);
1638 static gboolean pm_treeview_button_press_cb(GtkWidget *widget, GdkEventButton *event,
1639 G_GNUC_UNUSED gpointer user_data)
1641 if (event->button == 3)
1643 gtk_menu_popup_at_pointer(GTK_MENU(pm_widgets.popup_menu), (GdkEvent *) event);
1645 return FALSE;
1649 static gint pm_tree_sort_func(GtkTreeModel *model, GtkTreeIter *a, GtkTreeIter *b,
1650 gpointer user_data)
1652 Plugin *pa, *pb;
1654 gtk_tree_model_get(model, a, PLUGIN_COLUMN_PLUGIN, &pa, -1);
1655 gtk_tree_model_get(model, b, PLUGIN_COLUMN_PLUGIN, &pb, -1);
1657 if (pa && pb)
1658 return strcmp(pa->info.name, pb->info.name);
1659 else
1660 return pa - pb;
1664 static gboolean pm_tree_search(const gchar *key, const gchar *haystack)
1666 gchar *normalized_string = NULL;
1667 gchar *normalized_key = NULL;
1668 gchar *case_normalized_string = NULL;
1669 gchar *case_normalized_key = NULL;
1670 gboolean matched = TRUE;
1672 normalized_string = g_utf8_normalize(haystack, -1, G_NORMALIZE_ALL);
1673 normalized_key = g_utf8_normalize(key, -1, G_NORMALIZE_ALL);
1675 if (normalized_string != NULL && normalized_key != NULL)
1677 GString *stripped_key;
1678 gchar **subkey, **subkeys;
1680 case_normalized_string = g_utf8_casefold(normalized_string, -1);
1681 case_normalized_key = g_utf8_casefold(normalized_key, -1);
1682 stripped_key = g_string_new(case_normalized_key);
1683 do {} while (utils_string_replace_all(stripped_key, " ", " "));
1684 subkeys = g_strsplit(stripped_key->str, " ", -1);
1685 g_string_free(stripped_key, TRUE);
1686 foreach_strv(subkey, subkeys)
1688 if (strstr(case_normalized_string, *subkey) == NULL)
1690 matched = FALSE;
1691 break;
1694 g_strfreev(subkeys);
1697 g_free(normalized_key);
1698 g_free(normalized_string);
1699 g_free(case_normalized_key);
1700 g_free(case_normalized_string);
1702 return matched;
1706 static gboolean pm_tree_filter_func(GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data)
1708 Plugin *plugin;
1709 gboolean matched;
1710 const gchar *key;
1711 gchar *haystack, *filename;
1713 gtk_tree_model_get(model, iter, PLUGIN_COLUMN_PLUGIN, &plugin, -1);
1715 if (!plugin)
1716 return TRUE;
1717 key = gtk_entry_get_text(GTK_ENTRY(pm_widgets.filter_entry));
1719 filename = g_path_get_basename(plugin->filename);
1720 haystack = g_strjoin(" ", plugin->info.name, plugin->info.description,
1721 plugin->info.author, filename, NULL);
1722 matched = pm_tree_search(key, haystack);
1723 g_free(haystack);
1724 g_free(filename);
1726 return matched;
1730 static void on_pm_tree_filter_entry_changed_cb(GtkEntry *entry, gpointer user_data)
1732 GtkTreeModel *filter_model = gtk_tree_view_get_model(GTK_TREE_VIEW(pm_widgets.tree));
1733 gtk_tree_model_filter_refilter(GTK_TREE_MODEL_FILTER(filter_model));
1737 static void on_pm_tree_filter_entry_icon_release_cb(GtkEntry *entry, GtkEntryIconPosition icon_pos,
1738 GdkEvent *event, gpointer user_data)
1740 if (event->button.button == 1 && icon_pos == GTK_ENTRY_ICON_PRIMARY)
1741 on_pm_tree_filter_entry_changed_cb(entry, user_data);
1745 static void pm_prepare_treeview(GtkWidget *tree, GtkTreeStore *store)
1747 GtkCellRenderer *text_renderer, *checkbox_renderer;
1748 GtkTreeViewColumn *column;
1749 GtkTreeModel *filter_model;
1750 GtkTreeSelection *sel;
1752 g_signal_connect(tree, "query-tooltip", G_CALLBACK(pm_treeview_query_tooltip), NULL);
1753 gtk_widget_set_has_tooltip(tree, TRUE);
1754 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree), FALSE);
1756 checkbox_renderer = gtk_cell_renderer_toggle_new();
1757 column = gtk_tree_view_column_new_with_attributes(
1758 _("Active"), checkbox_renderer,
1759 "active", PLUGIN_COLUMN_CHECK, "activatable", PLUGIN_COLUMN_CAN_UNCHECK, NULL);
1760 gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);
1761 g_signal_connect(checkbox_renderer, "toggled", G_CALLBACK(pm_plugin_toggled), NULL);
1763 text_renderer = gtk_cell_renderer_text_new();
1764 g_object_set(text_renderer, "ellipsize", PANGO_ELLIPSIZE_END, NULL);
1765 column = gtk_tree_view_column_new_with_attributes(_("Plugin"), text_renderer, NULL);
1766 gtk_tree_view_column_set_cell_data_func(column, text_renderer,
1767 pm_treeview_text_cell_data_func, NULL, NULL);
1768 gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);
1770 gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(tree), TRUE);
1771 gtk_tree_view_set_enable_search(GTK_TREE_VIEW(tree), FALSE);
1772 gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(store), PLUGIN_COLUMN_PLUGIN,
1773 pm_tree_sort_func, NULL, NULL);
1774 gtk_tree_sortable_set_sort_column_id(
1775 GTK_TREE_SORTABLE(store), PLUGIN_COLUMN_PLUGIN, GTK_SORT_ASCENDING);
1777 /* selection handling */
1778 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree));
1779 gtk_tree_selection_set_mode(sel, GTK_SELECTION_SINGLE);
1780 g_signal_connect(sel, "changed", G_CALLBACK(pm_selection_changed), NULL);
1782 g_signal_connect(tree, "button-press-event", G_CALLBACK(pm_treeview_button_press_cb), NULL);
1784 /* filter */
1785 filter_model = gtk_tree_model_filter_new(GTK_TREE_MODEL(store), NULL);
1786 gtk_tree_model_filter_set_visible_func(
1787 GTK_TREE_MODEL_FILTER(filter_model), pm_tree_filter_func, NULL, NULL);
1789 /* set model to tree view */
1790 gtk_tree_view_set_model(GTK_TREE_VIEW(tree), filter_model);
1791 g_object_unref(filter_model);
1793 pm_populate(store);
1797 static void pm_on_plugin_button_clicked(G_GNUC_UNUSED GtkButton *button, gpointer user_data)
1799 GtkTreeModel *model;
1800 GtkTreeSelection *selection;
1801 GtkTreeIter iter;
1802 Plugin *p;
1804 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(pm_widgets.tree));
1805 if (gtk_tree_selection_get_selected(selection, &model, &iter))
1807 gtk_tree_model_get(model, &iter, PLUGIN_COLUMN_PLUGIN, &p, -1);
1809 if (p != NULL)
1811 if (GPOINTER_TO_INT(user_data) == PM_BUTTON_CONFIGURE)
1812 plugin_show_configure(&p->public);
1813 else if (GPOINTER_TO_INT(user_data) == PM_BUTTON_HELP)
1815 g_return_if_fail(p->cbs.help != NULL);
1816 p->cbs.help(&p->public, p->cb_data);
1818 else if (GPOINTER_TO_INT(user_data) == PM_BUTTON_KEYBINDINGS && p->key_group && p->key_group->plugin_key_count > 0)
1819 keybindings_dialog_show_prefs_scroll(p->info.name);
1825 static void
1826 free_non_active_plugin(gpointer data, gpointer user_data)
1828 Plugin *plugin = data;
1830 /* don't do anything when closing the plugin manager and it is an active plugin */
1831 if (is_active_plugin(plugin))
1832 return;
1834 plugin_free(plugin);
1838 /* Callback when plugin manager dialog closes, responses GTK_RESPONSE_CLOSE and
1839 * GTK_RESPONSE_DELETE_EVENT are treated the same. */
1840 static void pm_dialog_response(GtkDialog *dialog, gint response, gpointer user_data)
1842 switch (response)
1844 case GTK_RESPONSE_CLOSE:
1845 case GTK_RESPONSE_DELETE_EVENT:
1846 if (plugin_list != NULL)
1848 /* remove all non-active plugins from the list */
1849 g_list_foreach(plugin_list, free_non_active_plugin, NULL);
1850 g_list_free(plugin_list);
1851 plugin_list = NULL;
1853 gtk_widget_destroy(GTK_WIDGET(dialog));
1854 pm_widgets.dialog = NULL;
1856 configuration_save();
1857 break;
1858 case PM_BUTTON_CONFIGURE:
1859 case PM_BUTTON_HELP:
1860 case PM_BUTTON_KEYBINDINGS:
1861 /* forward event to the generic handler */
1862 pm_on_plugin_button_clicked(NULL, GINT_TO_POINTER(response));
1863 break;
1868 static void pm_show_dialog(GtkMenuItem *menuitem, gpointer user_data)
1870 GtkWidget *vbox, *vbox2, *swin, *label, *menu_item, *filter_entry;
1872 if (pm_widgets.dialog != NULL)
1874 gtk_window_present(GTK_WINDOW(pm_widgets.dialog));
1875 return;
1878 /* before showing the dialog, we need to create the list of available plugins */
1879 load_all_plugins();
1881 pm_widgets.dialog = gtk_dialog_new();
1882 gtk_window_set_title(GTK_WINDOW(pm_widgets.dialog), _("Plugins"));
1883 gtk_window_set_transient_for(GTK_WINDOW(pm_widgets.dialog), GTK_WINDOW(main_widgets.window));
1884 gtk_window_set_destroy_with_parent(GTK_WINDOW(pm_widgets.dialog), TRUE);
1886 vbox = ui_dialog_vbox_new(GTK_DIALOG(pm_widgets.dialog));
1887 gtk_widget_set_name(pm_widgets.dialog, "GeanyDialog");
1888 gtk_box_set_spacing(GTK_BOX(vbox), 6);
1890 gtk_window_set_default_size(GTK_WINDOW(pm_widgets.dialog), 500, 450);
1892 pm_widgets.help_button = gtk_dialog_add_button(
1893 GTK_DIALOG(pm_widgets.dialog), GTK_STOCK_HELP, PM_BUTTON_HELP);
1894 pm_widgets.configure_button = gtk_dialog_add_button(
1895 GTK_DIALOG(pm_widgets.dialog), GTK_STOCK_PREFERENCES, PM_BUTTON_CONFIGURE);
1896 pm_widgets.keybindings_button = gtk_dialog_add_button(
1897 GTK_DIALOG(pm_widgets.dialog), _("Keybindings"), PM_BUTTON_KEYBINDINGS);
1898 gtk_dialog_add_button(GTK_DIALOG(pm_widgets.dialog), GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE);
1899 gtk_dialog_set_default_response(GTK_DIALOG(pm_widgets.dialog), GTK_RESPONSE_CLOSE);
1901 /* filter */
1902 pm_widgets.filter_entry = filter_entry = gtk_entry_new();
1903 gtk_entry_set_icon_from_stock(GTK_ENTRY(filter_entry), GTK_ENTRY_ICON_PRIMARY, GTK_STOCK_FIND);
1904 ui_entry_add_clear_icon(GTK_ENTRY(filter_entry));
1905 g_signal_connect(filter_entry, "changed", G_CALLBACK(on_pm_tree_filter_entry_changed_cb), NULL);
1906 g_signal_connect(filter_entry, "icon-release",
1907 G_CALLBACK(on_pm_tree_filter_entry_icon_release_cb), NULL);
1909 /* prepare treeview */
1910 pm_widgets.tree = gtk_tree_view_new();
1911 pm_widgets.store = gtk_tree_store_new(
1912 PLUGIN_N_COLUMNS, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_POINTER);
1913 pm_prepare_treeview(pm_widgets.tree, pm_widgets.store);
1914 gtk_tree_view_expand_all(GTK_TREE_VIEW(pm_widgets.tree));
1915 g_object_unref(pm_widgets.store);
1917 swin = gtk_scrolled_window_new(NULL, NULL);
1918 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(swin),
1919 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
1920 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(swin), GTK_SHADOW_IN);
1921 gtk_container_add(GTK_CONTAINER(swin), pm_widgets.tree);
1923 label = geany_wrap_label_new(_("Choose which plugins should be loaded at startup:"));
1925 /* plugin popup menu */
1926 pm_widgets.popup_menu = gtk_menu_new();
1928 menu_item = gtk_image_menu_item_new_from_stock(GTK_STOCK_PREFERENCES, NULL);
1929 gtk_container_add(GTK_CONTAINER(pm_widgets.popup_menu), menu_item);
1930 g_signal_connect(menu_item, "activate",
1931 G_CALLBACK(pm_on_plugin_button_clicked), GINT_TO_POINTER(PM_BUTTON_CONFIGURE));
1932 pm_widgets.popup_configure_menu_item = menu_item;
1934 menu_item = gtk_image_menu_item_new_with_mnemonic(_("Keybindings"));
1935 gtk_container_add(GTK_CONTAINER(pm_widgets.popup_menu), menu_item);
1936 g_signal_connect(menu_item, "activate",
1937 G_CALLBACK(pm_on_plugin_button_clicked), GINT_TO_POINTER(PM_BUTTON_KEYBINDINGS));
1938 pm_widgets.popup_keybindings_menu_item = menu_item;
1940 menu_item = gtk_image_menu_item_new_from_stock(GTK_STOCK_HELP, NULL);
1941 gtk_container_add(GTK_CONTAINER(pm_widgets.popup_menu), menu_item);
1942 g_signal_connect(menu_item, "activate",
1943 G_CALLBACK(pm_on_plugin_button_clicked), GINT_TO_POINTER(PM_BUTTON_HELP));
1944 pm_widgets.popup_help_menu_item = menu_item;
1946 /* put it together */
1947 vbox2 = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
1948 gtk_box_pack_start(GTK_BOX(vbox2), label, FALSE, FALSE, 0);
1949 gtk_box_pack_start(GTK_BOX(vbox2), filter_entry, FALSE, FALSE, 0);
1950 gtk_box_pack_start(GTK_BOX(vbox2), swin, TRUE, TRUE, 0);
1952 g_signal_connect(pm_widgets.dialog, "response", G_CALLBACK(pm_dialog_response), NULL);
1954 gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
1955 gtk_widget_show_all(pm_widgets.dialog);
1956 gtk_widget_show_all(pm_widgets.popup_menu);
1958 /* set initial plugin buttons state, pass NULL as no plugin is selected by default */
1959 pm_update_buttons(NULL);
1960 gtk_widget_grab_focus(pm_widgets.filter_entry);
1964 /** Register the plugin as a proxy for other plugins
1966 * Proxy plugins register a list of file extensions and a set of callbacks that are called
1967 * appropriately. A plugin can be a proxy for multiple types of sub-plugins by handling
1968 * separate file extensions, however they must share the same set of hooks, because this
1969 * function can only be called at most once per plugin.
1971 * Each callback receives the plugin-defined data as parameter (see geany_plugin_register()). The
1972 * callbacks must be set prior to calling this, by assigning to @a plugin->proxy_funcs.
1973 * GeanyProxyFuncs::load and GeanyProxyFuncs::unload must be implemented.
1975 * Nested proxies are unsupported at this point (TODO).
1977 * @note It is entirely up to the proxy to provide access to Geany's plugin API. Native code
1978 * can naturally call Geany's API directly, for interpreted languages the proxy has to
1979 * implement some kind of bindings that the plugin can use.
1981 * @see proxy for detailed documentation and an example.
1983 * @param plugin The pointer to the plugin's GeanyPlugin instance
1984 * @param extensions A @c NULL-terminated string array of file extensions, excluding the dot.
1985 * @return @c TRUE if the proxy was successfully registered, otherwise @c FALSE
1987 * @since 1.26 (API 226)
1989 GEANY_API_SYMBOL
1990 gboolean geany_plugin_register_proxy(GeanyPlugin *plugin, const gchar **extensions)
1992 Plugin *p;
1993 const gchar **ext;
1994 PluginProxy *proxy;
1995 GList *node;
1997 g_return_val_if_fail(plugin != NULL, FALSE);
1998 g_return_val_if_fail(extensions != NULL, FALSE);
1999 g_return_val_if_fail(*extensions != NULL, FALSE);
2000 g_return_val_if_fail(plugin->proxy_funcs->load != NULL, FALSE);
2001 g_return_val_if_fail(plugin->proxy_funcs->unload != NULL, FALSE);
2003 p = plugin->priv;
2004 /* Check if this was called already. We want to reserve for the use case of calling
2005 * this again to set new supported extensions (for example, based on proxy configuration). */
2006 foreach_list(node, active_proxies.head)
2008 proxy = node->data;
2009 g_return_val_if_fail(p != proxy->plugin, FALSE);
2012 foreach_strv(ext, extensions)
2014 if (**ext == '.')
2016 g_warning(_("Proxy plugin '%s' extension '%s' starts with a dot. "
2017 "Please fix your proxy plugin."), p->info.name, *ext);
2020 proxy = g_new(PluginProxy, 1);
2021 g_strlcpy(proxy->extension, *ext, sizeof(proxy->extension));
2022 proxy->plugin = p;
2023 /* prepend, so that plugins automatically override core providers for a given extension */
2024 g_queue_push_head(&active_proxies, proxy);
2027 return TRUE;
2030 #endif