Pass the event to gtk_menu_popup_at_pointer() when possible
[geany-mirror.git] / src / plugins.c
blob8545b18faf2e0b6bad61357f278839780b54dca1
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_foreach(list, (GFunc) g_free, NULL);
1112 g_slist_free(list);
1114 if (count)
1115 geany_debug("Added %d plugin(s) in '%s'.", count, path);
1119 static gchar *get_plugin_path(void)
1121 return g_strdup(utils_resource_dir(RESOURCE_DIR_PLUGIN));
1125 /* See load_all_plugins(), this simply sorts items with lower hierarchy level first
1126 * (where hierarchy level == number of intermediate proxies before the builtin so loader) */
1127 static gint cmp_plugin_by_proxy(gconstpointer a, gconstpointer b)
1129 const Plugin *pa = a;
1130 const Plugin *pb = b;
1132 while (TRUE)
1134 if (pa->proxy == pb->proxy)
1135 return 0;
1136 else if (pa->proxy == &builtin_so_proxy_plugin)
1137 return -1;
1138 else if (pb->proxy == &builtin_so_proxy_plugin)
1139 return 1;
1141 pa = pa->proxy;
1142 pb = pb->proxy;
1147 /* Load (but don't initialize) all plugins for the Plugin Manager dialog */
1148 static void load_all_plugins(void)
1150 gchar *plugin_path_config;
1151 gchar *plugin_path_system;
1152 gchar *plugin_path_custom;
1154 plugin_path_config = g_build_filename(app->configdir, "plugins", NULL);
1155 plugin_path_system = get_plugin_path();
1157 /* first load plugins in ~/.config/geany/plugins/ */
1158 load_plugins_from_path(plugin_path_config);
1160 /* load plugins from a custom path */
1161 plugin_path_custom = get_custom_plugin_path(plugin_path_config, plugin_path_system);
1162 if (plugin_path_custom)
1164 load_plugins_from_path(plugin_path_custom);
1165 g_free(plugin_path_custom);
1168 /* finally load plugins from $prefix/lib/geany */
1169 load_plugins_from_path(plugin_path_system);
1171 /* It is important to sort any plugins that are proxied after their proxy because
1172 * pm_populate() needs the proxy to be loaded and active (if selected by user) in order
1173 * to properly set the value for the PLUGIN_COLUMN_CAN_UNCHECK column. The order between
1174 * sub-plugins does not matter, only between sub-plugins and their proxy, thus
1175 * sorting by hierarchy level is perfectly sufficient */
1176 plugin_list = g_list_sort(plugin_list, cmp_plugin_by_proxy);
1178 g_free(plugin_path_config);
1179 g_free(plugin_path_system);
1183 static void on_tools_menu_show(GtkWidget *menu_item, G_GNUC_UNUSED gpointer user_data)
1185 GList *item, *list = gtk_container_get_children(GTK_CONTAINER(menu_item));
1186 guint i = 0;
1187 gboolean have_plugin_menu_items = FALSE;
1189 for (item = list; item != NULL; item = g_list_next(item))
1191 if (item->data == menu_separator)
1193 if (i < g_list_length(list) - 1)
1195 have_plugin_menu_items = TRUE;
1196 break;
1199 i++;
1201 g_list_free(list);
1203 ui_widget_show_hide(menu_separator, have_plugin_menu_items);
1207 /* Calling this starts up plugin support */
1208 void plugins_load_active(void)
1210 GtkWidget *widget;
1212 want_plugins = TRUE;
1214 geany_data_init();
1216 widget = gtk_separator_menu_item_new();
1217 gtk_widget_show(widget);
1218 gtk_container_add(GTK_CONTAINER(main_widgets.tools_menu), widget);
1220 widget = gtk_menu_item_new_with_mnemonic(_("_Plugin Manager"));
1221 gtk_container_add(GTK_CONTAINER(main_widgets.tools_menu), widget);
1222 gtk_widget_show(widget);
1223 g_signal_connect(widget, "activate", G_CALLBACK(pm_show_dialog), NULL);
1225 menu_separator = gtk_separator_menu_item_new();
1226 gtk_container_add(GTK_CONTAINER(main_widgets.tools_menu), menu_separator);
1227 g_signal_connect(main_widgets.tools_menu, "show", G_CALLBACK(on_tools_menu_show), NULL);
1229 load_active_plugins();
1233 /* Update the global active plugins list so it's up-to-date when configuration
1234 * is saved. Called in response to GeanyObject's "save-settings" signal. */
1235 static void update_active_plugins_pref(void)
1237 gint i = 0;
1238 GList *list;
1239 gsize count;
1241 /* if plugins are disabled, don't clear list of active plugins */
1242 if (!want_plugins)
1243 return;
1245 count = g_list_length(active_plugin_list) + g_list_length(failed_plugins_list);
1247 g_strfreev(active_plugins_pref);
1249 if (count == 0)
1251 active_plugins_pref = NULL;
1252 return;
1255 active_plugins_pref = g_new0(gchar*, count + 1);
1257 for (list = g_list_first(active_plugin_list); list != NULL; list = list->next)
1259 Plugin *plugin = list->data;
1261 active_plugins_pref[i] = g_strdup(plugin->filename);
1262 i++;
1264 for (list = g_list_first(failed_plugins_list); list != NULL; list = list->next)
1266 const gchar *fname = list->data;
1268 active_plugins_pref[i] = g_strdup(fname);
1269 i++;
1271 active_plugins_pref[i] = NULL;
1275 /* called even if plugin support is disabled */
1276 void plugins_init(void)
1278 StashGroup *group;
1279 gchar *path;
1281 path = get_plugin_path();
1282 geany_debug("System plugin path: %s", path);
1283 g_free(path);
1285 group = stash_group_new("plugins");
1286 configuration_add_session_group(group, TRUE);
1288 stash_group_add_toggle_button(group, &prefs.load_plugins,
1289 "load_plugins", TRUE, "check_plugins");
1290 stash_group_add_entry(group, &prefs.custom_plugin_path,
1291 "custom_plugin_path", "", "extra_plugin_path_entry");
1293 g_signal_connect(geany_object, "save-settings", G_CALLBACK(update_active_plugins_pref), NULL);
1294 stash_group_add_string_vector(group, &active_plugins_pref, "active_plugins", NULL);
1296 g_queue_push_head(&active_proxies, &builtin_so_proxy);
1300 /* Same as plugin_free(), except it does nothing for proxies-in-use, to be called on
1301 * finalize in a loop */
1302 static void plugin_free_leaf(Plugin *p)
1304 if (p->proxied_count == 0)
1305 plugin_free(p);
1309 /* called even if plugin support is disabled */
1310 void plugins_finalize(void)
1312 if (failed_plugins_list != NULL)
1314 g_list_foreach(failed_plugins_list, (GFunc) g_free, NULL);
1315 g_list_free(failed_plugins_list);
1317 /* Have to loop because proxys cannot be unloaded until after all their
1318 * plugins are unloaded as well (the second loop should should catch all the remaining ones) */
1319 while (active_plugin_list != NULL)
1320 g_list_foreach(active_plugin_list, (GFunc) plugin_free_leaf, NULL);
1322 g_strfreev(active_plugins_pref);
1326 /* Check whether there are any plugins loaded which provide a configure symbol */
1327 gboolean plugins_have_preferences(void)
1329 GList *item;
1331 if (active_plugin_list == NULL)
1332 return FALSE;
1334 foreach_list(item, active_plugin_list)
1336 Plugin *plugin = item->data;
1337 if (plugin->configure_single != NULL || plugin->cbs.configure != NULL)
1338 return TRUE;
1341 return FALSE;
1345 /* Plugin Manager */
1347 enum
1349 PLUGIN_COLUMN_CHECK = 0,
1350 PLUGIN_COLUMN_CAN_UNCHECK,
1351 PLUGIN_COLUMN_PLUGIN,
1352 PLUGIN_N_COLUMNS,
1353 PM_BUTTON_KEYBINDINGS,
1354 PM_BUTTON_CONFIGURE,
1355 PM_BUTTON_HELP
1358 typedef struct
1360 GtkWidget *dialog;
1361 GtkWidget *tree;
1362 GtkTreeStore *store;
1363 GtkWidget *filter_entry;
1364 GtkWidget *configure_button;
1365 GtkWidget *keybindings_button;
1366 GtkWidget *help_button;
1367 GtkWidget *popup_menu;
1368 GtkWidget *popup_configure_menu_item;
1369 GtkWidget *popup_keybindings_menu_item;
1370 GtkWidget *popup_help_menu_item;
1372 PluginManagerWidgets;
1374 static PluginManagerWidgets pm_widgets;
1377 static void pm_update_buttons(Plugin *p)
1379 gboolean has_configure = FALSE;
1380 gboolean has_help = FALSE;
1381 gboolean has_keybindings = FALSE;
1383 if (p != NULL && is_active_plugin(p))
1385 has_configure = p->cbs.configure || p->configure_single;
1386 has_help = p->cbs.help != NULL;
1387 has_keybindings = p->key_group && p->key_group->plugin_key_count;
1390 gtk_widget_set_sensitive(pm_widgets.configure_button, has_configure);
1391 gtk_widget_set_sensitive(pm_widgets.help_button, has_help);
1392 gtk_widget_set_sensitive(pm_widgets.keybindings_button, has_keybindings);
1394 gtk_widget_set_sensitive(pm_widgets.popup_configure_menu_item, has_configure);
1395 gtk_widget_set_sensitive(pm_widgets.popup_help_menu_item, has_help);
1396 gtk_widget_set_sensitive(pm_widgets.popup_keybindings_menu_item, has_keybindings);
1400 static void pm_selection_changed(GtkTreeSelection *selection, gpointer user_data)
1402 GtkTreeIter iter;
1403 GtkTreeModel *model;
1404 Plugin *p;
1406 if (gtk_tree_selection_get_selected(selection, &model, &iter))
1408 gtk_tree_model_get(model, &iter, PLUGIN_COLUMN_PLUGIN, &p, -1);
1410 if (p != NULL)
1411 pm_update_buttons(p);
1416 static gboolean find_iter_for_plugin(Plugin *p, GtkTreeModel *model, GtkTreeIter *iter)
1418 Plugin *pp;
1419 gboolean valid;
1421 for (valid = gtk_tree_model_get_iter_first(model, iter);
1422 valid;
1423 valid = gtk_tree_model_iter_next(model, iter))
1425 gtk_tree_model_get(model, iter, PLUGIN_COLUMN_PLUGIN, &pp, -1);
1426 if (p == pp)
1427 return TRUE;
1430 return FALSE;
1434 static void pm_populate(GtkTreeStore *store);
1437 static void pm_plugin_toggled(GtkCellRendererToggle *cell, gchar *pth, gpointer data)
1439 gboolean old_state, state;
1440 gchar *file_name;
1441 GtkTreeIter iter;
1442 GtkTreeIter store_iter;
1443 GtkTreePath *path = gtk_tree_path_new_from_string(pth);
1444 GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(pm_widgets.tree));
1445 Plugin *p;
1446 Plugin *proxy;
1447 guint prev_num_proxies;
1449 gtk_tree_model_get_iter(model, &iter, path);
1451 gtk_tree_model_get(model, &iter,
1452 PLUGIN_COLUMN_CHECK, &old_state,
1453 PLUGIN_COLUMN_PLUGIN, &p, -1);
1455 /* no plugins item */
1456 if (p == NULL)
1458 gtk_tree_path_free(path);
1459 return;
1462 gtk_tree_model_filter_convert_iter_to_child_iter(
1463 GTK_TREE_MODEL_FILTER(model), &store_iter, &iter);
1465 state = ! old_state; /* toggle the state */
1467 /* save the filename and proxy of the plugin */
1468 file_name = g_strdup(p->filename);
1469 proxy = p->proxy;
1470 prev_num_proxies = active_proxies.length;
1472 /* unload plugin module */
1473 if (!state)
1474 /* save shortcuts (only need this group, but it doesn't take long) */
1475 keybindings_write_to_file();
1477 /* plugin_new() below may cause a tree view refresh with invalid p - set to NULL */
1478 gtk_tree_store_set(pm_widgets.store, &store_iter,
1479 PLUGIN_COLUMN_PLUGIN, NULL, -1);
1480 plugin_free(p);
1482 /* reload plugin module and initialize it if item is checked */
1483 p = plugin_new(proxy, file_name, state, TRUE);
1484 if (!p)
1486 /* plugin file may no longer be on disk, or is now incompatible */
1487 gtk_tree_store_remove(pm_widgets.store, &store_iter);
1489 else
1491 if (state)
1492 keybindings_load_keyfile(); /* load shortcuts */
1494 /* update model */
1495 gtk_tree_store_set(pm_widgets.store, &store_iter,
1496 PLUGIN_COLUMN_CHECK, state,
1497 PLUGIN_COLUMN_PLUGIN, p, -1);
1499 /* set again the sensitiveness of the configure and help buttons */
1500 pm_update_buttons(p);
1502 /* Depending on the state disable the checkbox for the proxy of this plugin, and
1503 * only re-enable if the proxy is not used by any other plugin */
1504 if (p->proxy != &builtin_so_proxy_plugin)
1506 GtkTreeIter parent;
1507 gboolean can_uncheck;
1508 GtkTreePath *store_path = gtk_tree_model_filter_convert_path_to_child_path(
1509 GTK_TREE_MODEL_FILTER(model), path);
1511 g_warn_if_fail(store_path != NULL);
1512 if (gtk_tree_path_up(store_path))
1514 gtk_tree_model_get_iter(GTK_TREE_MODEL(pm_widgets.store), &parent, store_path);
1516 if (state)
1517 can_uncheck = FALSE;
1518 else
1519 can_uncheck = p->proxy->proxied_count == 0;
1521 gtk_tree_store_set(pm_widgets.store, &parent,
1522 PLUGIN_COLUMN_CAN_UNCHECK, can_uncheck, -1);
1524 gtk_tree_path_free(store_path);
1527 /* We need to find out if a proxy was added or removed because that affects the plugin list
1528 * presented by the plugin manager */
1529 if (prev_num_proxies != active_proxies.length)
1531 /* Rescan the plugin list as we now support more. Gives some "already loaded" warnings
1532 * they are unproblematic */
1533 if (prev_num_proxies < active_proxies.length)
1534 load_all_plugins();
1536 pm_populate(pm_widgets.store);
1537 gtk_tree_view_expand_row(GTK_TREE_VIEW(pm_widgets.tree), path, FALSE);
1540 gtk_tree_path_free(path);
1541 g_free(file_name);
1544 static void pm_populate(GtkTreeStore *store)
1546 GtkTreeIter iter;
1547 GList *list;
1549 gtk_tree_store_clear(store);
1550 list = g_list_first(plugin_list);
1551 if (list == NULL)
1553 gtk_tree_store_append(store, &iter, NULL);
1554 gtk_tree_store_set(store, &iter, PLUGIN_COLUMN_CHECK, FALSE,
1555 PLUGIN_COLUMN_PLUGIN, NULL, -1);
1557 else
1559 for (; list != NULL; list = list->next)
1561 Plugin *p = list->data;
1562 GtkTreeIter parent;
1564 if (p->proxy != &builtin_so_proxy_plugin
1565 && find_iter_for_plugin(p->proxy, GTK_TREE_MODEL(pm_widgets.store), &parent))
1566 gtk_tree_store_append(store, &iter, &parent);
1567 else
1568 gtk_tree_store_append(store, &iter, NULL);
1570 gtk_tree_store_set(store, &iter,
1571 PLUGIN_COLUMN_CHECK, is_active_plugin(p),
1572 PLUGIN_COLUMN_PLUGIN, p,
1573 PLUGIN_COLUMN_CAN_UNCHECK, (p->proxied_count == 0),
1574 -1);
1579 static gboolean pm_treeview_query_tooltip(GtkWidget *widget, gint x, gint y,
1580 gboolean keyboard_mode, GtkTooltip *tooltip, gpointer user_data)
1582 GtkTreeModel *model;
1583 GtkTreeIter iter;
1584 GtkTreePath *path;
1585 Plugin *p = NULL;
1586 gboolean can_uncheck = TRUE;
1588 if (! gtk_tree_view_get_tooltip_context(GTK_TREE_VIEW(widget), &x, &y, keyboard_mode,
1589 &model, &path, &iter))
1590 return FALSE;
1592 gtk_tree_model_get(model, &iter, PLUGIN_COLUMN_PLUGIN, &p, PLUGIN_COLUMN_CAN_UNCHECK, &can_uncheck, -1);
1593 if (p != NULL)
1595 gchar *prefix, *suffix, *details, *markup;
1596 const gchar *uchk;
1598 uchk = can_uncheck ?
1599 "" : _("\n<i>Other plugins depend on this. Disable them first to allow deactivation.</i>\n");
1600 /* Four allocations is less than ideal but meh */
1601 details = g_strdup_printf(_("Version:\t%s\nAuthor(s):\t%s\nFilename:\t%s"),
1602 p->info.version, p->info.author, p->filename);
1603 prefix = g_markup_printf_escaped("<b>%s</b>\n%s\n", p->info.name, p->info.description);
1604 suffix = g_markup_printf_escaped("<small><i>\n%s</i></small>", details);
1605 markup = g_strconcat(prefix, uchk, suffix, NULL);
1607 gtk_tooltip_set_markup(tooltip, markup);
1608 gtk_tree_view_set_tooltip_row(GTK_TREE_VIEW(widget), tooltip, path);
1610 g_free(details);
1611 g_free(suffix);
1612 g_free(prefix);
1613 g_free(markup);
1615 gtk_tree_path_free(path);
1617 return p != NULL;
1621 static void pm_treeview_text_cell_data_func(GtkTreeViewColumn *column, GtkCellRenderer *cell,
1622 GtkTreeModel *model, GtkTreeIter *iter, gpointer data)
1624 Plugin *p;
1626 gtk_tree_model_get(model, iter, PLUGIN_COLUMN_PLUGIN, &p, -1);
1628 if (p == NULL)
1629 g_object_set(cell, "text", _("No plugins available."), NULL);
1630 else
1632 gchar *markup = g_markup_printf_escaped("<b>%s</b>\n%s", p->info.name, p->info.description);
1634 g_object_set(cell, "markup", markup, NULL);
1635 g_free(markup);
1640 static gboolean pm_treeview_button_press_cb(GtkWidget *widget, GdkEventButton *event,
1641 G_GNUC_UNUSED gpointer user_data)
1643 if (event->button == 3)
1645 gtk_menu_popup_at_pointer(GTK_MENU(pm_widgets.popup_menu), (GdkEvent *) event);
1647 return FALSE;
1651 static gint pm_tree_sort_func(GtkTreeModel *model, GtkTreeIter *a, GtkTreeIter *b,
1652 gpointer user_data)
1654 Plugin *pa, *pb;
1656 gtk_tree_model_get(model, a, PLUGIN_COLUMN_PLUGIN, &pa, -1);
1657 gtk_tree_model_get(model, b, PLUGIN_COLUMN_PLUGIN, &pb, -1);
1659 if (pa && pb)
1660 return strcmp(pa->info.name, pb->info.name);
1661 else
1662 return pa - pb;
1666 static gboolean pm_tree_search(const gchar *key, const gchar *haystack)
1668 gchar *normalized_string = NULL;
1669 gchar *normalized_key = NULL;
1670 gchar *case_normalized_string = NULL;
1671 gchar *case_normalized_key = NULL;
1672 gboolean matched = TRUE;
1674 normalized_string = g_utf8_normalize(haystack, -1, G_NORMALIZE_ALL);
1675 normalized_key = g_utf8_normalize(key, -1, G_NORMALIZE_ALL);
1677 if (normalized_string != NULL && normalized_key != NULL)
1679 GString *stripped_key;
1680 gchar **subkey, **subkeys;
1682 case_normalized_string = g_utf8_casefold(normalized_string, -1);
1683 case_normalized_key = g_utf8_casefold(normalized_key, -1);
1684 stripped_key = g_string_new(case_normalized_key);
1685 do {} while (utils_string_replace_all(stripped_key, " ", " "));
1686 subkeys = g_strsplit(stripped_key->str, " ", -1);
1687 g_string_free(stripped_key, TRUE);
1688 foreach_strv(subkey, subkeys)
1690 if (strstr(case_normalized_string, *subkey) == NULL)
1692 matched = FALSE;
1693 break;
1696 g_strfreev(subkeys);
1699 g_free(normalized_key);
1700 g_free(normalized_string);
1701 g_free(case_normalized_key);
1702 g_free(case_normalized_string);
1704 return matched;
1708 static gboolean pm_tree_filter_func(GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data)
1710 Plugin *plugin;
1711 gboolean matched;
1712 const gchar *key;
1713 gchar *haystack, *filename;
1715 gtk_tree_model_get(model, iter, PLUGIN_COLUMN_PLUGIN, &plugin, -1);
1717 if (!plugin)
1718 return TRUE;
1719 key = gtk_entry_get_text(GTK_ENTRY(pm_widgets.filter_entry));
1721 filename = g_path_get_basename(plugin->filename);
1722 haystack = g_strjoin(" ", plugin->info.name, plugin->info.description,
1723 plugin->info.author, filename, NULL);
1724 matched = pm_tree_search(key, haystack);
1725 g_free(haystack);
1726 g_free(filename);
1728 return matched;
1732 static void on_pm_tree_filter_entry_changed_cb(GtkEntry *entry, gpointer user_data)
1734 GtkTreeModel *filter_model = gtk_tree_view_get_model(GTK_TREE_VIEW(pm_widgets.tree));
1735 gtk_tree_model_filter_refilter(GTK_TREE_MODEL_FILTER(filter_model));
1739 static void on_pm_tree_filter_entry_icon_release_cb(GtkEntry *entry, GtkEntryIconPosition icon_pos,
1740 GdkEvent *event, gpointer user_data)
1742 if (event->button.button == 1 && icon_pos == GTK_ENTRY_ICON_PRIMARY)
1743 on_pm_tree_filter_entry_changed_cb(entry, user_data);
1747 static void pm_prepare_treeview(GtkWidget *tree, GtkTreeStore *store)
1749 GtkCellRenderer *text_renderer, *checkbox_renderer;
1750 GtkTreeViewColumn *column;
1751 GtkTreeModel *filter_model;
1752 GtkTreeSelection *sel;
1754 g_signal_connect(tree, "query-tooltip", G_CALLBACK(pm_treeview_query_tooltip), NULL);
1755 gtk_widget_set_has_tooltip(tree, TRUE);
1756 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree), FALSE);
1758 checkbox_renderer = gtk_cell_renderer_toggle_new();
1759 column = gtk_tree_view_column_new_with_attributes(
1760 _("Active"), checkbox_renderer,
1761 "active", PLUGIN_COLUMN_CHECK, "activatable", PLUGIN_COLUMN_CAN_UNCHECK, NULL);
1762 gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);
1763 g_signal_connect(checkbox_renderer, "toggled", G_CALLBACK(pm_plugin_toggled), NULL);
1765 text_renderer = gtk_cell_renderer_text_new();
1766 g_object_set(text_renderer, "ellipsize", PANGO_ELLIPSIZE_END, NULL);
1767 column = gtk_tree_view_column_new_with_attributes(_("Plugin"), text_renderer, NULL);
1768 gtk_tree_view_column_set_cell_data_func(column, text_renderer,
1769 pm_treeview_text_cell_data_func, NULL, NULL);
1770 gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);
1772 gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(tree), TRUE);
1773 gtk_tree_view_set_enable_search(GTK_TREE_VIEW(tree), FALSE);
1774 gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(store), PLUGIN_COLUMN_PLUGIN,
1775 pm_tree_sort_func, NULL, NULL);
1776 gtk_tree_sortable_set_sort_column_id(
1777 GTK_TREE_SORTABLE(store), PLUGIN_COLUMN_PLUGIN, GTK_SORT_ASCENDING);
1779 /* selection handling */
1780 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree));
1781 gtk_tree_selection_set_mode(sel, GTK_SELECTION_SINGLE);
1782 g_signal_connect(sel, "changed", G_CALLBACK(pm_selection_changed), NULL);
1784 g_signal_connect(tree, "button-press-event", G_CALLBACK(pm_treeview_button_press_cb), NULL);
1786 /* filter */
1787 filter_model = gtk_tree_model_filter_new(GTK_TREE_MODEL(store), NULL);
1788 gtk_tree_model_filter_set_visible_func(
1789 GTK_TREE_MODEL_FILTER(filter_model), pm_tree_filter_func, NULL, NULL);
1791 /* set model to tree view */
1792 gtk_tree_view_set_model(GTK_TREE_VIEW(tree), filter_model);
1793 g_object_unref(filter_model);
1795 pm_populate(store);
1799 static void pm_on_plugin_button_clicked(G_GNUC_UNUSED GtkButton *button, gpointer user_data)
1801 GtkTreeModel *model;
1802 GtkTreeSelection *selection;
1803 GtkTreeIter iter;
1804 Plugin *p;
1806 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(pm_widgets.tree));
1807 if (gtk_tree_selection_get_selected(selection, &model, &iter))
1809 gtk_tree_model_get(model, &iter, PLUGIN_COLUMN_PLUGIN, &p, -1);
1811 if (p != NULL)
1813 if (GPOINTER_TO_INT(user_data) == PM_BUTTON_CONFIGURE)
1814 plugin_show_configure(&p->public);
1815 else if (GPOINTER_TO_INT(user_data) == PM_BUTTON_HELP)
1817 g_return_if_fail(p->cbs.help != NULL);
1818 p->cbs.help(&p->public, p->cb_data);
1820 else if (GPOINTER_TO_INT(user_data) == PM_BUTTON_KEYBINDINGS && p->key_group && p->key_group->plugin_key_count > 0)
1821 keybindings_dialog_show_prefs_scroll(p->info.name);
1827 static void
1828 free_non_active_plugin(gpointer data, gpointer user_data)
1830 Plugin *plugin = data;
1832 /* don't do anything when closing the plugin manager and it is an active plugin */
1833 if (is_active_plugin(plugin))
1834 return;
1836 plugin_free(plugin);
1840 /* Callback when plugin manager dialog closes, responses GTK_RESPONSE_CLOSE and
1841 * GTK_RESPONSE_DELETE_EVENT are treated the same. */
1842 static void pm_dialog_response(GtkDialog *dialog, gint response, gpointer user_data)
1844 switch (response)
1846 case GTK_RESPONSE_CLOSE:
1847 case GTK_RESPONSE_DELETE_EVENT:
1848 if (plugin_list != NULL)
1850 /* remove all non-active plugins from the list */
1851 g_list_foreach(plugin_list, free_non_active_plugin, NULL);
1852 g_list_free(plugin_list);
1853 plugin_list = NULL;
1855 gtk_widget_destroy(GTK_WIDGET(dialog));
1856 pm_widgets.dialog = NULL;
1858 configuration_save();
1859 break;
1860 case PM_BUTTON_CONFIGURE:
1861 case PM_BUTTON_HELP:
1862 case PM_BUTTON_KEYBINDINGS:
1863 /* forward event to the generic handler */
1864 pm_on_plugin_button_clicked(NULL, GINT_TO_POINTER(response));
1865 break;
1870 static void pm_show_dialog(GtkMenuItem *menuitem, gpointer user_data)
1872 GtkWidget *vbox, *vbox2, *swin, *label, *menu_item, *filter_entry;
1874 if (pm_widgets.dialog != NULL)
1876 gtk_window_present(GTK_WINDOW(pm_widgets.dialog));
1877 return;
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_box_new(GTK_ORIENTATION_VERTICAL, 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 if (**ext == '.')
2018 g_warning(_("Proxy plugin '%s' extension '%s' starts with a dot. "
2019 "Please fix your proxy plugin."), p->info.name, *ext);
2022 proxy = g_new(PluginProxy, 1);
2023 g_strlcpy(proxy->extension, *ext, sizeof(proxy->extension));
2024 proxy->plugin = p;
2025 /* prepend, so that plugins automatically override core providers for a given extension */
2026 g_queue_push_head(&active_proxies, proxy);
2029 return TRUE;
2032 #endif