]> icculus.org git repositories - dana/openbox.git/blob - src/python.cc
free the surfaces' pixeldata after rendering it
[dana/openbox.git] / src / python.cc
1 // -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 2; -*-
2
3 #include "python.hh"
4 #include "openbox.hh"
5 #include "actions.hh"
6 #include "python.hh"
7 #include "bindings.hh"
8 #include "otk/display.hh"
9 #include "otk/util.hh"
10
11 namespace ob {
12
13 static PyObject *obdict = NULL;
14
15 void python_init(char *argv0)
16 {
17   // start the python engine
18   Py_SetProgramName(argv0);
19   Py_Initialize();
20   // prepend the openbox directories for python scripts to the sys path
21   PyRun_SimpleString("import sys");
22   PyRun_SimpleString("sys.path.insert(0, '" SCRIPTDIR "')");
23   PyRun_SimpleString(const_cast<char*>(("sys.path.insert(0, '" +
24                                         otk::expandTilde("~/.openbox/python") +
25                                         "')").c_str()));
26   //PyRun_SimpleString("import ob; import otk; import config;");
27   PyRun_SimpleString("import config;");
28   // set up convenience global variables
29   //PyRun_SimpleString("ob.openbox = ob.Openbox_instance()");
30   //PyRun_SimpleString("otk.display = otk.Display_instance()");
31
32   // set up access to the python global variables
33   PyObject *obmodule = PyImport_AddModule("config");
34   obdict = PyModule_GetDict(obmodule);
35 }
36
37 void python_destroy()
38 {
39   Py_Finalize();
40 }
41
42 bool python_exec(const std::string &path)
43 {
44   FILE *rcpyfd = fopen(path.c_str(), "r");
45   if (!rcpyfd) {
46     printf("Failed to load python file %s\n", path.c_str());
47     return false;
48   }
49   PyRun_SimpleFile(rcpyfd, const_cast<char*>(path.c_str()));
50   fclose(rcpyfd);
51   return true;
52 }
53
54 bool python_get_long(const char *name, long *value)
55 {
56   PyObject *val = PyDict_GetItemString(obdict, const_cast<char*>(name));
57   if (!(val && PyInt_Check(val))) return false;
58   
59   *value = PyInt_AsLong(val);
60   return true;
61 }
62
63 bool python_get_string(const char *name, otk::ustring *value)
64 {
65   PyObject *val = PyDict_GetItemString(obdict, const_cast<char*>(name));
66   if (!(val && PyString_Check(val))) return false;
67   
68   *value = PyString_AsString(val);
69   return true;
70 }
71
72 bool python_get_stringlist(const char *name, std::vector<otk::ustring> *value)
73 {
74   PyObject *val = PyDict_GetItemString(obdict, const_cast<char*>(name));
75   if (!(val && PyList_Check(val))) return false;
76
77   for (int i = 0, end = PyList_Size(val); i < end; ++i) {
78     PyObject *str = PyList_GetItem(val, i);
79     if (PyString_Check(str))
80       value->push_back(PyString_AsString(str));
81   }
82   return true;
83 }
84
85 }