From 706f9bca82d463f6f1bd17d5dc609807e4a1e8a9 Mon Sep 17 00:00:00 2001 From: Patrick Griffis Date: Sat, 2 Sep 2017 17:52:25 -0400 Subject: python: Rewrite with CFFI --- .travis.yml | 2 +- meson.build | 4 + plugins/python/_hexchat.py | 364 ++++ plugins/python/generate_plugin.py | 89 + plugins/python/hexchat.py | 1 + plugins/python/meson.build | 14 +- plugins/python/python.c | 2834 -------------------------------- plugins/python/python.def | 1 - plugins/python/python.py | 497 ++++++ plugins/python/python2.vcxproj | 8 +- plugins/python/python3.vcxproj | 15 +- plugins/python/python3.vcxproj.filters | 19 +- plugins/python/xchat.py | 1 + src/common/meson.build | 4 - win32/copy/copy.vcxproj | 5 + win32/installer/hexchat.iss.tt | 9 +- 16 files changed, 1017 insertions(+), 2850 deletions(-) create mode 100644 plugins/python/_hexchat.py create mode 100755 plugins/python/generate_plugin.py create mode 100644 plugins/python/hexchat.py delete mode 100644 plugins/python/python.c create mode 100644 plugins/python/python.py create mode 100644 plugins/python/xchat.py diff --git a/.travis.yml b/.travis.yml index df0c7e1f..9e226f0c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,7 +2,7 @@ sudo: required services: docker before_install: - docker pull ubuntu:16.04 - - docker run --privileged --cidfile=/tmp/cid ubuntu:16.04 /bin/sh -c 'apt-get update && apt-get install -y meson/xenial-backports libcanberra-dev libdbus-glib-1-dev libglib2.0-dev libgtk2.0-dev libluajit-5.1-dev libnotify-dev libpci-dev libperl-dev libproxy-dev libssl-dev python3-dev mono-devel desktop-file-utils' + - docker run --privileged --cidfile=/tmp/cid ubuntu:16.04 /bin/sh -c 'apt-get update && apt-get install -y meson/xenial-backports libcanberra-dev libdbus-glib-1-dev libglib2.0-dev libgtk2.0-dev libluajit-5.1-dev libnotify-dev libpci-dev libperl-dev libproxy-dev libssl-dev python3-dev python3-cffi mono-devel desktop-file-utils' - docker commit `cat /tmp/cid` hexchat/ubuntu-ci - rm -f /tmp/cid install: diff --git a/meson.build b/meson.build index 9d2ae05b..17e73795 100644 --- a/meson.build +++ b/meson.build @@ -49,6 +49,10 @@ config_h.set('GLIB_VERSION_MIN_REQUIRED', 'GLIB_VERSION_2_34') config_h.set('HAVE_MEMRCHR', cc.has_function('memrchr')) config_h.set('HAVE_STRINGS_H', cc.has_header('strings.h')) +config_h.set_quoted('HEXCHATLIBDIR', + join_paths(get_option('prefix'), get_option('libdir'), 'hexchat/plugins') +) + if libssl_dep.found() config_h.set('HAVE_X509_GET_SIGNATURE_NID', cc.has_function('X509_get_signature_nid', dependencies: libssl_dep) diff --git a/plugins/python/_hexchat.py b/plugins/python/_hexchat.py new file mode 100644 index 00000000..52b3ec14 --- /dev/null +++ b/plugins/python/_hexchat.py @@ -0,0 +1,364 @@ +from contextlib import contextmanager +import inspect +import sys +from _hexchat_embedded import ffi, lib + +__all__ = [ + 'EAT_ALL', 'EAT_HEXCHAT', 'EAT_NONE', 'EAT_PLUGIN', 'EAT_XCHAT', + 'PRI_HIGH', 'PRI_HIGHEST', 'PRI_LOW', 'PRI_LOWEST', 'PRI_NORM', + '__doc__', '__version__', 'command', 'del_pluginpref', 'emit_print', + 'find_context', 'get_context', 'get_info', + 'get_list', 'get_lists', 'get_pluginpref', 'get_prefs', 'hook_command', + 'hook_print', 'hook_print_attrs', 'hook_server', 'hook_server_attrs', + 'hook_timer', 'hook_unload', 'list_pluginpref', 'nickcmp', 'prnt', + 'set_pluginpref', 'strip', 'unhook', +] + +__doc__ = 'HexChat Scripting Interface' +__version__ = (2, 0) +__license__ = 'GPL-2.0+' + +EAT_NONE = 0 +EAT_HEXCHAT = 1 +EAT_XCHAT = EAT_HEXCHAT +EAT_PLUGIN = 2 +EAT_ALL = EAT_HEXCHAT | EAT_PLUGIN + +PRI_LOWEST = -128 +PRI_LOW = -64 +PRI_NORM = 0 +PRI_HIGH = 64 +PRI_HIGHEST = 127 + + +# We need each module to be able to reference their parent plugin +# which is a bit tricky since they all share the exact same module. +# Simply navigating up to what module called it seems to actually +# be a fairly reliable and simple method of doing so if ugly. +def __get_current_plugin(): + frame = inspect.stack()[1][0] + while '__plugin' not in frame.f_globals: + frame = frame.f_back + assert frame is not None + return frame.f_globals['__plugin'] + + +# Keeping API compat +if sys.version_info[0] is 2: + def __decode(string): + return string +else: + def __decode(string): + return string.decode() + + +# ------------ API ------------ +def prnt(string): + lib.hexchat_print(lib.ph, string.encode()) + + +def emit_print(event_name, *args, **kwargs): + time = kwargs.pop('time', 0) # For py2 compat + cargs = [] + for i in range(4): + arg = args[i].encode() if len(args) > i else b'' + cstring = ffi.new('char[]', arg) + cargs.append(cstring) + if time is 0: + return lib.hexchat_emit_print(lib.ph, event_name.encode(), *cargs) + else: + attrs = lib.hexchat_event_attrs_create(lib.ph) + attrs.server_time_utc = time + ret = lib.hexchat_emit_print(lib.ph, attrs, event_name.encode(), *cargs) + lib.hexchat_event_attrs_free(lib.ph, attrs) + return ret + + +def command(command): + lib.hexchat_command(lib.ph, command.encode()) + + +def nickcmp(string1, string2): + return lib.hexchat_nickcmp(lib.ph, string1.encode(), string2.encode()) + + +def strip(text, length=-1, flags=3): + stripped = lib.hexchat_strip(lib.ph, text.encode(), length, flags) + ret = __decode(ffi.string(stripped)) + lib.hexchat_free(lib.ph, stripped) + return ret + + +def get_info(name): + ret = lib.hexchat_get_info(lib.ph, name.encode()) + if ret == ffi.NULL: + return None + if name in ('gtkwin_ptr', 'win_ptr'): + # Surely there is a less dumb way? + ptr = repr(ret).rsplit(' ', 1)[1][:-1] + return ptr + return __decode(ffi.string(ret)) + + +def get_prefs(name): + string_out = ffi.new('char**') + int_out = ffi.new('int*') + type = lib.hexchat_get_prefs(lib.ph, name.encode(), string_out, int_out) + if type is 0: + return None + elif type is 1: + return __decode(ffi.string(string_out[0])) + elif type is 2 or type is 3: # XXX: 3 should be a bool, but keeps API + return int_out[0] + else: + assert False + + +def __cstrarray_to_list(arr): + i = 0 + ret = [] + while arr[i] != ffi.NULL: + ret.append(ffi.string(arr[i])) + i += 1 + return ret + + +__FIELD_CACHE = {} + + +def __get_fields(name): + return __FIELD_CACHE.setdefault(name, + __cstrarray_to_list(lib.hexchat_list_fields(lib.ph, name))) + + +__FIELD_PROPERTY_CACHE = {} + + +def __cached_decoded_str(string): + return __FIELD_PROPERTY_CACHE.setdefault(string, __decode(string)) + + +def get_lists(): + return [__cached_decoded_str(field) for field in __get_fields(b'lists')] + + +class ListItem: + def __init__(self, name): + self._listname = name + + def __repr__(self): + return '<{} list item at {}>'.format(self._listname, id(self)) + + +def get_list(name): + # XXX: This function is extremely inefficient and could be interators and + # lazily loaded properties, but for API compat we stay slow + orig_name = name + name = name.encode() + + if name not in __get_fields(b'lists'): + raise KeyError('list not available') + + list_ = lib.hexchat_list_get(lib.ph, name) + if list_ == ffi.NULL: + return None + + ret = [] + fields = __get_fields(name) + + def string_getter(field): + string = lib.hexchat_list_str(lib.ph, list_, field) + if string != ffi.NULL: + return __decode(ffi.string(string)) + return '' + + def ptr_getter(field): + if field == b'context': + ptr = lib.hexchat_list_str(lib.ph, list_, field) + ctx = ffi.cast('hexchat_context*', ptr) + return Context(ctx) + return None + + getters = { + ord('s'): string_getter, + ord('i'): lambda field: lib.hexchat_list_int(lib.ph, list_, field), + ord('t'): lambda field: lib.hexchat_list_time(lib.ph, list_, field), + ord('p'): ptr_getter, + } + + while lib.hexchat_list_next(lib.ph, list_) is 1: + item = ListItem(orig_name) + for field in fields: + getter = getters.get(ord(field[0])) + if getter is not None: + field_name = field[1:] + setattr(item, __cached_decoded_str(field_name), getter(field_name)) + ret.append(item) + + lib.hexchat_list_free(lib.ph, list_) + return ret + + +def hook_command(command, callback, userdata=None, priority=PRI_NORM, help=None): + plugin = __get_current_plugin() + hook = plugin.add_hook(callback, userdata) + handle = lib.hexchat_hook_command(lib.ph, command.encode(), priority, lib._on_command_hook, + help.encode() if help is not None else ffi.NULL, + hook.handle) + hook.hexchat_hook = handle + return id(hook) + + +def hook_print(name, callback, userdata=None, priority=PRI_NORM): + plugin = __get_current_plugin() + hook = plugin.add_hook(callback, userdata) + handle = lib.hexchat_hook_print(lib.ph, name.encode(), priority, lib._on_print_hook, + hook.handle) + hook.hexchat_hook = handle + return id(hook) + + +def hook_print_attrs(name, callback, userdata=None, priority=PRI_NORM): + plugin = __get_current_plugin() + hook = plugin.add_hook(callback, userdata) + handle = lib.hexchat_hook_print_attrs(lib.ph, name.encode(), priority, lib._on_print_attrs_hook, + hook.handle) + hook.hexchat_hook = handle + return id(hook) + + +def hook_server(name, callback, userdata=None, priority=PRI_NORM): + plugin = __get_current_plugin() + hook = plugin.add_hook(callback, userdata) + handle = lib.hexchat_hook_server(lib.ph, name.encode(), priority, lib._on_server_hook, + hook.handle) + hook.hexchat_hook = handle + return id(hook) + + +def hook_server_attrs(name, callback, userdata=None, priority=PRI_NORM): + plugin = __get_current_plugin() + hook = plugin.add_hook(callback, userdata) + handle = lib.hexchat_hook_server_attrs(lib.ph, name.encode(), priority, lib._on_server_attrs_hook, + hook.handle) + hook.hexchat_hook = handle + return id(hook) + + +def hook_timer(timeout, callback, userdata=None): + plugin = __get_current_plugin() + hook = plugin.add_hook(callback, userdata) + handle = lib.hexchat_hook_timer(lib.ph, timeout, lib._on_timer_hook, hook.handle) + hook.hexchat_hook = handle + return id(hook) + + +def hook_unload(callback, userdata=None): + plugin = __get_current_plugin() + hook = plugin.add_hook(callback, userdata, is_unload=True) + return id(hook) + + +def unhook(handle): + plugin = __get_current_plugin() + return plugin.remove_hook(handle) + + +def set_pluginpref(name, value): + if isinstance(value, str): + return bool(lib.hexchat_pluginpref_set_str(lib.ph, name.encode(), value.encode())) + elif isinstance(value, int): + return bool(lib.hexchat_pluginpref_set_int(lib.ph, name.encode(), value)) + else: + # XXX: This should probably raise but this keeps API + return False + + +def get_pluginpref(name): + name = name.encode() + string_out = ffi.new('char[512]') + if lib.hexchat_pluginpref_get_str(lib.ph, name, string_out) is not 1: + return None + + string = ffi.string(string_out) + # This API stores everything as a string so we have to figure out what + # its actual type was supposed to be. + if len(string) > 12: # Can't be a number + return __decode(string) + + number = lib.hexchat_pluginpref_get_int(lib.ph, name) + if number == -1 and string != b'-1': + return __decode(string) + + return number + + +def del_pluginpref(name): + return bool(lib.hexchat_pluginpref_delete(lib.ph, name.encode())) + + +def list_pluginpref(): + prefs_str = ffi.new('char[4096]') + if lib.hexchat_pluginpref_list(lib.ph, prefs_str) is 1: + return __decode(prefs_str).split(',') + return [] + + +class Context: + def __init__(self, ctx): + self._ctx = ctx + + def __eq__(self, value): + if not isinstance(value, Context): + return False + return self._ctx == value._ctx + + @contextmanager + def __change_context(self): + old_ctx = lib.hexchat_get_context(lib.ph) + if not self.set(): + # XXX: Behavior change, previously used wrong context + lib.hexchat_print(lib.ph, + b'Context object refers to closed context, ignoring call') + return + yield + lib.hexchat_set_context(lib.ph, old_ctx) + + def set(self): + # XXX: API addition, C plugin silently ignored failure + return bool(lib.hexchat_set_context(lib.ph, self._ctx)) + + def prnt(self, string): + with self.__change_context(): + prnt(string) + + def emit_print(self, event_name, *args, **kwargs): + time = kwargs.pop('time', 0) # For py2 compat + with self.__change_context(): + return emit_print(event_name, *args, time=time) + + def command(self, string): + with self.__change_context(): + command(string) + + def get_info(self, name): + with self.__change_context(): + return get_info(name) + + def get_list(self, name): + with self.__change_context(): + return get_list(name) + + +def get_context(): + ctx = lib.hexchat_get_context(lib.ph) + return Context(ctx) + + +def find_context(server=None, channel=None): + server = server.encode() if server is not None else ffi.NULL + channel = channel.encode() if channel is not None else ffi.NULL + ctx = lib.hexchat_find_context(lib.ph, server, channel) + if ctx == ffi.NULL: + return None + return Context(ctx) diff --git a/plugins/python/generate_plugin.py b/plugins/python/generate_plugin.py new file mode 100755 index 00000000..5c52b37b --- /dev/null +++ b/plugins/python/generate_plugin.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 + +import sys +import cffi + +builder = cffi.FFI() + +# hexchat-plugin.h +with open(sys.argv[1]) as f: + output = [] + eat_until_endif = 0 + # This is very specific to hexchat-plugin.h, it is not a cpp + for line in f: + if line.startswith('#define'): + continue + elif line.endswith('HEXCHAT_PLUGIN_H\n'): + continue + elif 'time.h' in line: + output.append('typedef int... time_t;') + elif line.startswith('#if'): + eat_until_endif += 1 + elif line.startswith('#endif'): + eat_until_endif -= 1 + elif eat_until_endif and '_hexchat_context' not in line: + continue + else: + output.append(line) + builder.cdef(''.join(output)) + +builder.embedding_api(''' +extern "Python" int _on_py_command(char **, char **, void *); +extern "Python" int _on_load_command(char **, char **, void *); +extern "Python" int _on_unload_command(char **, char **, void *); +extern "Python" int _on_reload_command(char **, char **, void *); +extern "Python" int _on_say_command(char **, char **, void *); + +extern "Python" int _on_command_hook(char **, char **, void *); +extern "Python" int _on_print_hook(char **, void *); +extern "Python" int _on_print_attrs_hook(char **, hexchat_event_attrs *, void *); +extern "Python" int _on_server_hook(char **, char **, void *); +extern "Python" int _on_server_attrs_hook(char **, char **, hexchat_event_attrs *, void *); +extern "Python" int _on_timer_hook(void *); + +extern "Python" int _on_plugin_init(char **, char **, char **, char *, char *); +extern "Python" int _on_plugin_deinit(void); + +static hexchat_plugin *ph; +''') + +builder.set_source('_hexchat_embedded', ''' +/* Python's header defines these.. */ +#undef HAVE_MEMRCHR +#undef HAVE_STRINGS_H + +#include "config.h" +#include "hexchat-plugin.h" + +static hexchat_plugin *ph; +CFFI_DLLEXPORT int _on_plugin_init(char **, char **, char **, char *, char *); +CFFI_DLLEXPORT int _on_plugin_deinit(void); + +int hexchat_plugin_init(hexchat_plugin *plugin_handle, + char **name_out, char **description_out, + char **version_out, char *arg) +{ + if (ph != NULL) + { + puts ("Python plugin already loaded\\n"); + return 0; /* Prevent loading twice */ + } + + ph = plugin_handle; + return _on_plugin_init(name_out, description_out, version_out, arg, HEXCHATLIBDIR); +} + +int hexchat_plugin_deinit(void) +{ + int ret = _on_plugin_deinit(); + ph = NULL; + return ret; +} +''') + +# python.py +with open(sys.argv[2]) as f: + builder.embedding_init_code(f.read()) + +# python.c +builder.emit_c_code(sys.argv[3]) diff --git a/plugins/python/hexchat.py b/plugins/python/hexchat.py new file mode 100644 index 00000000..6922490b --- /dev/null +++ b/plugins/python/hexchat.py @@ -0,0 +1 @@ +from _hexchat import * diff --git a/plugins/python/meson.build b/plugins/python/meson.build index e24f0c6f..2ad5128e 100644 --- a/plugins/python/meson.build +++ b/plugins/python/meson.build @@ -5,8 +5,18 @@ else python_dep = dependency(python_opt, version: '>= 2.7') endif -shared_module('python', 'python.c', - dependencies: [libgio_dep, hexchat_plugin_dep, python_dep], +python3_source = custom_target('python-bindings', + input: ['../../src/common/hexchat-plugin.h', 'python.py'], + output: 'python.c', + command: [find_program('generate_plugin.py'), '@INPUT@', '@OUTPUT@'] +) + +install_data(['_hexchat.py', 'hexchat.py', 'xchat.py'], + install_dir: join_paths(get_option('libdir'), 'hexchat/python') +) + +shared_module('python', python3_source, + dependencies: [hexchat_plugin_dep, python_dep], install: true, install_dir: plugindir, name_prefix: '', diff --git a/plugins/python/python.c b/plugins/python/python.c deleted file mode 100644 index 4403474d..00000000 --- a/plugins/python/python.c +++ /dev/null @@ -1,2834 +0,0 @@ -/* -* Copyright (c) 2002-2003 Gustavo Niemeyer -* -* XChat Python Plugin Interface -* -* Xchat Python Plugin Interface is free software; you can redistribute -* it and/or modify it under the terms of the GNU General Public License -* as published by the Free Software Foundation; either version 2 of the -* License, or (at your option) any later version. -* -* pybot is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this file; if not, write to the Free Software -* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA -*/ - -/* Thread support - * ============== - * - * The python interpreter has a global interpreter lock. Any thread - * executing must acquire it before working with data accessible from - * python code. Here we must also care about xchat not being - * thread-safe. We do this by using an xchat lock, which protects - * xchat instructions from being executed out of time (when this - * plugin is not "active"). - * - * When xchat calls python code: - * - Change the current_plugin for the executing plugin; - * - Release xchat lock - * - Acquire the global interpreter lock - * - Make the python call - * - Release the global interpreter lock - * - Acquire xchat lock - * - * When python code calls xchat: - * - Release the global interpreter lock - * - Acquire xchat lock - * - Restore context, if necessary - * - Make the xchat call - * - Release xchat lock - * - Acquire the global interpreter lock - * - * Inside a timer, so that individual threads have a chance to run: - * - Release xchat lock - * - Go ahead threads. Have a nice time! - * - Acquire xchat lock - * - */ - -#include "config.h" - -#include -#include -#include -#include -#include - -#ifdef WIN32 -#include -#else -#include -#include -#endif - -#include "hexchat-plugin.h" -#undef _POSIX_C_SOURCE /* Avoid warnings from /usr/include/features.h */ -#undef _XOPEN_SOURCE -#undef HAVE_MEMRCHR /* Avoid redefinition in Python.h */ -#undef HAVE_STRINGS_H -#include -#include -#include - -/* Macros to convert version macros into string literals. - * The indirect macro is a well-known preprocessor trick to force X to be evaluated before the # operator acts to make it a string literal. - * If STRINGIZE were to be directly defined as #X instead, VERSION would be "VERSION_MAJOR" instead of "1". - */ -#define STRINGIZE2(X) #X -#define STRINGIZE(X) STRINGIZE2(X) - -/* Version number macros */ -#define VERSION_MAJOR 1 -#define VERSION_MINOR 0 - -/* Version string macro e.g 1.0/3.3 */ -#define VERSION STRINGIZE(VERSION_MAJOR) "." STRINGIZE(VERSION_MINOR) "/" \ - STRINGIZE(PY_MAJOR_VERSION) "." STRINGIZE (PY_MINOR_VERSION) - -/* #define's for Python 2 */ -#if PY_MAJOR_VERSION == 2 -#undef PyLong_Check -#define PyLong_Check PyInt_Check -#define PyLong_AsLong PyInt_AsLong -#define PyLong_FromLong PyInt_FromLong - -#undef PyUnicode_Check -#undef PyUnicode_FromString -#undef PyUnicode_FromFormat -#define PyUnicode_Check PyString_Check -#define PyUnicode_AsFormat PyString_AsFormat -#define PyUnicode_FromFormat PyString_FromFormat -#define PyUnicode_FromString PyString_FromString -#define PyUnicode_AsUTF8 PyString_AsString - -#ifdef WIN32 -#undef WITH_THREAD -#endif -#endif - -/* #define for Python 3 */ -#if PY_MAJOR_VERSION == 3 -#define IS_PY3K -#endif - -#define NONE 0 -#define ALLOW_THREADS 1 -#define RESTORE_CONTEXT 2 - -#ifdef WITH_THREAD -#define ACQUIRE_XCHAT_LOCK() PyThread_acquire_lock(xchat_lock, 1) -#define RELEASE_XCHAT_LOCK() PyThread_release_lock(xchat_lock) -#define BEGIN_XCHAT_CALLS(x) \ - do { \ - PyObject *calls_plugin = NULL; \ - PyThreadState *calls_thread; \ - if ((x) & RESTORE_CONTEXT) \ - calls_plugin = Plugin_GetCurrent(); \ - calls_thread = PyEval_SaveThread(); \ - ACQUIRE_XCHAT_LOCK(); \ - if (!((x) & ALLOW_THREADS)) { \ - PyEval_RestoreThread(calls_thread); \ - calls_thread = NULL; \ - } \ - if (calls_plugin) \ - hexchat_set_context(ph, \ - Plugin_GetContext(calls_plugin)); \ - while (0) -#define END_XCHAT_CALLS() \ - RELEASE_XCHAT_LOCK(); \ - if (calls_thread) \ - PyEval_RestoreThread(calls_thread); \ - } while(0) -#else -#define ACQUIRE_XCHAT_LOCK() -#define RELEASE_XCHAT_LOCK() -#define BEGIN_XCHAT_CALLS(x) -#define END_XCHAT_CALLS() -#endif - -#ifdef WITH_THREAD - -#define BEGIN_PLUGIN(plg) \ - do { \ - hexchat_context *begin_plugin_ctx = hexchat_get_context(ph); \ - RELEASE_XCHAT_LOCK(); \ - Plugin_AcquireThread(plg); \ - Plugin_SetContext(plg, begin_plugin_ctx); \ - } while (0) -#define END_PLUGIN(plg) \ - do { \ - Plugin_ReleaseThread(plg); \ - ACQUIRE_XCHAT_LOCK(); \ - } while (0) - -#else /* !WITH_THREAD (win32) */ - -static PyThreadState *pTempThread; - -#define BEGIN_PLUGIN(plg) \ - do { \ - hexchat_context *begin_plugin_ctx = hexchat_get_context(ph); \ - RELEASE_XCHAT_LOCK(); \ - PyEval_AcquireLock(); \ - pTempThread = PyThreadState_Swap(((PluginObject *)(plg))->tstate); \ - Plugin_SetContext(plg, begin_plugin_ctx); \ - } while (0) -#define END_PLUGIN(plg) \ - do { \ - ((PluginObject *)(plg))->tstate = PyThreadState_Swap(pTempThread); \ - PyEval_ReleaseLock(); \ - ACQUIRE_XCHAT_LOCK(); \ - } while (0) - -#endif /* !WITH_THREAD */ - -#define Plugin_Swap(x) \ - PyThreadState_Swap(((PluginObject *)(x))->tstate) -#define Plugin_AcquireThread(x) \ - PyEval_AcquireThread(((PluginObject *)(x))->tstate) -#define Plugin_ReleaseThread(x) \ - Util_ReleaseThread(((PluginObject *)(x))->tstate) -#define Plugin_GetFilename(x) \ - (((PluginObject *)(x))->filename) -#define Plugin_GetName(x) \ - (((PluginObject *)(x))->name) -#define Plugin_GetVersion(x) \ - (((PluginObject *)(x))->version) -#define Plugin_GetDesc(x) \ - (((PluginObject *)(x))->description) -#define Plugin_GetHooks(x) \ - (((PluginObject *)(x))->hooks) -#define Plugin_GetContext(x) \ - (((PluginObject *)(x))->context) -#define Plugin_SetFilename(x, y) \ - ((PluginObject *)(x))->filename = (y); -#define Plugin_SetName(x, y) \ - ((PluginObject *)(x))->name = (y); -#define Plugin_SetVersion(x, y) \ - ((PluginObject *)(x))->version = (y); -#define Plugin_SetDescription(x, y) \ - ((PluginObject *)(x))->description = (y); -#define Plugin_SetHooks(x, y) \ - ((PluginObject *)(x))->hooks = (y); -#define Plugin_SetContext(x, y) \ - ((PluginObject *)(x))->context = (y); -#define Plugin_SetGui(x, y) \ - ((PluginObject *)(x))->gui = (y); - -#define HOOK_XCHAT 1 -#define HOOK_XCHAT_ATTR 2 -#define HOOK_UNLOAD 3 - -/* ===================================================================== */ -/* Object definitions */ - -typedef struct { - PyObject_HEAD - int softspace; /* We need it for print support. */ -} XChatOutObject; - -typedef struct { - PyObject_HEAD - hexchat_context *context; -} ContextObject; - -typedef struct { - PyObject_HEAD - PyObject *time; -} AttributeObject; - -typedef struct { - PyObject_HEAD - const char *listname; - PyObject *dict; -} ListItemObject; - -typedef struct { - PyObject_HEAD - char *name; - char *version; - char *filename; - char *description; - GSList *hooks; - PyThreadState *tstate; - hexchat_context *context; - void *gui; -} PluginObject; - -typedef struct { - int type; - PyObject *plugin; - PyObject *callback; - PyObject *userdata; - char *name; - void *data; /* A handle, when type == HOOK_XCHAT */ -} Hook; - - -/* ===================================================================== */ -/* Function declarations */ - -static PyObject *Util_BuildList(char *word[]); -static PyObject *Util_BuildEOLList(char *word[]); -static void Util_Autoload(void); -static char *Util_Expand(char *filename); - -static int Callback_Server(char *word[], char *word_eol[], hexchat_event_attrs *attrs, void *userdata); -static int Callback_Command(char *word[], char *word_eol[], void *userdata); -static int Callback_Print_Attrs(char *word[], hexchat_event_attrs *attrs, void *userdata); -static int Callback_Print(char *word[], void *userdata); -static int Callback_Timer(void *userdata); -static int Callback_ThreadTimer(void *userdata); - -static PyObject *XChatOut_New(void); -static PyObject *XChatOut_write(PyObject *self, PyObject *args); -static void XChatOut_dealloc(PyObject *self); - -static PyObject *Attribute_New(hexchat_event_attrs *attrs); - -static void Context_dealloc(PyObject *self); -static PyObject *Context_set(ContextObject *self, PyObject *args); -static PyObject *Context_command(ContextObject *self, PyObject *args); -static PyObject *Context_prnt(ContextObject *self, PyObject *args); -static PyObject *Context_get_info(ContextObject *self, PyObject *args); -static PyObject *Context_get_list(ContextObject *self, PyObject *args); -static PyObject *Context_compare(ContextObject *a, ContextObject *b, int op); -static PyObject *Context_FromContext(hexchat_context *context); -static PyObject *Context_FromServerAndChannel(char *server, char *channel); - -static PyObject *Plugin_New(char *filename, PyObject *xcoobj); -static PyObject *Plugin_GetCurrent(void); -static PluginObject *Plugin_ByString(char *str); -static Hook *Plugin_AddHook(int type, PyObject *plugin, PyObject *callback, - PyObject *userdata, char *name, void *data); -static Hook *Plugin_FindHook(PyObject *plugin, char *name); -static void Plugin_RemoveHook(PyObject *plugin, Hook *hook); -static void Plugin_RemoveAllHooks(PyObject *plugin); - -static PyObject *Module_hexchat_command(PyObject *self, PyObject *args); -static PyObject *Module_xchat_prnt(PyObject *self, PyObject *args); -static PyObject *Module_hexchat_get_context(PyObject *self, PyObject *args); -static PyObject *Module_hexchat_find_context(PyObject *self, PyObject *args, - PyObject *kwargs); -static PyObject *Module_hexchat_get_info(PyObject *self, PyObject *args); -static PyObject *Module_hexchat_hook_command(PyObject *self, PyObject *args, - PyObject *kwargs); -static PyObject *Module_hexchat_hook_server(PyObject *self, PyObject *args, - PyObject *kwargs); -static PyObject *Module_hexchat_hook_print(PyObject *self, PyObject *args, - PyObject *kwargs); -static PyObject *Module_hexchat_hook_timer(PyObject *self, PyObject *args, - PyObject *kwargs); -static PyObject *Module_hexchat_unhook(PyObject *self, PyObject *args); -static PyObject *Module_hexchat_get_info(PyObject *self, PyObject *args); -static PyObject *Module_xchat_get_list(PyObject *self, PyObject *args); -static PyObject *Module_xchat_get_lists(PyObject *self, PyObject *args); -static PyObject *Module_hexchat_nickcmp(PyObject *self, PyObject *args); -static PyObject *Module_hexchat_strip(PyObject *self, PyObject *args); -static PyObject *Module_hexchat_pluginpref_set(PyObject *self, PyObject *args); -static PyObject *Module_hexchat_pluginpref_get(PyObject *self, PyObject *args); -static PyObject *Module_hexchat_pluginpref_delete(PyObject *self, PyObject *args); -static PyObject *Module_hexchat_pluginpref_list(PyObject *self, PyObject *args); - -static void IInterp_Exec(char *command); -static int IInterp_Cmd(char *word[], char *word_eol[], void *userdata); - -static void Command_PyList(void); -static void Command_PyLoad(char *filename); -static void Command_PyUnload(char *name); -static void Command_PyReload(char *name); -static void Command_PyAbout(void); -static int Command_Py(char *word[], char *word_eol[], void *userdata); - -/* ===================================================================== */ -/* Static declarations and definitions */ - -static PyTypeObject Plugin_Type; -static PyTypeObject XChatOut_Type; -static PyTypeObject Context_Type; -static PyTypeObject ListItem_Type; -static PyTypeObject Attribute_Type; - -static PyThreadState *main_tstate = NULL; -static void *thread_timer = NULL; - -static hexchat_plugin *ph; -static GSList *plugin_list = NULL; - -static PyObject *interp_plugin = NULL; -static PyObject *xchatout = NULL; - -#ifdef WITH_THREAD -static PyThread_type_lock xchat_lock = NULL; -#endif - -static const char usage[] = "\ -Usage: /PY LOAD \n\ - UNLOAD \n\ - RELOAD \n\ - LIST\n\ - EXEC \n\ - CONSOLE\n\ - ABOUT\n\ -\n"; - -static const char about[] = "HexChat Python interface version " VERSION "\n"; - -/* ===================================================================== */ -/* Utility functions */ - -static PyObject * -Util_BuildList(char *word[]) -{ - PyObject *list; - int listsize = 31; - int i; - /* Find the last valid array member; there may be intermediate NULLs that - * would otherwise cause us to drop some members. */ - while (listsize > 0 && - (word[listsize] == NULL || word[listsize][0] == 0)) - listsize--; - list = PyList_New(listsize); - if (list == NULL) { - PyErr_Print(); - return NULL; - } - for (i = 1; i <= listsize; i++) { - PyObject *o; - if (word[i] == NULL) { - Py_INCREF(Py_None); - o = Py_None; - } else { - /* This handles word[i][0] == 0 automatically. */ - o = PyUnicode_FromString(word[i]); - } - PyList_SetItem(list, i - 1, o); - } - return list; -} - -static PyObject * -Util_BuildEOLList(char *word[]) -{ - PyObject *list; - int listsize = 31; - int i; - char *accum = NULL; - char *last = NULL; - - /* Find the last valid array member; there may be intermediate NULLs that - * would otherwise cause us to drop some members. */ - while (listsize > 0 && - (word[listsize] == NULL || word[listsize][0] == 0)) - listsize--; - list = PyList_New(listsize); - if (list == NULL) { - PyErr_Print(); - return NULL; - } - for (i = listsize; i > 0; i--) { - char *part = word[i]; - PyObject *uni_part; - if (accum == NULL) { - accum = g_strdup (part); - } else if (part != NULL && part[0] != 0) { - last = accum; - accum = g_strjoin(" ", part, last, NULL); - g_free (last); - last = NULL; - - if (accum == NULL) { - Py_DECREF(list); - hexchat_print(ph, "Not enough memory to alloc accum" - "for python plugin callback"); - return NULL; - } - } - uni_part = PyUnicode_FromString(accum); - PyList_SetItem(list, i - 1, uni_part); - } - - g_free (last); - g_free (accum); - - return list; -} - -static void -Util_Autoload_from (const char *dir_name) -{ - gchar *oldcwd; - const char *entry_name; - GDir *dir; - - oldcwd = g_get_current_dir (); - if (oldcwd == NULL) - return; - if (g_chdir(dir_name) != 0) - { - g_free (oldcwd); - return; - } - dir = g_dir_open (".", 0, NULL); - if (dir == NULL) - { - g_free (oldcwd); - return; - } - while ((entry_name = g_dir_read_name (dir))) - { - if (g_str_has_suffix (entry_name, ".py")) - Command_PyLoad((char*)entry_name); - } - g_dir_close (dir); - g_chdir (oldcwd); -} - -static void -Util_Autoload() -{ - const char *xdir; - char *sub_dir; - /* we need local filesystem encoding for g_chdir, g_dir_open etc */ - - xdir = hexchat_get_info(ph, "configdir"); - - /* auto-load from subdirectory addons */ - sub_dir = g_build_filename (xdir, "addons", NULL); - Util_Autoload_from(sub_dir); - g_free (sub_dir); -} - -static char * -Util_Expand(char *filename) -{ - char *expanded; - - /* Check if this is an absolute path. */ - if (g_path_is_absolute(filename)) { - if (g_file_test(filename, G_FILE_TEST_EXISTS)) - return g_strdup(filename); - else - return NULL; - } - - /* Check if it starts with ~/ and expand the home if positive. */ - if (*filename == '~' && *(filename+1) == '/') { - expanded = g_build_filename(g_get_home_dir(), - filename+2, NULL); - if (g_file_test(expanded, G_FILE_TEST_EXISTS)) - return expanded; - else { - g_free(expanded); - return NULL; - } - } - - /* Check if it's in the current directory. */ - expanded = g_build_filename(g_get_current_dir(), - filename, NULL); - if (g_file_test(expanded, G_FILE_TEST_EXISTS)) - return expanded; - g_free(expanded); - - /* Check if ~/.config/hexchat/addons/ exists. */ - expanded = g_build_filename(hexchat_get_info(ph, "configdir"), - "addons", filename, NULL); - if (g_file_test(expanded, G_FILE_TEST_EXISTS)) - return expanded; - g_free(expanded); - - return NULL; -} - -/* Similar to PyEval_ReleaseThread, but accepts NULL thread states. */ -static void -Util_ReleaseThread(PyThreadState *tstate) -{ - PyThreadState *old_tstate; - if (tstate == NULL) - Py_FatalError("PyEval_ReleaseThread: NULL thread state"); - old_tstate = PyThreadState_Swap(NULL); - if (old_tstate != tstate && old_tstate != NULL) - Py_FatalError("PyEval_ReleaseThread: wrong thread state"); - PyEval_ReleaseLock(); -} - -/* ===================================================================== */ -/* Hookable functions. These are the entry points to python code, besides - * the load function, and the hooks for interactive interpreter. */ - -static int -Callback_Server(char *word[], char *word_eol[], hexchat_event_attrs *attrs, void *userdata) -{ - Hook *hook = (Hook *) userdata; - PyObject *retobj; - PyObject *word_list, *word_eol_list; - PyObject *attributes; - int ret = HEXCHAT_EAT_NONE; - PyObject *plugin; - - plugin = hook->plugin; - BEGIN_PLUGIN(plugin); - - word_list = Util_BuildList(word); - if (word_list == NULL) { - END_PLUGIN(plugin); - return HEXCHAT_EAT_NONE; - } - word_eol_list = Util_BuildList(word_eol); - if (word_eol_list == NULL) { - Py_DECREF(word_list); - END_PLUGIN(plugin); - return HEXCHAT_EAT_NONE; - } - - attributes = Attribute_New(attrs); - - if (hook->type == HOOK_XCHAT_ATTR) - retobj = PyObject_CallFunction(hook->callback, "(OOOO)", word_list, - word_eol_list, hook->userdata, attributes); - else - retobj = PyObject_CallFunction(hook->callback, "(OOO)", word_list, - word_eol_list, hook->userdata); - Py_DECREF(word_list); - Py_DECREF(word_eol_list); - Py_DECREF(attributes); - - if (retobj == Py_None) { - ret = HEXCHAT_EAT_NONE; - Py_DECREF(retobj); - } else if (retobj) { - ret = PyLong_AsLong(retobj); - Py_DECREF(retobj); - } else { - PyErr_Print(); - } - - END_PLUGIN(plugin); - - return ret; -} - -static int -Callback_Command(char *word[], char *word_eol[], void *userdata) -{ - Hook *hook = (Hook *) userdata; - PyObject *retobj; - PyObject *word_list, *word_eol_list; - int ret = HEXCHAT_EAT_NONE; - PyObject *plugin; - - plugin = hook->plugin; - BEGIN_PLUGIN(plugin); - - word_list = Util_BuildList(word); - if (word_list == NULL) { - END_PLUGIN(plugin); - return HEXCHAT_EAT_NONE; - } - word_eol_list = Util_BuildList(word_eol); - if (word_eol_list == NULL) { - Py_DECREF(word_list); - END_PLUGIN(plugin); - return HEXCHAT_EAT_NONE; - } - - retobj = PyObject_CallFunction(hook->callback, "(OOO)", word_list, - word_eol_list, hook->userdata); - Py_DECREF(word_list); - Py_DECREF(word_eol_list); - - if (retobj == Py_None) { - ret = HEXCHAT_EAT_NONE; - Py_DECREF(retobj); - } else if (retobj) { - ret = PyLong_AsLong(retobj); - Py_DECREF(retobj); - } else { - PyErr_Print(); - } - - END_PLUGIN(plugin); - - return ret; -} - -static int -Callback_Print_Attrs(char *word[], hexchat_event_attrs *attrs, void *userdata) -{ - Hook *hook = (Hook *) userdata; - PyObject *retobj; - PyObject *word_list; - PyObject *word_eol_list; - PyObject *attributes; - int ret = HEXCHAT_EAT_NONE; - PyObject *plugin; - - plugin = hook->plugin; - BEGIN_PLUGIN(plugin); - - word_list = Util_BuildList(word); - if (word_list == NULL) { - END_PLUGIN(plugin); - return HEXCHAT_EAT_NONE; - } - word_eol_list = Util_BuildEOLList(word); - if (word_eol_list == NULL) { - Py_DECREF(word_list); - END_PLUGIN(plugin); - return HEXCHAT_EAT_NONE; - } - - attributes = Attribute_New(attrs); - - retobj = PyObject_CallFunction(hook->callback, "(OOOO)", word_list, - word_eol_list, hook->userdata, attributes); - - Py_DECREF(word_list); - Py_DECREF(word_eol_list); - Py_DECREF(attributes); - - if (retobj == Py_None) { - ret = HEXCHAT_EAT_NONE; - Py_DECREF(retobj); - } else if (retobj) { - ret = PyLong_AsLong(retobj); - Py_DECREF(retobj); - } else { - PyErr_Print(); - } - - END_PLUGIN(plugin); - - return ret; -} - -static int -Callback_Print(char *word[], void *userdata) -{ - Hook *hook = (Hook *) userdata; - PyObject *retobj; - PyObject *word_list; - PyObject *word_eol_list; - int ret = HEXCHAT_EAT_NONE; - PyObject *plugin; - - plugin = hook->plugin; - BEGIN_PLUGIN(plugin); - - word_list = Util_BuildList(word); - if (word_list == NULL) { - END_PLUGIN(plugin); - return HEXCHAT_EAT_NONE; - } - word_eol_list = Util_BuildEOLList(word); - if (word_eol_list == NULL) { - Py_DECREF(word_list); - END_PLUGIN(plugin); - return HEXCHAT_EAT_NONE; - } - - retobj = PyObject_CallFunction(hook->callback, "(OOO)", word_list, - word_eol_list, hook->userdata); - - Py_DECREF(word_list); - Py_DECREF(word_eol_list); - - if (retobj == Py_None) { - ret = HEXCHAT_EAT_NONE; - Py_DECREF(retobj); - } else if (retobj) { - ret = PyLong_AsLong(retobj); - Py_DECREF(retobj); - } else { - PyErr_Print(); - } - - END_PLUGIN(plugin); - - return ret; -} - -static int -Callback_Timer(void *userdata) -{ - Hook *hook = (Hook *) userdata; - PyObject *retobj; - int ret = 0; - PyObject *plugin; - - plugin = hook->plugin; - - BEGIN_PLUGIN(hook->plugin); - - retobj = PyObject_CallFunction(hook->callback, "(O)", hook->userdata); - - if (retobj) { - ret = PyObject_IsTrue(retobj); - Py_DECREF(retobj); - } else { - PyErr_Print(); - } - - /* Returning 0 for this callback unhooks itself. */ - if (ret == 0) - Plugin_RemoveHook(plugin, hook); - - END_PLUGIN(plugin); - - return ret; -} - -#ifdef WITH_THREAD -static int -Callback_ThreadTimer(void *userdata) -{ - RELEASE_XCHAT_LOCK(); -#ifndef WIN32 - usleep(1); -#endif - ACQUIRE_XCHAT_LOCK(); - return 1; -} -#endif - -/* ===================================================================== */ -/* XChatOut object */ - -/* We keep this information global, so we can reset it when the - * deinit function is called. */ -/* XXX This should be somehow bound to the printing context. */ -static GString *xchatout_buffer = NULL; - -static PyObject * -XChatOut_New() -{ - XChatOutObject *xcoobj; - xcoobj = PyObject_New(XChatOutObject, &XChatOut_Type); - if (xcoobj != NULL) - xcoobj->softspace = 0; - return (PyObject *) xcoobj; -} - -static void -XChatOut_dealloc(PyObject *self) -{ - Py_TYPE(self)->tp_free((PyObject *)self); -} - -/* This is a little bit complex because we have to buffer data - * until a \n is received, since xchat breaks the line automatically. - * We also crop the last \n for this reason. */ -static PyObject * -XChatOut_write(PyObject *self, PyObject *args) -{ - gboolean add_space; - char *data, *pos; - - if (!PyArg_ParseTuple(args, "s:write", &data)) - return NULL; - if (!data || !*data) { - Py_RETURN_NONE; - } - BEGIN_XCHAT_CALLS(RESTORE_CONTEXT|ALLOW_THREADS); - if (((XChatOutObject *)self)->softspace) { - add_space = TRUE; - ((XChatOutObject *)self)->softspace = 0; - } else { - add_space = FALSE; - } - - g_string_append (xchatout_buffer, data); - - /* If not end of line add space to continue buffer later */ - if (add_space && xchatout_buffer->str[xchatout_buffer->len - 1] != '\n') - { - g_string_append_c (xchatout_buffer, ' '); - } - - /* If there is an end of line print up to that */ - if ((pos = strrchr (xchatout_buffer->str, '\n'))) - { - *pos = '\0'; - hexchat_print (ph, xchatout_buffer->str); - - /* Then remove it from buffer */ - g_string_erase (xchatout_buffer, 0, pos - xchatout_buffer->str + 1); - } - - END_XCHAT_CALLS(); - Py_RETURN_NONE; -} - -#define OFF(x) offsetof(XChatOutObject, x) - -static PyMemberDef XChatOut_members[] = { - {"softspace", T_INT, OFF(softspace), 0}, - {0} -}; - -static PyMethodDef XChatOut_methods[] = { - {"write", XChatOut_write, METH_VARARGS}, - {NULL, NULL} -}; - -static PyTypeObject XChatOut_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "hexchat.XChatOut", /*tp_name*/ - sizeof(XChatOutObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - XChatOut_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr,/*tp_getattro*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - XChatOut_methods, /*tp_methods*/ - XChatOut_members, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Del, /*tp_free*/ - 0, /*tp_is_gc*/ -}; - - -/* ===================================================================== */ -/* Attribute object */ - -#undef OFF -#define OFF(x) offsetof(AttributeObject, x) - -static PyMemberDef Attribute_members[] = { - {"time", T_OBJECT, OFF(time), 0}, - {0} -}; - -static void -Attribute_dealloc(PyObject *self) -{ - Py_DECREF(((AttributeObject*)self)->time); - Py_TYPE(self)->tp_free((PyObject *)self); -} - -static PyObject * -Attribute_repr(PyObject *self) -{ - return PyUnicode_FromFormat("", self); -} - -static PyTypeObject Attribute_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "hexchat.Attribute", /*tp_name*/ - sizeof(AttributeObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - Attribute_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - Attribute_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr,/*tp_getattro*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - Attribute_members, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Del, /*tp_free*/ - 0, /*tp_is_gc*/ -}; - -static PyObject * -Attribute_New(hexchat_event_attrs *attrs) -{ - AttributeObject *attr; - attr = PyObject_New(AttributeObject, &Attribute_Type); - if (attr != NULL) { - attr->time = PyLong_FromLong((long)attrs->server_time_utc); - } - return (PyObject *) attr; -} - - -/* ===================================================================== */ -/* Context object */ - -static void -Context_dealloc(PyObject *self) -{ - Py_TYPE(self)->tp_free((PyObject *)self); -} - -static PyObject * -Context_set(ContextObject *self, PyObject *args) -{ - PyObject *plugin = Plugin_GetCurrent(); - Plugin_SetContext(plugin, self->context); - Py_RETURN_NONE; -} - -static PyObject * -Context_command(ContextObject *self, PyObject *args) -{ - char *text; - if (!PyArg_ParseTuple(args, "s:command", &text)) - return NULL; - BEGIN_XCHAT_CALLS(ALLOW_THREADS); - hexchat_set_context(ph, self->context); - hexchat_command(ph, text); - END_XCHAT_CALLS(); - Py_RETURN_NONE; -} - -static PyObject * -Context_prnt(ContextObject *self, PyObject *args) -{ - char *text; - if (!PyArg_ParseTuple(args, "s:prnt", &text)) - return NULL; - BEGIN_XCHAT_CALLS(ALLOW_THREADS); - hexchat_set_context(ph, self->context); - hexchat_print(ph, text); - END_XCHAT_CALLS(); - Py_RETURN_NONE; -} - -static PyObject * -Context_emit_print(ContextObject *self, PyObject *args, PyObject *kwargs) -{ - char *argv[6]; - char *name; - int res; - long time = 0; - hexchat_event_attrs *attrs; - char *kwlist[] = {"name", "arg1", "arg2", "arg3", - "arg4", "arg5", "arg6", - "time", NULL}; - memset(&argv, 0, sizeof(char*)*6); - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|ssssssl:print_event", kwlist, &name, - &argv[0], &argv[1], &argv[2], - &argv[3], &argv[4], &argv[5], - &time)) - return NULL; - BEGIN_XCHAT_CALLS(ALLOW_THREADS); - hexchat_set_context(ph, self->context); - attrs = hexchat_event_attrs_create(ph); - attrs->server_time_utc = (time_t)time; - - res = hexchat_emit_print_attrs(ph, attrs, name, argv[0], argv[1], argv[2], - argv[3], argv[4], argv[5], NULL); - - hexchat_event_attrs_free(ph, attrs); - END_XCHAT_CALLS(); - return PyLong_FromLong(res); -} - -static PyObject * -Context_get_info(ContextObject *self, PyObject *args) -{ - const char *info; - char *name; - if (!PyArg_ParseTuple(args, "s:get_info", &name)) - return NULL; - BEGIN_XCHAT_CALLS(NONE); - hexchat_set_context(ph, self->context); - info = hexchat_get_info(ph, name); - END_XCHAT_CALLS(); - if (info == NULL) { - Py_RETURN_NONE; - } - return PyUnicode_FromString(info); -} - -static PyObject * -Context_get_list(ContextObject *self, PyObject *args) -{ - PyObject *plugin = Plugin_GetCurrent(); - hexchat_context *saved_context = Plugin_GetContext(plugin); - PyObject *ret; - Plugin_SetContext(plugin, self->context); - ret = Module_xchat_get_list((PyObject*)self, args); - Plugin_SetContext(plugin, saved_context); - return ret; -} - -/* needed to make context1 == context2 work */ -static PyObject * -Context_compare(ContextObject *a, ContextObject *b, int op) -{ - PyObject *ret; - /* check for == */ - if (op == Py_EQ) - ret = (a->context == b->context ? Py_True : Py_False); - /* check for != */ - else if (op == Py_NE) - ret = (a->context != b->context ? Py_True : Py_False); - /* only makes sense as == and != */ - else - { - PyErr_SetString(PyExc_TypeError, "contexts are either equal or not equal"); - ret = Py_None; - } - - Py_INCREF(ret); - return ret; -} - -static PyMethodDef Context_methods[] = { - {"set", (PyCFunction) Context_set, METH_NOARGS}, - {"command", (PyCFunction) Context_command, METH_VARARGS}, - {"prnt", (PyCFunction) Context_prnt, METH_VARARGS}, - {"emit_print", (PyCFunction) Context_emit_print, METH_VARARGS|METH_KEYWORDS}, - {"get_info", (PyCFunction) Context_get_info, METH_VARARGS}, - {"get_list", (PyCFunction) Context_get_list, METH_VARARGS}, - {NULL, NULL} -}; - -static PyTypeObject Context_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "hexchat.Context", /*tp_name*/ - sizeof(ContextObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - Context_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr,/*tp_getattro*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - (richcmpfunc)Context_compare, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - Context_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Del, /*tp_free*/ - 0, /*tp_is_gc*/ -}; - -static PyObject * -Context_FromContext(hexchat_context *context) -{ - ContextObject *ctxobj = PyObject_New(ContextObject, &Context_Type); - if (ctxobj != NULL) - ctxobj->context = context; - return (PyObject *) ctxobj; -} - -static PyObject * -Context_FromServerAndChannel(char *server, char *channel) -{ - ContextObject *ctxobj; - hexchat_context *context; - BEGIN_XCHAT_CALLS(NONE); - context = hexchat_find_context(ph, server, channel); - END_XCHAT_CALLS(); - if (context == NULL) - return NULL; - ctxobj = PyObject_New(ContextObject, &Context_Type); - if (ctxobj == NULL) - return NULL; - ctxobj->context = context; - return (PyObject *) ctxobj; -} - - -/* ===================================================================== */ -/* ListItem object */ - -#undef OFF -#define OFF(x) offsetof(ListItemObject, x) - -static PyMemberDef ListItem_members[] = { - {"__dict__", T_OBJECT, OFF(dict), 0}, - {0} -}; - -static void -ListItem_dealloc(PyObject *self) -{ - Py_DECREF(((ListItemObject*)self)->dict); - Py_TYPE(self)->tp_free((PyObject *)self); -} - -static PyObject * -ListItem_repr(PyObject *self) -{ - return PyUnicode_FromFormat("<%s list item at %p>", - ((ListItemObject*)self)->listname, self); -} - -static PyTypeObject ListItem_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "hexchat.ListItem", /*tp_name*/ - sizeof(ListItemObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - ListItem_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - ListItem_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr,/*tp_getattro*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - ListItem_members, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - OFF(dict), /*tp_dictoffset*/ - 0, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Del, /*tp_free*/ - 0, /*tp_is_gc*/ -}; - -static PyObject * -ListItem_New(const char *listname) -{ - ListItemObject *item; - item = PyObject_New(ListItemObject, &ListItem_Type); - if (item != NULL) { - /* listname parameter must be statically allocated. */ - item->listname = listname; - item->dict = PyDict_New(); - if (item->dict == NULL) { - Py_DECREF(item); - item = NULL; - } - } - return (PyObject *) item; -} - - -/* ===================================================================== */ -/* Plugin object */ - -#define GET_MODULE_DATA(x, force) \ - o = PyObject_GetAttrString(m, "__module_" #x "__"); \ - if (o == NULL) { \ - if (force) { \ - hexchat_print(ph, "Module has no __module_" #x "__ " \ - "defined"); \ - goto error; \ - } \ - plugin->x = g_strdup(""); \ - } else {\ - if (!PyUnicode_Check(o)) { \ - hexchat_print(ph, "Variable __module_" #x "__ " \ - "must be a string"); \ - goto error; \ - } \ - plugin->x = g_strdup(PyUnicode_AsUTF8(o)); \ - if (plugin->x == NULL) { \ - hexchat_print(ph, "Not enough memory to allocate " #x); \ - goto error; \ - } \ - } - -static PyObject * -Plugin_GetCurrent() -{ - PyObject *plugin; - plugin = PySys_GetObject("__plugin__"); - if (plugin == NULL) - PyErr_SetString(PyExc_RuntimeError, "lost sys.__plugin__"); - return plugin; -} - -static hexchat_plugin * -Plugin_GetHandle(PluginObject *plugin) -{ - /* This works but the issue is that the script must be ran to get - * the name of it thus upon first use it will use the wrong handler - * work around would be to run a fake script once to get name? */ -#if 0 - /* return fake handle for pluginpref */ - if (plugin->gui != NULL) - return plugin->gui; - else -#endif - return ph; -} - -static PluginObject * -Plugin_ByString(char *str) -{ - GSList *list; - PluginObject *plugin; - char *basename; - list = plugin_list; - while (list != NULL) { - plugin = (PluginObject *) list->data; - basename = g_path_get_basename(plugin->filename); - if (basename == NULL) - break; - if (strcasecmp(plugin->name, str) == 0 || - strcasecmp(plugin->filename, str) == 0 || - strcasecmp(basename, str) == 0) { - g_free(basename); - return plugin; - } - g_free(basename); - list = list->next; - } - return NULL; -} - -static Hook * -Plugin_AddHook(int type, PyObject *plugin, PyObject *callback, - PyObject *userdata, char *name, void *data) -{ - Hook *hook = g_new(Hook, 1); - hook->type = type; - hook->plugin = plugin; - Py_INCREF(callback); - hook->callback = callback; - Py_INCREF(userdata); - hook->userdata = userdata; - hook->name = g_strdup (name); - hook->data = NULL; - Plugin_SetHooks(plugin, g_slist_append(Plugin_GetHooks(plugin), - hook)); - - return hook; -} - -static Hook * -Plugin_FindHook(PyObject *plugin, char *name) -{ - Hook *hook = NULL; - GSList *plugin_hooks = Plugin_GetHooks(plugin); - - while (plugin_hooks) - { - if (g_strcmp0 (((Hook *)plugin_hooks->data)->name, name) == 0) - { - hook = (Hook *)plugin_hooks->data; - break; - } - - plugin_hooks = g_slist_next(plugin_hooks); - } - - return hook; -} - -static void -Plugin_RemoveHook(PyObject *plugin, Hook *hook) -{ - GSList *list; - /* Is this really a hook of the running plugin? */ - list = g_slist_find(Plugin_GetHooks(plugin), hook); - if (list) { - /* Ok, unhook it. */ - if (hook->type != HOOK_UNLOAD) { - /* This is an xchat hook. Unregister it. */ - BEGIN_XCHAT_CALLS(NONE); - hexchat_unhook(ph, (hexchat_hook*)hook->data); - END_XCHAT_CALLS(); - } - Plugin_SetHooks(plugin, - g_slist_remove(Plugin_GetHooks(plugin), - hook)); - Py_DECREF(hook->callback); - Py_DECREF(hook->userdata); - g_free(hook->name); - g_free(hook); - } -} - -static void -Plugin_RemoveAllHooks(PyObject *plugin) -{ - GSList *list = Plugin_GetHooks(plugin); - while (list) { - Hook *hook = (Hook *) list->data; - if (hook->type != HOOK_UNLOAD) { - /* This is an xchat hook. Unregister it. */ - BEGIN_XCHAT_CALLS(NONE); - hexchat_unhook(ph, (hexchat_hook*)hook->data); - END_XCHAT_CALLS(); - } - Py_DECREF(hook->callback); - Py_DECREF(hook->userdata); - g_free(hook->name); - g_free(hook); - list = list->next; - } - Plugin_SetHooks(plugin, NULL); -} - -static void -Plugin_Delete(PyObject *plugin) -{ - PyThreadState *tstate = ((PluginObject*)plugin)->tstate; - GSList *list = Plugin_GetHooks(plugin); - while (list) { - Hook *hook = (Hook *) list->data; - if (hook->type == HOOK_UNLOAD) { - PyObject *retobj; - retobj = PyObject_CallFunction(hook->callback, "(O)", - hook->userdata); - if (retobj) { - Py_DECREF(retobj); - } else { - PyErr_Print(); - PyErr_Clear(); - } - } - list = list->next; - } - Plugin_RemoveAllHooks(plugin); - if (((PluginObject *)plugin)->gui != NULL) - hexchat_plugingui_remove(ph, ((PluginObject *)plugin)->gui); - Py_DECREF(plugin); - /*PyThreadState_Swap(tstate); needed? */ - Py_EndInterpreter(tstate); -} - -static PyObject * -Plugin_New(char *filename, PyObject *xcoobj) -{ - PluginObject *plugin = NULL; - PyObject *m, *o; -#ifdef IS_PY3K - wchar_t *argv[] = { L"", 0 }; -#else - char *argv[] = { "", 0 }; -#endif - - if (filename) { - char *old_filename = filename; - filename = Util_Expand(filename); - if (filename == NULL) { - hexchat_printf(ph, "File not found: %s", old_filename); - return NULL; - } - } - - /* Allocate plugin structure. */ - plugin = PyObject_New(PluginObject, &Plugin_Type); - if (plugin == NULL) { - hexchat_print(ph, "Can't create plugin object"); - goto error; - } - - Plugin_SetName(plugin, NULL); - Plugin_SetVersion(plugin, NULL); - Plugin_SetFilename(plugin, NULL); - Plugin_SetDescription(plugin, NULL); - Plugin_SetHooks(plugin, NULL); - Plugin_SetContext(plugin, hexchat_get_context(ph)); - Plugin_SetGui(plugin, NULL); - - /* Start a new interpreter environment for this plugin. */ - PyEval_AcquireThread(main_tstate); - plugin->tstate = Py_NewInterpreter(); - if (plugin->tstate == NULL) { - hexchat_print(ph, "Can't create interpreter state"); - goto error; - } - - PySys_SetArgv(1, argv); - PySys_SetObject("__plugin__", (PyObject *) plugin); - - /* Set stdout and stderr to xchatout. */ - Py_INCREF(xcoobj); - PySys_SetObject("stdout", xcoobj); - Py_INCREF(xcoobj); - PySys_SetObject("stderr", xcoobj); - - if (filename) { -#ifdef WIN32 - char *file; - if (!g_file_get_contents(filename, &file, NULL, NULL)) { - hexchat_printf(ph, "Can't open file %s: %s\n", - filename, strerror(errno)); - goto error; - } - - if (PyRun_SimpleString(file) != 0) { - hexchat_printf(ph, "Error loading module %s\n", - filename); - g_free (file); - goto error; - } - - plugin->filename = filename; - filename = NULL; - g_free (file); -#else - FILE *fp; - plugin->filename = filename; - - /* It's now owned by the plugin. */ - filename = NULL; - - /* Open the plugin file. */ - fp = fopen(plugin->filename, "r"); - if (fp == NULL) { - hexchat_printf(ph, "Can't open file %s: %s\n", - plugin->filename, strerror(errno)); - goto error; - } - - /* Run the plugin. */ - if (PyRun_SimpleFile(fp, plugin->filename) != 0) { - hexchat_printf(ph, "Error loading module %s\n", - plugin->filename); - fclose(fp); - goto error; - } - fclose(fp); -#endif - m = PyDict_GetItemString(PyImport_GetModuleDict(), - "__main__"); - if (m == NULL) { - hexchat_print(ph, "Can't get __main__ module"); - goto error; - } - GET_MODULE_DATA(name, 1); - GET_MODULE_DATA(version, 0); - GET_MODULE_DATA(description, 0); - plugin->gui = hexchat_plugingui_add(ph, plugin->filename, - plugin->name, - plugin->description, - plugin->version, NULL); - } - - PyEval_ReleaseThread(plugin->tstate); - - return (PyObject *) plugin; - -error: - g_free(filename); - - if (plugin) { - if (plugin->tstate) - Plugin_Delete((PyObject *)plugin); - else - Py_DECREF(plugin); - } - PyEval_ReleaseLock(); - - return NULL; -} - -static void -Plugin_dealloc(PluginObject *self) -{ - g_free(self->filename); - g_free(self->name); - g_free(self->version); - g_free(self->description); - Py_TYPE(self)->tp_free((PyObject *)self); -} - -static PyTypeObject Plugin_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "hexchat.Plugin", /*tp_name*/ - sizeof(PluginObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - (destructor)Plugin_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr,/*tp_getattro*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Del, /*tp_free*/ - 0, /*tp_is_gc*/ -}; - - -/* ===================================================================== */ -/* XChat module */ - -static PyObject * -Module_hexchat_command(PyObject *self, PyObject *args) -{ - char *text; - if (!PyArg_ParseTuple(args, "s:command", &text)) - return NULL; - BEGIN_XCHAT_CALLS(RESTORE_CONTEXT|ALLOW_THREADS); - hexchat_command(ph, text); - END_XCHAT_CALLS(); - Py_RETURN_NONE; -} - -static PyObject * -Module_xchat_prnt(PyObject *self, PyObject *args) -{ - char *text; - if (!PyArg_ParseTuple(args, "s:prnt", &text)) - retu