summaryrefslogtreecommitdiffstats
path: root/xbmc/interfaces/python/PythonInvoker.h
blob: dd093ed73acd6ed14b1b3eeac1c8d96cc22431e6 (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
/*
 *  Copyright (C) 2013-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.
 */

#pragma once

#include "interfaces/generic/ILanguageInvoker.h"
#include "interfaces/legacy/Addon.h"
#include "interfaces/python/LanguageHook.h"
#include "threads/CriticalSection.h"
#include "threads/Event.h"

#include <map>
#include <string>
#include <vector>

typedef struct _object PyObject;

class CPythonInvoker : public ILanguageInvoker
{
public:
  explicit CPythonInvoker(ILanguageInvocationHandler* invocationHandler);
  ~CPythonInvoker() override;

  bool Execute(const std::string& script,
               const std::vector<std::string>& arguments = std::vector<std::string>()) override;

  bool IsStopping() const override { return m_stop || ILanguageInvoker::IsStopping(); }

  typedef PyObject* (*PythonModuleInitialization)();

protected:
  // implementation of ILanguageInvoker
  bool execute(const std::string& script, const std::vector<std::string>& arguments) override;
  virtual void executeScript(FILE* fp, const std::string& script, PyObject* moduleDict);
  bool stop(bool abort) override;
  void onExecutionDone() override;
  void onExecutionFailed() override;

  // custom virtual methods
  virtual std::map<std::string, PythonModuleInitialization> getModules() const = 0;
  virtual const char* getInitializationScript() const = 0;
  virtual void onInitialization();
  // actually a PyObject* but don't wanna draw Python.h include into the header
  virtual void onPythonModuleInitialization(void* moduleDict);
  virtual void onDeinitialization();

  virtual void onSuccess() {}
  virtual void onAbort() {}
  virtual void onError(const std::string& exceptionType = "",
                       const std::string& exceptionValue = "",
                       const std::string& exceptionTraceback = "");

  std::string m_sourceFile;
  CCriticalSection m_critical;

private:
  void initializeModules(const std::map<std::string, PythonModuleInitialization>& modules);
  bool initializeModule(PythonModuleInitialization module);
  void getAddonModuleDeps(const ADDON::AddonPtr& addon, std::set<std::string>& paths);
  bool execute(const std::string& script, std::vector<std::wstring>& arguments);
  FILE* PyFile_AsFileWithMode(PyObject* py_file, const char* mode);

  PyThreadState* m_threadState;
  bool m_stop;
  CEvent m_stoppedEvent;

  XBMCAddon::AddonClass::Ref<XBMCAddon::Python::PythonLanguageHook> m_languageHook;
  bool m_systemExitThrown = false;

  static CCriticalSection s_critical;
};