Debian Codegraph @

fontforge/plugin.cpp

raw symbols SCIP
1 /* Copyright (C) 2000-2012 by George Williams, 2021 Skef Iterum */
2 /*
3 * Redistribution and use in source and binary forms, with or without
4 * modification, are permitted provided that the following conditions are met:
5
6 * Redistributions of source code must retain the above copyright notice, this
7 * list of conditions and the following disclaimer.
8
9 * Redistributions in binary form must reproduce the above copyright notice,
10 * this list of conditions and the following disclaimer in the documentation
11 * and/or other materials provided with the distribution.
12
13 * The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28
29 #include <fontforge-config.h>
30
31 #ifndef _NO_PYTHON
32
33 #include "plugin.h"
34
35 #include "gfile.h"
36 #include "intl.h"
37 #include "uiinterface.h"
38
39 #include <string> /* for std::string */
40 #include <ini.h> /* mINI library for INI file parsing */
41
42 int use_plugins = true; // Prefs variable
43 int attempted_plugin_load = false;
44
45 enum plugin_startup_mode_type plugin_startup_mode = sm_ask;
46 FFList *plugin_data = NULL;
47
48 void FreePluginEntry(PluginEntry *pe) {
49 free(pe->name);
50 free(pe->package_name);
51 free(pe->summary);
52 free(pe->package_url);
53 free(pe->module_name);
54 free(pe->attrs);
55 if (pe->pyobj != NULL) {
56 Py_DECREF(pe->pyobj);
57 }
58 if (pe->entrypoint != NULL) {
59 Py_DECREF(pe->entrypoint);
60 }
61 free(pe);
62 }
63
64 static PluginEntry *NewPluginEntry(const char *name, const char *pkgname,
65 const char *modname, const char *url,
66 enum plugin_startup_mode_type sm) {
67 PluginEntry *pe = (PluginEntry *)malloc(sizeof(PluginEntry));
68 pe->name = copy(name);
69 pe->package_name = copy(pkgname);
70 pe->summary = NULL;
71 pe->module_name = copy(modname);
72 pe->attrs = NULL;
73 pe->package_url = copy(url);
74 pe->startup_mode = sm;
75 pe->pyobj = NULL;
76 pe->entrypoint = NULL;
77 pe->is_present = false;
78 pe->is_well_formed = true;
79 pe->has_prefs = false;
80 return pe;
81 }
82
83 static char *GetPluginDirName() {
84 char *buf, *dir = getFontForgeUserDir(Config);
85
86 if (dir == NULL) {
87 return NULL;
88 }
89
90 buf = smprintf("%s/plugin", dir);
91 free(dir);
92 if (ff_access(buf, F_OK) == -1)
93 if (GFileMkDir(buf, 0755) == -1) {
94 LogError(_("Could not create plugin directory '%s'"), buf);
95 return (NULL);
96 }
97 return buf;
98 }
99
100 const char *PluginInfoString(PluginEntry *pe, int do_new, int *is_err) {
101 enum plugin_startup_mode_type sm = do_new ? pe->new_mode : pe->startup_mode;
102 int err = true;
103 const char *r = NULL;
104 if (!pe->is_present) {
105 r = N_("Not Found");
106 } else if (sm != sm_on) {
107 err = false;
108 } else if (pe->is_present && pe->pyobj == NULL && pe->entrypoint == NULL) {
109 r = N_("Couldn't Load");
110 } else if (pe->pyobj != NULL && !pe->is_well_formed) {
111 r = N_("Couldn't Start");
112 } else if (pe->entrypoint != NULL) {
113 r = N_("Unloaded");
114 err = false;
115 } else {
116 err = false;
117 }
118 if (is_err != NULL) {
119 *is_err = err;
120 }
121 return r;
122 }
123
124 const char *PluginStartupModeString(enum plugin_startup_mode_type sm, int global) {
125 if (sm == sm_off) {
126 return N_("Off");
127 } else if (sm == sm_on) {
128 return N_("On");
129 } else {
130 return global ? N_("Ask") : N_("New");
131 }
132 }
133
134
135 static enum plugin_startup_mode_type PluginStartupModeFromString(const char *modestr) {
136 if (modestr == NULL) {
137 return sm_ask;
138 } else if (strcasecmp(modestr, "off") == 0) {
139 return sm_off;
140 } else if (strcasecmp(modestr, "on") == 0) {
141 return sm_on;
142 } else {
143 return sm_ask;
144 }
145 }
146
147 void *GetPluginStartupMode() {
148 return copy(PluginStartupModeString(plugin_startup_mode, true));
149 }
150
151 void SetPluginStartupMode(void *modevoid) {
152 plugin_startup_mode = PluginStartupModeFromString((char *)modevoid);
153 }
154
155 void SavePluginConfig() {
156 mINI::INIStructure ini;
157
158 for (FFList *i = plugin_data; i != NULL; i = i->next) {
159 PluginEntry *pe = (PluginEntry *) i->data;
160 if (pe->startup_mode == sm_ask) {
161 continue; // Don't save merely discovered plugin config
162 }
163 std::string section(pe->name);
164 if (pe->package_name != NULL) {
165 ini[section]["Package name"] = pe->package_name;
166 }
167 ini[section]["Module name"] = pe->module_name;
168 ini[section]["Active"] = PluginStartupModeString(pe->startup_mode, false);
169 if (pe->package_url != NULL) {
170 ini[section]["URL"] = pe->package_url;
171 }
172 }
173
174 char *pdir = GetPluginDirName();
175 if (pdir != NULL) {
176 char *fname = smprintf("%s/plugin_config.ini", pdir);
177 mINI::INIFile file(fname);
178 if (!file.write(ini)) {
179 LogError(_("Error saving plugin configuration file '%s'"), fname);
180 }
181 free(fname);
182 free(pdir);
183 }
184 }
185
186 static void LoadPluginConfig() {
187 char *pdir = GetPluginDirName();
188 if (pdir == NULL) {
189 return;
190 }
191
192 char *fname = smprintf("%s/plugin_config.ini", pdir);
193 mINI::INIFile file(fname);
194 mINI::INIStructure ini;
195
196 if (!file.read(ini)) {
197 /* File doesn't exist or can't be read - not an error for new installs */
198 free(fname);
199 free(pdir);
200 return;
201 }
202
203 for (auto const& section : ini) {
204 const std::string& name = section.first;
205 const auto& values = section.second;
206
207 if (!values.has("Module name")) {
208 LogError(_("No module name for '%s' in plugin config -- skipping."), name.c_str());
209 continue;
210 }
211 std::string modname = values.get("Module name");
212 if (modname.empty()) {
213 LogError(_("No module name for '%s' in plugin config -- skipping."), name.c_str());
214 continue;
215 }
216
217 std::string pkgname = values.get("Package name");
218 std::string sm_string = values.get("Active");
219 std::string url = values.get("URL");
220
221 PluginEntry *pe = NewPluginEntry(
222 name.c_str(),
223 pkgname.empty() ? NULL : pkgname.c_str(),
224 modname.c_str(),
225 url.empty() ? NULL : url.c_str(),
226 PluginStartupModeFromString(sm_string.empty() ? NULL : sm_string.c_str())
227 );
228 plugin_data = ff_list_append(plugin_data, pe);
229 }
230
231 free(fname);
232 free(pdir);
233 }
234
235 void LoadPlugin(PluginEntry *pe) {
236 PyObject *str, *tmp, *tmp2;
237 if (!use_plugins || !pe->is_present || pe->pyobj != NULL || pe->entrypoint == NULL) {
238 return;
239 }
240 str = PyUnicode_FromString("load");
241 pe->pyobj = PyObject_CallMethodObjArgs(pe->entrypoint, str, NULL);
242 Py_DECREF(str);
243 if (pe->pyobj != NULL) {
244 tmp = PyObject_GetAttrString(pe->pyobj, "fontforge_plugin_init");
245 if (tmp != NULL && PyFunction_Check(tmp)) {
246 PyObject *args = PyTuple_New(0);
247 PyObject *kwargs = PyDict_New();
248 char *b1 = GetPluginDirName(), *b2 = smprintf("%s/%s", b1, pe->name);
249 PyObject *dstr = PyUnicode_FromString(b2);
250 free(b1);
251 free(b2);
252 PyDict_SetItemString(kwargs, "preferences_path", dstr);
253 tmp2 = PyObject_Call(tmp, args, kwargs);
254 if (tmp2 == NULL) {
255 LogError(_("Skipping plugin %s: module '%s': Error calling 'fontforge_plugin_init' function"), pe->name, pe->module_name);
256 PyErr_Print();
257 } else {
258 pe->is_well_formed = true;
259 Py_DECREF(tmp2);
260 }
261 Py_DECREF(dstr);
262 Py_DECREF(kwargs);
263 Py_DECREF(args);
264 Py_DECREF(tmp);
265 } else {
266 LogError(_("Skipping plugin %s: module '%s': Lacks 'fontforge_plugin_init' function"), pe->name, pe->module_name);
267 if (tmp != NULL) {
268 Py_DECREF(tmp);
269 } else {
270 PyErr_Clear();
271 }
272 }
273 tmp = PyObject_GetAttrString(pe->pyobj, "fontforge_plugin_config");
274 pe->has_prefs = (tmp != NULL && PyFunction_Check(tmp));
275 if (tmp != NULL) {
276 Py_DECREF(tmp);
277 } else {
278 PyErr_Clear();
279 }
280 } else {
281 LogError(_("Skipping plugin %s: module '%s': Could not load."), pe->name, pe->module_name);
282 PyErr_Print();
283 }
284 Py_DECREF(pe->entrypoint);
285 pe->entrypoint = NULL;
286 }
287
288 static void ReimportPlugins() {
289 FFList *i;
290 if (!use_plugins) {
291 return;
292 }
293 for (i = plugin_data; i != NULL; i = i->next) {
294 PluginEntry *pe = (PluginEntry *)i->data;
295 if (pe->startup_mode == sm_on && pe->is_present && pe->pyobj == NULL) {
296 LoadPlugin(pe);
297 }
298 }
299 }
300
301 static PyObject *GetPluginEntryPoints() {
302 PyObject *iter = NULL, *all_eps = NULL;
303 PyObject *entry_points = NULL;
304
305 PyObject *importlib = PyImport_ImportModule("importlib.metadata");
306 if (!importlib) {
307 PyErr_Clear();
308 LogError(_("Core python package 'importlib.metadata' not found: Cannot discover plugins"));
309 return NULL;
310 }
311 if (!PyObject_HasAttrString(importlib, "entry_points")) {
312 LogError(_("Method 'entry_points()' not found in module 'importlib.metadata'"));
313 PyErr_Clear();
314 Py_DECREF(importlib);
315 return NULL;
316 }
317 all_eps = PyObject_CallMethod(importlib, "entry_points", NULL);
318
319 /* The object returned from importlib.metadata.entry_points() varies between versions*/
320 if (PyDict_Check(all_eps)) {
321 /* entry_points is a dictionary of entry point groups */
322 entry_points = PyDict_GetItemString(all_eps, "fontforge_plugin");
323 if (!entry_points) {
324 /* No FontForge plugins found */
325 PyErr_Clear();
326 return NULL;
327 }
328 } else {
329 /* all_eps is an EntryPoints object. Call all_eps.select(group="fontforge_plugin") */
330 PyObject *select_method = PyObject_GetAttrString(all_eps, "select");
331 PyObject *kw_args = Py_BuildValue("{s,s}", "group", "fontforge_plugin");
332 entry_points = PyObject_Call(select_method, PyTuple_New(0), kw_args);
333 Py_DECREF(select_method);
334 Py_DECREF(kw_args);
335 if (!entry_points) {
336 LogError(_("Failed to retrieve plugin entry points"));
337 PyErr_Print();
338 return NULL;
339 }
340 }
341
342 Py_DECREF(importlib);
343
344 iter = PyObject_GetIter(entry_points);
345 if (!iter || !PyIter_Check(iter)) {
346 PyErr_Clear();
347 LogError(_("Could not iterate 'fontforge_plugin' entry points."));
348 Py_XDECREF(iter);
349 return NULL;
350 }
351
352 return iter;
353 }
354
355 static void RetrieveStringItem(PyObject* obj, const char* key, char** p_value) {
356 PyObject* str = PyUnicode_FromString(key);
357 PyObject* val = PyObject_GetItem(obj, str);
358 if (val) {
359 free(*p_value);
360 *p_value = copy(PyUnicode_AsUTF8(val));
361 }
362 Py_XDECREF(str);
363 Py_XDECREF(val);
364 }
365
366 /* Retrieve name, URL, and summary of the plugin */
367 static void LoadPluginMetadata(PluginEntry* pe) {
368 PyObject *globals = PyDict_New(), *locals = PyDict_New();
369 PyObject *dist = NULL, *function_args = NULL;
370
371 /* The `EntryPoint.dist` attribute is available starting with Python 3.10.
372 * To support Python 3.8+ we resort to the ugly but more uniform method of
373 * retrieving all `Distribution` objects and traversing them until we find
374 * one which points to our `EntryPoint` object. */
375 const char* function_string =
376 "def load_plugin_metadata(entrypoint):\n"
377 " import importlib.metadata\n"
378 " all_dists = importlib.metadata.distributions()\n"
379 " for dist in all_dists:\n"
380 " dist_eps = dist.entry_points\n"
381 " for ep in dist_eps:\n"
382 " if ep == entrypoint:\n"
383 " return dist\n"
384 " return None\n";
385
386 /* Execute the function definition */
387 if (PyRun_String(function_string, Py_file_input, globals, locals) == NULL) {
388 Py_DECREF(globals);
389 Py_DECREF(locals);
390 return;
391 }
392
393 /* Retrieve the function object */
394 PyObject* func = PyDict_GetItemString(locals, "load_plugin_metadata");
395 if (func == NULL || !PyCallable_Check(func)) {
396 PyErr_SetString(PyExc_RuntimeError, "Could not find the function");
397 Py_DECREF(globals);
398 Py_DECREF(locals);
399 return;
400 }
401
402 /* Call the function */
403 function_args = PyTuple_Pack(1, pe->entrypoint);
404 if (function_args != NULL) {
405 dist = PyObject_Call(func, function_args, NULL);
406 Py_DECREF(function_args);
407 }
408 /* Note: func is a borrowed reference from PyDict_GetItemString, don't DECREF */
409
410 Py_DECREF(globals);
411 Py_DECREF(locals);
412
413 if (dist == NULL || dist == Py_None) {
414 if (dist == NULL) {
415 PyErr_Print();
416 }
417 PyErr_Format(PyExc_RuntimeError,
418 "Could not retrieve distribution for plugin '%s'", pe->name);
419 Py_XDECREF(dist);
420 return;
421 }
422
423 if (PyObject_HasAttrString(dist, "metadata")) {
424 PyObject* metadata = PyObject_GetAttrString(dist, "metadata");
425
426 RetrieveStringItem(metadata, "Home-page", &pe->package_url);
427 RetrieveStringItem(metadata, "Name", &pe->package_name);
428 RetrieveStringItem(metadata, "Summary", &pe->summary);
429 Py_XDECREF(metadata);
430 }
431
432 Py_DECREF(dist);
433 }
434
435 static bool DiscoverPlugins(int do_import) {
436 int do_ask = false;
437 PluginEntry *pe = NULL;
438 FFList *i;
439 PyObject *str, *str2, *iter, *entrypoint;
440
441 iter = GetPluginEntryPoints();
442 if (iter == NULL) {
443 return false;
444 }
445
446 while ((entrypoint = PyIter_Next(iter))) {
447 // Find name and module_name
448 str = PyObject_GetAttrString(entrypoint, "name");
449 const char *name = PyUnicode_AsUTF8(str);
450 if (name == NULL) {
451 Py_XDECREF(str);
452 PyErr_Clear();
453 continue;
454 }
455 str2 = PyObject_GetAttrString(entrypoint, "value");
456 const char *modname = PyUnicode_AsUTF8(str2);
457 if (modname == NULL) {
458 Py_XDECREF(str);
459 Py_XDECREF(str2);
460 PyErr_Clear();
461 continue;
462 }
463 // Find entry in current list or add entry to end
464 pe = NULL;
465 for (i = plugin_data; i != NULL; i = i->next) {
466 pe = (PluginEntry *)i->data;
467 if (strcmp(name, pe->name) == 0 && strcmp(modname, pe->module_name) == 0) {
468 break;
469 }
470 }
471 if (i != NULL && pe->pyobj != NULL) { // Already loaded
472 continue;
473 }
474 if (i == NULL) {
475 pe = NewPluginEntry(name, NULL, modname, NULL, plugin_startup_mode);
476 plugin_data = ff_list_append(plugin_data, pe);
477 }
478 Py_DECREF(str);
479 Py_DECREF(str2);
480 str = PyObject_GetAttrString(entrypoint, "attr");
481 if (str == NULL || str == Py_None) {
482 PyErr_Clear();
483 } else {
484 if (pe->attrs) {
485 free(pe->attrs);
486 }
487 const char *attrs = PyUnicode_AsUTF8(str);
488 pe->attrs = attrs != NULL ? copy(attrs) : NULL;
489 }
490 Py_XDECREF(str);
491 pe->is_present = true;
492 Py_XDECREF(pe->entrypoint);
493 pe->entrypoint = entrypoint;
494
495 LoadPluginMetadata(pe);
496 if (do_import && pe->startup_mode == sm_on) {
497 LoadPlugin(pe);
498 } else if (do_import && pe->startup_mode == sm_ask) {
499 do_ask = true;
500 }
501 }
502 if (PyErr_Occurred()) {
503 PyErr_Print();
504 }
505 for (i = plugin_data; i != NULL; i = i->next) {
506 pe = (PluginEntry *)i->data;
507 if (!pe->is_present && pe->startup_mode == sm_on) {
508 LogError(_("Warning: Enabled Plugin '%s' was not discovered"), pe->name);
509 }
510 }
511 Py_DECREF(iter);
512 return do_ask;
513 }
514
515 void PluginDoPreferences(PluginEntry *pe) {
516 if (!use_plugins || pe->pyobj == NULL || !pe->has_prefs) {
517 return;
518 }
519
520 PyObject *tmp = PyObject_GetAttrString(pe->pyobj, "fontforge_plugin_config");
521 if (tmp == NULL) {
522 PyErr_Clear();
523 return;
524 }
525 if (!PyFunction_Check(tmp)) {
526 Py_DECREF(tmp);
527 return;
528 }
529 PyObject_CallFunctionObjArgs(tmp, NULL);
530 Py_DECREF(tmp);
531 }
532
533 void PyFF_ImportPlugins(int do_import) {
534
535 if (!use_plugins) {
536 return;
537 }
538
539 if (!attempted_plugin_load) {
540 LoadPluginConfig();
541 int ask = DiscoverPlugins(do_import);
542 attempted_plugin_load = true;
543 if (ask) {
544 PluginDlg();
545 }
546 } else if (do_import) {
547 ReimportPlugins();
548 }
549
550 SavePluginConfig();
551 }
552
553 extern PyObject *PyFF_GetPluginInfo(PyObject *UNUSED(noself), PyObject *UNUSED(args)) {
554 PyObject *r, *d;
555 FFList *l;
556 PluginEntry *pe;
557
558 r = PyList_New(0);
559
560 for (l = plugin_data; l != NULL; l = l->next) {
561 pe = (PluginEntry *) l->data;
562 d = Py_BuildValue("{s:s,s:s,s:s,s:s,s:s,s:s,s:O,s:s,s:s}", "name", pe->name,
563 "enabled", PluginStartupModeString(pe->startup_mode, false),
564 "status", PluginInfoString(pe, false, NULL),
565 "package_name", pe->package_name,
566 "module_name", pe->module_name,
567 "attrs", pe->attrs,
568 "prefs", pe->has_prefs ? Py_True : Py_False,
569 "package_url", pe->package_url,
570 "summary", pe->summary);
571 PyList_Append(r, d);
572 }
573 return r;
574 }
575
576 extern PyObject *PyFF_ConfigurePlugins(PyObject *UNUSED(noself), PyObject *args) {
577 PyObject *iter = NULL, *item;
578 FFList *l, *nl = NULL;
579 PluginEntry *pe;
580 int type_error = false;
581 if (args != NULL || PyTuple_Check(args) || PyTuple_Size(args) == 1) {
582 PyObject *l = PyTuple_GetItem(args, 0);
583 if (l != NULL) {
584 iter = PyObject_GetIter(l);
585 }
586 }
587
588 if (iter != NULL) {
589 for (l = plugin_data; l != NULL; l = l->next) {
590 pe = (PluginEntry *) l->data;
591 pe->new_mode = sm_ask;
592 }
593 while ((item = PyIter_Next(iter))) {
594 if (!PyDict_Check(item)) {
595 type_error = true;
596 break;
597 }
598 PyObject *nameobj = PyDict_GetItemString(item, "name");
599 if (nameobj == NULL || !PyUnicode_Check(nameobj)) {
600 type_error = true;
601 break;
602 }
603 const char *namestr = PyUnicode_AsUTF8(nameobj);
604 for (l = plugin_data; l != NULL; l = l->next) {
605 pe = (PluginEntry *) l->data;
606 if (strcasecmp(namestr, pe->name) == 0) {
607 break;
608 }
609 }
610 if (l == NULL) {
611 PyErr_Format(PyExc_ValueError, _("'%s' is not the name of a currently known plugin"), namestr);
612 ff_list_free(ff_steal_pointer(&nl));
613 return NULL;
614 }
615 nl = ff_list_append(nl, pe);
616 PyObject *smobj = PyDict_GetItemString(item, "enabled");
617 pe->new_mode = PluginStartupModeFromString(PyUnicode_AsUTF8(smobj));
618 if (pe->new_mode == sm_ask) {
619 PyErr_Format(PyExc_ValueError, _("Startup mode '%s' (for plugin '%s') must be 'on' or 'off'. (To set a discovered plugin to 'new' omit it from the list.)"), PyUnicode_AsUTF8(smobj), namestr);
620 ff_list_free(ff_steal_pointer(&nl));
621 return NULL;
622 }
623 }
624 } else {
625 type_error = true;
626 }
627
628 if (type_error) {
629 PyErr_Format(PyExc_TypeError, _("The single parameter to this method must be an iterable object (such as a list) where each item is a tuple with a plugin name as its first element and 'on' or 'off' as its second element."));
630 return NULL;
631 }
632 for (l = plugin_data; l != NULL; l = l->next) {
633 pe = (PluginEntry *) l->data;
634 pe->startup_mode = pe->new_mode;
635 if (pe->new_mode == sm_ask) {
636 if (pe->is_present) {
637 nl = ff_list_append(nl, pe);
638 } else {
639 FreePluginEntry(pe);
640 }
641 }
642 }
643 ff_list_free(plugin_data);
644 plugin_data = nl;
645 SavePluginConfig();
646
647 return Py_None;
648 }
649
650 #endif // _NO_PYTHON