summaryrefslogtreecommitdiffstats
path: root/xbmc/interfaces/python/swig.cpp
blob: 0c49f87ca84e1d30297560379e1c9c45b21d9b55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/*
 *  Copyright (C) 2005-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#include "swig.h"

#include "LanguageHook.h"
#include "interfaces/legacy/AddonString.h"
#include "utils/StringUtils.h"

#include <string>

namespace PythonBindings
{
  TypeInfo::TypeInfo(const std::type_info& ti) : swigType(NULL), parentType(NULL), typeIndex(ti)
  {
    static PyTypeObject py_type_object_header = {
      PyVarObject_HEAD_INIT(nullptr, 0) 0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
#if PY_VERSION_HEX > 0x03080000
      0,
      0,
#endif
#if PY_VERSION_HEX < 0x03090000
      0,
#endif
#if PY_VERSION_HEX >= 0x030C00A1
      0,
#endif
    };

    static int size = (long*)&(py_type_object_header.tp_name) - (long*)&py_type_object_header;
    memcpy(&(this->pythonType), &py_type_object_header, size);
  }

  class PyObjectDecrementor
  {
    PyObject* obj;
  public:
    inline explicit PyObjectDecrementor(PyObject* pyobj) : obj(pyobj) {}
    inline ~PyObjectDecrementor() { Py_XDECREF(obj); }

    inline PyObject* get() { return obj; }
  };

  void PyXBMCGetUnicodeString(std::string& buf, PyObject* pObject, bool coerceToString,
                              const char* argumentName, const char* methodname)
  {
    // It's okay for a string to be "None". In this case the buf returned
    // will be the emptyString.
    if (pObject == Py_None)
    {
      buf = XBMCAddon::emptyString;
      return;
    }

    //! @todo UTF-8: Does python use UTF-16?
    //!              Do we need to convert from the string charset to UTF-8
    //!              for non-unicode data?
    if (PyUnicode_Check(pObject))
    {
      // Python unicode objects are UCS2 or UCS4 depending on compilation
      // options, wchar_t is 16-bit or 32-bit depending on platform.
      // Avoid the complexity by just letting python convert the string.

      buf = PyUnicode_AsUTF8(pObject);
      return;
    }

    if (PyBytes_Check(pObject)) // If pobject is of type Bytes
    {
      buf = PyBytes_AsString(pObject);
      return;
    }

    // if we got here then we need to coerce the value to a string
    if (coerceToString)
    {
      PyObjectDecrementor dec(PyObject_Str(pObject));
      PyObject* pyStrCast = dec.get();
      if (pyStrCast)
      {
        PyXBMCGetUnicodeString(buf,pyStrCast,false,argumentName,methodname);
        return;
      }
    }

    // Object is not a unicode or a normal string.
    buf = "";
    throw XBMCAddon::WrongTypeException("argument \"%s\" for method \"%s\" must be unicode or str", argumentName, methodname);
  }

  // need to compare the typestring
  bool isParameterRightType(const char* passedType, const char* expectedType, const char* methodNamespacePrefix, bool tryReverse)
  {
    if (strcmp(expectedType,passedType) == 0)
      return true;

    // well now things are a bit more complicated. We need to see if the passed type
    // is a subset of the overall type
    std::string et(expectedType);
    bool isPointer = (et[0] == 'p' && et[1] == '.');
    std::string baseType(et,(isPointer ? 2 : 0)); // this may contain a namespace

    std::string ns(methodNamespacePrefix);
    // cut off trailing '::'
    if (ns.size() > 2 && ns[ns.size() - 1] == ':' && ns[ns.size() - 2] == ':')
      ns = ns.substr(0,ns.size()-2);

    bool done = false;
    while(! done)
    {
      done = true;

      // now we need to see if the expected type can be munged
      //  into the passed type by tacking on the namespace of
      //  of the method.
      std::string check(isPointer ? "p." : "");
      check += ns;
      check += "::";
      check += baseType;

      if (strcmp(check.c_str(),passedType) == 0)
        return true;

      // see if the namespace is nested.
      int posOfScopeOp = ns.find("::");
      if (posOfScopeOp >= 0)
      {
        done = false;
        // cur off the outermost namespace
        ns = ns.substr(posOfScopeOp + 2);
      }
    }

    // so far we applied the namespace to the expected type. Now lets try
    //  the reverse if we haven't already.
    if (tryReverse)
      return isParameterRightType(expectedType, passedType, methodNamespacePrefix, false);

    return false;
  }

  PythonToCppException::PythonToCppException() : XbmcCommons::UncheckedException(" ")
  {
    setClassname("PythonToCppException");

    std::string msg;
    std::string type, value, traceback;
    if (!ParsePythonException(type, value, traceback))
      UncheckedException::SetMessage("Strange: No Python exception occurred");
    else
      SetMessage(type, value, traceback);
  }

  PythonToCppException::PythonToCppException(const std::string &exceptionType, const std::string &exceptionValue, const std::string &exceptionTraceback) : XbmcCommons::UncheckedException(" ")
  {
    setClassname("PythonToCppException");

    SetMessage(exceptionType, exceptionValue, exceptionTraceback);
  }

  bool PythonToCppException::ParsePythonException(std::string &exceptionType, std::string &exceptionValue, std::string &exceptionTraceback)
  {
    PyObject* exc_type;
    PyObject* exc_value;
    PyObject* exc_traceback;
    PyObject* pystring = NULL;

    PyErr_Fetch(&exc_type, &exc_value, &exc_traceback);
    if (exc_type == NULL && exc_value == NULL && exc_traceback == NULL)
      return false;

    // See https://docs.python.org/3/c-api/exceptions.html#c.PyErr_NormalizeException
    PyErr_NormalizeException(&exc_type, &exc_value, &exc_traceback);
    if (exc_traceback != NULL) {
      PyException_SetTraceback(exc_value, exc_traceback);
    }

    exceptionType.clear();
    exceptionValue.clear();
    exceptionTraceback.clear();

    if (exc_type != NULL && (pystring = PyObject_Str(exc_type)) != NULL && PyUnicode_Check(pystring))
    {
      const char* str = PyUnicode_AsUTF8(pystring);
      if (str != NULL)
        exceptionType = str;

      pystring = PyObject_Str(exc_value);
      if (pystring != NULL)
      {
        str = PyUnicode_AsUTF8(pystring);
        exceptionValue = str;
      }

      PyObject *tracebackModule = PyImport_ImportModule("traceback");
      if (tracebackModule != NULL)
      {
        char method[] = "format_exception";
        char format[] = "OOO";
        PyObject *tbList = PyObject_CallMethod(tracebackModule, method, format, exc_type, exc_value == NULL ? Py_None : exc_value, exc_traceback == NULL ? Py_None : exc_traceback);

        if (tbList)
        {
          PyObject* emptyString = PyUnicode_FromString("");
          char method[] = "join";
          char format[] = "O";
          PyObject *strRetval = PyObject_CallMethod(emptyString, method, format, tbList);
          Py_DECREF(emptyString);

          if (strRetval)
          {
            str = PyUnicode_AsUTF8(strRetval);
            if (str != NULL)
              exceptionTraceback = str;
            Py_DECREF(strRetval);
          }
          Py_DECREF(tbList);
        }
        Py_DECREF(tracebackModule);

      }
    }

    Py_XDECREF(exc_type);
    Py_XDECREF(exc_value);
    Py_XDECREF(exc_traceback);
    Py_XDECREF(pystring);

    return true;
  }

  void PythonToCppException::SetMessage(const std::string &exceptionType, const std::string &exceptionValue, const std::string &exceptionTraceback)
  {
    std::string msg = "-->Python callback/script returned the following error<--\n";
    msg += " - NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!\n";

    if (!exceptionType.empty())
    {
      msg += StringUtils::Format("Error Type: {}\n", exceptionType);

      if (!exceptionValue.empty())
        msg += StringUtils::Format("Error Contents: {}\n", exceptionValue);

      if (!exceptionTraceback.empty())
        msg += exceptionTraceback;

      msg += "-->End of Python script error report<--\n";
    }
    else
      msg += "<unknown exception type>";

    UncheckedException::SetMessage("%s", msg.c_str());
  }

  XBMCAddon::AddonClass* doretrieveApiInstance(const PyHolder* pythonObj, const TypeInfo* typeInfo, const char* expectedType,
                              const char* methodNamespacePrefix, const char* methodNameForErrorString)
  {
    if (pythonObj->magicNumber != XBMC_PYTHON_TYPE_MAGIC_NUMBER)
      throw XBMCAddon::WrongTypeException("Non api type passed to \"%s\" in place of the expected type \"%s.\"",
                                          methodNameForErrorString, expectedType);
    if (!isParameterRightType(typeInfo->swigType,expectedType,methodNamespacePrefix))
    {
      // maybe it's a child class
      if (typeInfo->parentType)
        return doretrieveApiInstance(pythonObj, typeInfo->parentType,expectedType,
                                     methodNamespacePrefix, methodNameForErrorString);
      else
        throw XBMCAddon::WrongTypeException("Incorrect type passed to \"%s\", was expecting a \"%s\" but received a \"%s\"",
                                 methodNameForErrorString,expectedType,typeInfo->swigType);
    }
    return const_cast<XBMCAddon::AddonClass*>(pythonObj->pSelf);
  }

  /**
   * This method is a helper for the generated API. It's called prior to any API
   * class constructor being returned from the generated code to Python
   */
  void prepareForReturn(XBMCAddon::AddonClass* c)
  {
    XBMC_TRACE;
    if(c) {
      c->Acquire();
      PyThreadState* state = PyThreadState_Get();
      XBMCAddon::Python::PythonLanguageHook::GetIfExists(state->interp)->RegisterAddonClassInstance(c);
    }
  }

  static bool handleInterpRegistrationForClean(XBMCAddon::AddonClass* c)
  {
    XBMC_TRACE;
    if(c){
      XBMCAddon::AddonClass::Ref<XBMCAddon::Python::PythonLanguageHook> lh =
        XBMCAddon::AddonClass::Ref<XBMCAddon::AddonClass>(c->GetLanguageHook());

      if (lh.isNotNull())
      {
        lh->UnregisterAddonClassInstance(c);
        return true;
      }
      else
      {
        PyThreadState* state = PyThreadState_Get();
        lh = XBMCAddon::Python::PythonLanguageHook::GetIfExists(state->interp);
        if (lh.isNotNull()) lh->UnregisterAddonClassInstance(c);
        return true;
      }
    }
    return false;
  }

  /**
   * This method is a helper for the generated API. It's called prior to any API
   * class destructor being dealloc-ed from the generated code from Python
   */
  void cleanForDealloc(XBMCAddon::AddonClass* c)
  {
    XBMC_TRACE;
    if (handleInterpRegistrationForClean(c))
      c->Release();
  }

  /**
   * This method is a helper for the generated API. It's called prior to any API
   * class destructor being dealloc-ed from the generated code from Python
   *
   * There is a Catch-22 in the destruction of a Window. 'dispose' needs to be
   * called on destruction but cannot be called from the destructor.
   * This overrides the default cleanForDealloc to resolve that.
   */
  void cleanForDealloc(XBMCAddon::xbmcgui::Window* c)
  {
    XBMC_TRACE;
    if (handleInterpRegistrationForClean(c))
    {
      c->dispose();
      c->Release();
    }
  }

  /**
   * This method allows for conversion of the native api Type to the Python type.
   *
   * When this form of the call is used (and pytype isn't NULL) then the
   * passed type is used in the instance. This is for classes that extend API
   * classes in python. The type passed may not be the same type that's stored
   * in the class metadata of the AddonClass of which 'api' is an instance,
   * it can be a subclass in python.
   *
   * if pytype is NULL then the type is inferred using the class metadata
   * stored in the AddonClass instance 'api'.
   */
  PyObject* makePythonInstance(XBMCAddon::AddonClass* api, PyTypeObject* pytype, bool incrementRefCount)
  {
    // null api types result in Py_None
    if (!api)
    {
      Py_INCREF(Py_None);
      return Py_None;
    }

    // retrieve the TypeInfo from the api class
    const TypeInfo* typeInfo = getTypeInfoForInstance(api);
    PyTypeObject* typeObj = pytype == NULL ? const_cast<PyTypeObject*>(&(typeInfo->pythonType)) : pytype;

    PyHolder* self = reinterpret_cast<PyHolder*>(typeObj->tp_alloc(typeObj,0));
    if (!self) return NULL;
    self->magicNumber = XBMC_PYTHON_TYPE_MAGIC_NUMBER;
    self->typeInfo = typeInfo;
    self->pSelf = api;
    if (incrementRefCount)
      Py_INCREF((PyObject*)self);
    return (PyObject*)self;
  }

  std::map<std::type_index, const TypeInfo*> typeInfoLookup;

  void registerAddonClassTypeInformation(const TypeInfo* classInfo)
  {
    typeInfoLookup[classInfo->typeIndex] = classInfo;
  }

  const TypeInfo* getTypeInfoForInstance(XBMCAddon::AddonClass* obj)
  {
    std::type_index ti(typeid(*obj));
    return typeInfoLookup[ti];
  }

  int dummy_tp_init(PyObject* self, PyObject* args, PyObject* kwds)
  {
    return 0;
  }
}