[osx/ios] remove unused function
[vuplus_xbmc] / xbmc / interfaces / python / xbmcmodule / xbmcmodule.cpp
1 /*
2  *      Copyright (C) 2005-2008 Team XBMC
3  *      http://www.xbmc.org
4  *
5  *  This Program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2, or (at your option)
8  *  any later version.
9  *
10  *  This Program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with XBMC; see the file COPYING.  If not, write to
17  *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
18  *  http://www.gnu.org/copyleft/gpl.html
19  *
20  */
21
22 #include "system.h"
23 #if (defined USE_EXTERNAL_PYTHON)
24   #if (defined HAVE_LIBPYTHON2_6)
25     #include <python2.6/Python.h>
26   #elif (defined HAVE_LIBPYTHON2_5)
27     #include <python2.5/Python.h>
28   #elif (defined HAVE_LIBPYTHON2_4)
29     #include <python2.4/Python.h>
30   #else
31     #error "Could not determine version of Python to use."
32   #endif
33 #else
34   #include "python/Include/Python.h"
35 #endif
36 #include "../XBPythonDll.h"
37 #include "player.h"
38 #include "pyplaylist.h"
39 #include "keyboard.h"
40 #include "storage/IoSupport.h"
41 #ifndef _LINUX
42 #include <ConIo.h>
43 #endif
44 #include "infotagvideo.h"
45 #include "infotagmusic.h"
46 #ifdef HAS_HTTPAPI
47 #include "interfaces/http-api/XBMChttp.h"
48 #include "interfaces/http-api/HttpApi.h"
49 #endif
50 #include "pyjsonrpc.h"
51 #include "GUIInfoManager.h"
52 #include "guilib/GUIWindowManager.h"
53 #include "guilib/GUIAudioManager.h"
54 #include "Application.h"
55 #include "utils/Crc32.h"
56 #include "utils/URIUtils.h"
57 #include "Util.h"
58 #include "filesystem/File.h"
59 #include "filesystem/SpecialProtocol.h"
60 #include "settings/GUISettings.h"
61 #include "guilib/TextureManager.h"
62 #include "LangInfo.h"
63 #include "SectionLoader.h"
64 #include "settings/Settings.h"
65 #include "guilib/LocalizeStrings.h"
66 #include "utils/FileUtils.h"
67 #include "pythreadstate.h"
68
69 // include for constants
70 #include "pyutil.h"
71 #include "PlayListPlayer.h"
72
73 using namespace std;
74 using namespace XFILE;
75
76 #ifndef __GNUC__
77 #pragma code_seg("PY_TEXT")
78 #pragma data_seg("PY_DATA")
79 #pragma bss_seg("PY_BSS")
80 #pragma const_seg("PY_RDATA")
81 #endif
82
83 #if defined(__GNUG__) && (__GNUC__>4) || (__GNUC__==4 && __GNUC_MINOR__>=2)
84 #pragma GCC diagnostic ignored "-Wstrict-aliasing"
85 #endif
86
87 #ifdef __cplusplus
88 extern "C" {
89 #endif
90
91 namespace PYXBMC
92 {
93 /*****************************************************************
94  * start of xbmc methods
95  *****************************************************************/
96
97   // output() method
98   PyDoc_STRVAR(output__doc__,
99     "output(msg[, level]) -- Write a string to XBMC's log file and the debug window.\n"
100     "\n"
101     "msg            : string - text to output.\n"
102     "level          : [opt] integer - log level to ouput at. (default=LOGNOTICE)\n"
103     "\n"
104     "*Note, You can use the above as keywords for arguments and skip certain optional arguments.\n"
105     "       Once you use a keyword, all following arguments require the keyword.\n"
106     "\n"
107     "       Text is written to the log for the following conditions.\n"
108     "         XBMC loglevel == -1 (NONE, nothing at all is logged)"
109     "         XBMC loglevel == 0 (NORMAL, shows LOGNOTICE, LOGERROR, LOGSEVERE and LOGFATAL)"
110     "         XBMC loglevel == 1 (DEBUG, shows all)"
111     "       See pydocs for valid values for level.\n"
112     "\n"
113     "example:\n"
114     "  - xbmc.output(msg='This is a test string.', level=xbmc.LOGDEBUG)\n");
115
116   PyObject* XBMC_Output(PyObject *self, PyObject *args, PyObject *kwds)
117   {
118     static const char *keywords[] = {
119       "msg",
120       "level",
121       NULL};
122
123     char *s_line = NULL;
124     int iLevel = LOGNOTICE;
125     if (!PyArg_ParseTupleAndKeywords(
126       args,
127       kwds,
128       (char*)"s|i",
129       (char**)keywords,
130       &s_line,
131       &iLevel))
132     {
133       return NULL;
134     }
135     // check for a valid loglevel
136     if (iLevel < LOGDEBUG || iLevel > LOGNONE)
137       iLevel = LOGNOTICE;
138     CLog::Log(iLevel, "%s", s_line);
139
140     Py_INCREF(Py_None);
141     return Py_None;
142   }
143
144   // log() method
145   PyDoc_STRVAR(log__doc__,
146     "log(msg[, level]) -- Write a string to XBMC's log file.\n"
147     "\n"
148     "msg            : string - text to output.\n"
149     "level          : [opt] integer - log level to ouput at. (default=LOGNOTICE)\n"
150     "\n"
151     "\n"
152     "*Note, You can use the above as keywords for arguments and skip certain optional arguments.\n"
153     "       Once you use a keyword, all following arguments require the keyword.\n"
154     "\n"
155     "       Text is written to the log for the following conditions.\n"
156     "         XBMC loglevel == -1 (NONE, nothing at all is logged)"
157     "         XBMC loglevel == 0 (NORMAL, shows LOGNOTICE, LOGERROR, LOGSEVERE and LOGFATAL)"
158     "         XBMC loglevel == 1 (DEBUG, shows all)"
159     "       See pydocs for valid values for level.\n"
160     "\n"
161     "example:\n"
162     "  - xbmc.log(msg='This is a test string.', level=xbmc.LOGDEBUG)\n");
163
164   PyObject* XBMC_Log(PyObject *self, PyObject *args, PyObject *kwds)
165   {
166     static const char *keywords[] = {
167       "msg",
168       "level",
169       NULL};
170
171     char *s_line = NULL;
172     int iLevel = LOGNOTICE;
173     if (!PyArg_ParseTupleAndKeywords(
174       args,
175       kwds,
176       (char*)"s|i",
177       (char**)keywords,
178       &s_line,
179       &iLevel))
180     {
181       return NULL;
182     }
183     // check for a valid loglevel
184     if (iLevel < LOGDEBUG || iLevel > LOGNONE)
185       iLevel = LOGNOTICE;
186     CLog::Log(iLevel, "%s", s_line);
187
188     Py_INCREF(Py_None);
189     return Py_None;
190   }
191
192   // shutdown() method
193   PyDoc_STRVAR(shutdown__doc__,
194     "shutdown() -- Shutdown the xbox.\n"
195     "\n"
196     "example:\n"
197     "  - xbmc.shutdown()\n");
198
199   PyObject* XBMC_Shutdown(PyObject *self, PyObject *args)
200   {
201     ThreadMessage tMsg = {TMSG_SHUTDOWN};
202     g_application.getApplicationMessenger().SendMessage(tMsg);
203
204     Py_INCREF(Py_None);
205     return Py_None;
206   }
207
208   // dashboard() method
209   PyDoc_STRVAR(dashboard__doc__,
210     "dashboard() -- Boot to dashboard as set in My Pograms/General.\n"
211     "\n"
212     "example:\n"
213     "  - xbmc.dashboard()\n");
214
215   PyObject* XBMC_Dashboard(PyObject *self, PyObject *args)
216   {
217     ThreadMessage tMsg = {TMSG_DASHBOARD};
218     g_application.getApplicationMessenger().SendMessage(tMsg);
219
220     Py_INCREF(Py_None);
221     return Py_None;
222   }
223
224   // restart() method
225   PyDoc_STRVAR(restart__doc__,
226     "restart() -- Restart the xbox.\n"
227     "\n"
228     "example:\n"
229     "  - xbmc.restart()\n");
230
231   PyObject* XBMC_Restart(PyObject *self, PyObject *args)
232   {
233     ThreadMessage tMsg = {TMSG_RESTART};
234     g_application.getApplicationMessenger().SendMessage(tMsg);
235
236     Py_INCREF(Py_None);
237     return Py_None;
238   }
239
240   // executescript() method
241   PyDoc_STRVAR(executeScript__doc__,
242     "executescript(script) -- Execute a python script.\n"
243     "\n"
244     "script         : string - script filename to execute.\n"
245     "\n"
246     "example:\n"
247     "  - xbmc.executescript('special://home/scripts/update.py')\n");
248
249   PyObject* XBMC_ExecuteScript(PyObject *self, PyObject *args)
250   {
251     char *cLine = NULL;
252     if (!PyArg_ParseTuple(args, (char*)"s", &cLine)) return NULL;
253
254     ThreadMessage tMsg = {TMSG_EXECUTE_SCRIPT};
255     tMsg.strParam = cLine;
256     g_application.getApplicationMessenger().SendMessage(tMsg);
257
258     Py_INCREF(Py_None);
259     return Py_None;
260   }
261
262   // executebuiltin() method
263   PyDoc_STRVAR(executeBuiltIn__doc__,
264     "executebuiltin(function) -- Execute a built in XBMC function.\n"
265     "\n"
266     "function       : string - builtin function to execute.\n"
267     "\n"
268     "List of functions - http://wiki.xbmc.org/?title=List_of_Built_In_Functions \n"
269     "\n"
270     "example:\n"
271     "  - xbmc.executebuiltin('XBMC.RunXBE(c:\\\\avalaunch.xbe)')\n");
272
273   PyObject* XBMC_ExecuteBuiltIn(PyObject *self, PyObject *args)
274   {
275     char *cLine = NULL;
276     if (!PyArg_ParseTuple(args, (char*)"s", &cLine)) return NULL;
277
278     g_application.getApplicationMessenger().ExecBuiltIn(cLine);
279
280     Py_INCREF(Py_None);
281     return Py_None;
282   }
283
284 #ifdef HAS_HTTPAPI
285   // executehttpapi() method
286   PyDoc_STRVAR(executeHttpApi__doc__,
287     "executehttpapi(httpcommand) -- Execute an HTTP API command.\n"
288     "\n"
289     "httpcommand    : string - http command to execute.\n"
290     "\n"
291     "List of commands - http://wiki.xbmc.org/?title=WebServerHTTP-API#The_Commands \n"
292     "\n"
293     "example:\n"
294     "  - response = xbmc.executehttpapi('TakeScreenShot(special://temp/test.jpg,0,false,200,-1,90)')\n");
295
296   PyObject* XBMC_ExecuteHttpApi(PyObject *self, PyObject *args)
297   {
298     char *cLine = NULL;
299     if (!PyArg_ParseTuple(args, (char*)"s", &cLine)) return NULL;
300     if (!m_pXbmcHttp)
301       m_pXbmcHttp = new CXbmcHttp();
302     CStdString method = cLine;
303
304     int open, close;
305     CStdString parameter="", cmd=cLine, execute;
306     open = cmd.Find("(");
307     if (open>0)
308     {
309       close=cmd.length();
310       while (close>open && cmd.Mid(close,1)!=")")
311         close--;
312       if (close>open)
313       {
314         parameter = cmd.Mid(open + 1, close - open - 1);
315         parameter.Replace(",",";");
316         execute = cmd.Left(open);
317       }
318       else //open bracket but no close
319         return PyString_FromString("");
320     }
321     else //no parameters
322       execute = cmd;
323
324     CURL::Decode(parameter);
325     return PyString_FromString(CHttpApi::MethodCall(execute, parameter).c_str());
326   }
327 #endif
328
329 #ifdef HAS_JSONRPC
330   // executehttpapi() method
331   PyDoc_STRVAR(executeJSONRPC__doc__,
332     "executeJSONRPC(jsonrpccommand) -- Execute an JSONRPC command.\n"
333     "\n"
334     "jsonrpccommand    : string - jsonrpc command to execute.\n"
335     "\n"
336     "List of commands - \n"
337     "\n"
338     "example:\n"
339     "  - response = xbmc.executeJSONRPC('{ \"jsonrpc\": \"2.0\", \"method\": \"JSONRPC.Introspect\", \"id\": 1 }')\n");
340
341   PyObject* XBMC_ExecuteJSONRPC(PyObject *self, PyObject *args)
342   {
343     char *cLine = NULL;
344     if (!PyArg_ParseTuple(args, (char*)"s", &cLine))
345       return NULL;
346
347     CStdString method = cLine;
348
349     CPythonTransport transport;
350     CPythonTransport::CPythonClient client;
351
352     return PyString_FromString(JSONRPC::CJSONRPC::MethodCall(method, &transport, &client).c_str());
353   }
354 #endif
355
356   // sleep() method
357   PyDoc_STRVAR(sleep__doc__,
358     "sleep(time) -- Sleeps for 'time' msec.\n"
359     "\n"
360     "time           : integer - number of msec to sleep.\n"
361     "\n"
362     "*Note, This is useful if you have for example a Player class that is waiting\n"
363     "       for onPlayBackEnded() calls.\n"
364     "\n"
365     "Throws: PyExc_TypeError, if time is not an integer.\n"
366     "\n"
367     "example:\n"
368     "  - xbmc.sleep(2000) # sleeps for 2 seconds\n");
369
370   PyObject* XBMC_Sleep(PyObject *self, PyObject *args)
371   {
372     PyObject *pObject;
373     if (!PyArg_ParseTuple(args, (char*)"O", &pObject)) return NULL;
374     if (!PyInt_Check(pObject))
375     {
376       PyErr_Format(PyExc_TypeError, "argument must be a bool(integer) value");
377       return NULL;
378     }
379
380     long i = PyInt_AsLong(pObject);
381     //while(i != 0)
382     //{
383       CPyThreadState pyState;
384       Sleep(i);//(500);
385       pyState.Restore();
386
387       PyXBMC_MakePendingCalls();
388       //i = PyInt_AsLong(pObject);
389     //}
390
391     Py_INCREF(Py_None);
392     return Py_None;
393   }
394
395   // getLocalizedString() method
396   PyDoc_STRVAR(getLocalizedString__doc__,
397     "getLocalizedString(id) -- Returns a localized 'unicode string'.\n"
398     "\n"
399     "id             : integer - id# for string you want to localize.\n"
400     "\n"
401     "*Note, See strings.xml in \\language\\{yourlanguage}\\ for which id\n"
402     "       you need for a string.\n"
403     "\n"
404     "example:\n"
405     "  - locstr = xbmc.getLocalizedString(6)\n");
406
407   PyObject* XBMC_GetLocalizedString(PyObject *self, PyObject *args)
408   {
409     int iString;
410     if (!PyArg_ParseTuple(args, (char*)"i", &iString)) return NULL;
411
412     CStdString label;
413     if (iString >= 30000 && iString <= 30999)
414       label = g_localizeStringsTemp.Get(iString);
415     else if (iString >= 32000 && iString <= 32999)
416       label = g_localizeStringsTemp.Get(iString);
417     else
418       label = g_localizeStrings.Get(iString);
419
420     return PyUnicode_DecodeUTF8(label.c_str(), label.size(), "replace");
421   }
422
423   // getSkinDir() method
424   PyDoc_STRVAR(getSkinDir__doc__,
425     "getSkinDir() -- Returns the active skin directory as a string.\n"
426     "\n"
427     "*Note, This is not the full path like 'special://home/addons/MediaCenter', but only 'MediaCenter'.\n"
428     "\n"
429     "example:\n"
430     "  - skindir = xbmc.getSkinDir()\n");
431
432   PyObject* XBMC_GetSkinDir(PyObject *self, PyObject *args)
433   {
434     return PyString_FromString(g_guiSettings.GetString("lookandfeel.skin"));
435   }
436
437   // getLanguage() method
438   PyDoc_STRVAR(getLanguage__doc__,
439     "getLanguage() -- Returns the active language as a string.\n"
440     "\n"
441     "example:\n"
442     "  - language = xbmc.getLanguage()\n");
443
444   PyObject* XBMC_GetLanguage(PyObject *self, PyObject *args)
445   {
446     return PyString_FromString(g_guiSettings.GetString("locale.language"));
447   }
448
449   // getIPAddress() method
450   PyDoc_STRVAR(getIPAddress__doc__,
451     "getIPAddress() -- Returns the current ip address as a string.\n"
452     "\n"
453     "example:\n"
454     "  - ip = xbmc.getIPAddress()\n");
455
456   PyObject* XBMC_GetIPAddress(PyObject *self, PyObject *args)
457   {
458     char cTitleIP[32];
459     sprintf(cTitleIP, "127.0.0.1");
460     CNetworkInterface* iface = g_application.getNetwork().GetFirstConnectedInterface();
461     if (iface)
462       return PyString_FromString(iface->GetCurrentIPAddress().c_str());
463
464     return PyString_FromString(cTitleIP);
465   }
466
467   // getDVDState() method
468   PyDoc_STRVAR(getDVDState__doc__,
469     "getDVDState() -- Returns the dvd state as an integer.\n"
470     "\n"
471     "return values are:\n"
472     "   1 : xbmc.DRIVE_NOT_READY\n"
473     "  16 : xbmc.TRAY_OPEN\n"
474     "  64 : xbmc.TRAY_CLOSED_NO_MEDIA\n"
475     "  96 : xbmc.TRAY_CLOSED_MEDIA_PRESENT\n"
476     "\n"
477     "example:\n"
478     "  - dvdstate = xbmc.getDVDState()\n");
479
480   PyObject* XBMC_GetDVDState(PyObject *self, PyObject *args)
481   {
482     return PyInt_FromLong(CIoSupport::GetTrayState());
483   }
484
485   // getFreeMem() method
486   PyDoc_STRVAR(getFreeMem__doc__,
487     "getFreeMem() -- Returns the amount of free memory in MB as an integer.\n"
488     "\n"
489     "example:\n"
490     "  - freemem = xbmc.getFreeMem()\n");
491
492   PyObject* XBMC_GetFreeMem(PyObject *self, PyObject *args)
493   {
494     MEMORYSTATUS stat;
495     GlobalMemoryStatus(&stat);
496     return PyInt_FromLong( stat.dwAvailPhys  / ( 1024 * 1024 ) );
497   }
498
499   // getCpuTemp() method
500   // ## Doesn't work right, use getInfoLabel('System.CPUTemperature') instead.
501   /*PyDoc_STRVAR(getCpuTemp__doc__,
502     "getCpuTemp() -- Returns the current cpu temperature as an integer.\n"
503     "\n"
504     "example:\n"
505     "  - cputemp = xbmc.getCpuTemp()\n");
506
507   PyObject* XBMC_GetCpuTemp(PyObject *self, PyObject *args)
508   {
509     unsigned short cputemp;
510     unsigned short cpudec;
511
512     _outp(0xc004, (0x4c<<1)|0x01);
513     _outp(0xc008, 0x01);
514     _outpw(0xc000, _inpw(0xc000));
515     _outp(0xc002, (0) ? 0x0b : 0x0a);
516     while ((_inp(0xc000) & 8));
517     cputemp = _inpw(0xc006);
518
519     _outp(0xc004, (0x4c<<1)|0x01);
520     _outp(0xc008, 0x10);
521     _outpw(0xc000, _inpw(0xc000));
522     _outp(0xc002, (0) ? 0x0b : 0x0a);
523     while ((_inp(0xc000) & 8));
524     cpudec = _inpw(0xc006);
525
526     if (cpudec<10) cpudec = cpudec * 100;
527     if (cpudec<100) cpudec = cpudec *10;
528
529     return PyInt_FromLong((long)(cputemp + cpudec / 1000.0f));
530   }*/
531
532   // getInfolabel() method
533   PyDoc_STRVAR(getInfoLabel__doc__,
534     "getInfoLabel(infotag) -- Returns an InfoLabel as a string.\n"
535     "\n"
536     "infotag        : string - infoTag for value you want returned.\n"
537     "\n"
538     "List of InfoTags - http://wiki.xbmc.org/?title=InfoLabels \n"
539     "\n"
540     "example:\n"
541     "  - label = xbmc.getInfoLabel('Weather.Conditions')\n");
542
543   PyObject* XBMC_GetInfoLabel(PyObject *self, PyObject *args)
544   {
545     char *cLine = NULL;
546     if (!PyArg_ParseTuple(args, (char*)"s", &cLine)) return NULL;
547
548     int ret = g_infoManager.TranslateString(cLine);
549     return Py_BuildValue((char*)"s", g_infoManager.GetLabel(ret).c_str());
550   }
551
552   // getInfoImage() method
553   PyDoc_STRVAR(getInfoImage__doc__,
554     "getInfoImage(infotag) -- Returns a filename including path to the InfoImage's\n"
555     "                         thumbnail as a string.\n"
556     "\n"
557     "infotag        : string - infotag for value you want returned.\n"
558     "\n"
559     "List of InfoTags - http://wiki.xbmc.org/?title=InfoLabels \n"
560     "\n"
561     "example:\n"
562     "  - filename = xbmc.getInfoImage('Weather.Conditions')\n");
563
564   PyObject* XBMC_GetInfoImage(PyObject *self, PyObject *args)
565   {
566     char *cLine = NULL;
567     if (!PyArg_ParseTuple(args, (char*)"s", &cLine)) return NULL;
568
569     int ret = g_infoManager.TranslateString(cLine);
570     return Py_BuildValue((char*)"s", g_infoManager.GetImage(ret, WINDOW_INVALID).c_str());
571   }
572
573   // playSFX() method
574   PyDoc_STRVAR(playSFX__doc__,
575     "playSFX(filename) -- Plays a wav file by filename\n"
576     "\n"
577     "filename       : string - filename of the wav file to play.\n"
578     "\n"
579     "example:\n"
580     "  - xbmc.playSFX('special://xbmc/scripts/dingdong.wav')\n");
581
582   PyObject* XBMC_PlaySFX(PyObject *self, PyObject *args)
583   {
584     const char *cFile = NULL;
585
586     if (!PyArg_ParseTuple(args, (char*)"s", &cFile)) return NULL;
587
588     if (CFile::Exists(cFile))
589     {
590       g_audioManager.PlayPythonSound(cFile);
591     }
592
593     Py_INCREF(Py_None);
594     return Py_None;
595   }
596
597   // enableNavSounds() method
598   PyDoc_STRVAR(enableNavSounds__doc__,
599     "enableNavSounds(yesNo) -- Enables/Disables nav sounds\n"
600     "\n"
601     "yesNo          : integer - enable (True) or disable (False) nav sounds\n"
602     "\n"
603     "example:\n"
604     "  - xbmc.enableNavSounds(True)\n");
605
606   PyObject* XBMC_EnableNavSounds(PyObject *self, PyObject *args)
607   {
608     int yesNo = 1;
609
610     if (!PyArg_ParseTuple(args, (char*)"i", &yesNo)) return NULL;
611
612     g_audioManager.Enable(yesNo==1);
613
614     Py_INCREF(Py_None);
615     return Py_None;
616   }
617
618   // getCondVisibility() method
619   PyDoc_STRVAR(getCondVisibility__doc__,
620     "getCondVisibility(condition) -- Returns True (1) or False (0) as a bool.\n"
621     "\n"
622     "condition      : string - condition to check.\n"
623     "\n"
624     "List of Conditions - http://wiki.xbmc.org/?title=List_of_Boolean_Conditions \n"
625     "\n"
626     "*Note, You can combine two (or more) of the above settings by using \"+\" as an AND operator,\n"
627     "\"|\" as an OR operator, \"!\" as a NOT operator, and \"[\" and \"]\" to bracket expressions.\n"
628     "\n"
629     "example:\n"
630     "  - visible = xbmc.getCondVisibility('[Control.IsVisible(41) + !Control.IsVisible(12)]')\n");
631
632   PyObject* XBMC_GetCondVisibility(PyObject *self, PyObject *args)
633   {
634     char *cLine = NULL;
635     if (!PyArg_ParseTuple(args, (char*)"s", &cLine)) return NULL;
636
637     PyXBMCGUILock();
638     int id = g_windowManager.GetTopMostModalDialogID();
639     if (id == WINDOW_INVALID) id = g_windowManager.GetActiveWindow();
640     PyXBMCGUIUnlock();
641
642     int ret = g_infoManager.TranslateString(cLine);
643     return Py_BuildValue((char*)"b", g_infoManager.GetBool(ret,id));
644   }
645
646   // getGlobalIdleTime() method
647   PyDoc_STRVAR(getGlobalIdleTime__doc__,
648     "getGlobalIdleTime() -- Returns the elapsed idle time in seconds as an integer.\n"
649     "\n"
650     "example:\n"
651     "  - t = xbmc.getGlobalIdleTime()");
652
653   PyObject* XBMC_GetGlobalIdleTime(PyObject *self)
654   {
655     return Py_BuildValue((char*)"i", g_application.GlobalIdleTime());
656   }
657
658   // getCacheThumbName function
659   PyDoc_STRVAR(getCacheThumbName__doc__,
660     "getCacheThumbName(path) -- Returns a thumb cache filename.\n"
661     "\n"
662     "path           : string or unicode - path to file\n"
663     "\n"
664     "example:\n"
665     "  - thumb = xbmc.getCacheThumbName('f:\\\\videos\\\\movie.avi')\n");
666
667   PyObject* XBMC_GetCacheThumbName(PyObject *self, PyObject *args)
668   {
669     PyObject *pObjectText;
670     if (!PyArg_ParseTuple(args, (char*)"O", &pObjectText)) return NULL;
671
672     string strText;
673     if (!PyXBMCGetUnicodeString(strText, pObjectText, 1)) return NULL;
674
675     Crc32 crc;
676     CStdString strPath;
677     crc.ComputeFromLowerCase(strText);
678     strPath.Format("%08x.tbn", (unsigned __int32)crc);
679     return Py_BuildValue((char*)"s", strPath.c_str());
680   }
681
682   // makeLegalFilename function
683   PyDoc_STRVAR(makeLegalFilename__doc__,
684     "makeLegalFilename(filename[, fatX]) -- Returns a legal filename or path as a string.\n"
685     "\n"
686     "filename       : string or unicode - filename/path to make legal\n"
687     "fatX           : [opt] bool - True=Xbox file system(Default)\n"
688     "\n"
689     "*Note, If fatX is true you should pass a full path. If fatX is false only pass\n"
690     "       the basename of the path.\n"
691     "\n"
692     "       You can use the above as keywords for arguments and skip certain optional arguments.\n"
693     "       Once you use a keyword, all following arguments require the keyword.\n"
694     "\n"
695     "example:\n"
696     "  - filename = xbmc.makeLegalFilename('F:\\Trailers\\Ice Age: The Meltdown.avi')\n");
697
698   PyObject* XBMC_MakeLegalFilename(PyObject *self, PyObject *args, PyObject *kwds)
699   {
700     static const char *keywords[] = { "filename", "fatX", NULL };
701     PyObject *pObjectText;
702     char bIsFatX = true;
703     // parse arguments to constructor
704     if (!PyArg_ParseTupleAndKeywords(
705       args,
706       kwds,
707       (char*)"O|b",
708       (char**)keywords,
709       &pObjectText,
710       &bIsFatX
711       ))
712     {
713       return NULL;
714     };
715
716     CStdString strText;
717     if (!PyXBMCGetUnicodeString(strText, pObjectText, 1)) return NULL;
718
719     CStdString strFilename;
720     strFilename = CUtil::MakeLegalPath(strText);
721     return Py_BuildValue((char*)"s", strFilename.c_str());
722   }
723
724   // translatePath function
725   PyDoc_STRVAR(translatePath__doc__,
726     "translatePath(path) -- Returns the translated path.\n"
727     "\n"
728     "path           : string or unicode - Path to format\n"
729     "\n"
730     "*Note, Only useful if you are coding for both Linux and Windows/Xbox.\n"
731     "       e.g. Converts 'special://masterprofile/script_data' -> '/home/user/XBMC/UserData/script_data'\n"
732     "       on Linux. Would return 'special://masterprofile/script_data' on the Xbox.\n"
733     "\n"
734     "example:\n"
735     "  - fpath = xbmc.translatePath('special://masterprofile/script_data')\n");
736
737   PyObject* XBMC_TranslatePath(PyObject *self, PyObject *args)
738   {
739     PyObject *pObjectText;
740     if (!PyArg_ParseTuple(args, (char*)"O", &pObjectText)) return NULL;
741
742     CStdString strText;
743     if (!PyXBMCGetUnicodeString(strText, pObjectText, 1)) return NULL;
744
745     CStdString strPath;
746     if (URIUtils::IsDOSPath(strText))
747       strText = CSpecialProtocol::ReplaceOldPath(strText, 0);
748
749     strPath = CSpecialProtocol::TranslatePath(strText);
750
751     return Py_BuildValue((char*)"s", strPath.c_str());
752   }
753
754   // getcleanmovietitle function
755   PyDoc_STRVAR(getCleanMovieTitle__doc__,
756     "getCleanMovieTitle(path[, usefoldername]) -- Returns a clean movie title and year string if available.\n"
757     "\n"
758     "path           : string or unicode - String to clean\n"
759     "bool           : [opt] bool - use folder names (defaults to false)\n"
760     "\n"
761     "example:\n"
762     "  - title, year = xbmc.getCleanMovieTitle('/path/to/moviefolder/test.avi', True)\n");
763
764   PyObject* XBMC_GetCleanMovieTitle(PyObject *self, PyObject *args, PyObject *kwds)
765   {
766     static const char *keywords[] = { "path", "usefoldername", NULL };
767     PyObject *pObjectText;
768     bool bUseFolderName = false;
769     // parse arguments to constructor
770     if (!PyArg_ParseTupleAndKeywords(
771       args,
772       kwds,
773       (char*)"O|b",
774       (char**)keywords,
775       &pObjectText,
776       &bUseFolderName
777       ))
778     {
779       return NULL;
780     };
781
782     CStdString strPath;
783     if (!PyXBMCGetUnicodeString(strPath, pObjectText, 1)) return NULL;
784
785     CFileItem item(strPath, false);
786     CStdString strName = item.GetMovieName(bUseFolderName);
787
788     CStdString strTitle, strTitleAndYear, strYear;
789     CUtil::CleanString(strName, strTitle, strTitleAndYear, strYear, bUseFolderName);
790
791     return Py_BuildValue((char*)"s,s", strTitle.c_str(), strYear.c_str());
792   }
793
794   // validatePath function
795   PyDoc_STRVAR(validatePath__doc__,
796     "validatePath(path) -- Returns the validated path.\n"
797     "\n"
798     "path           : string or unicode - Path to format\n"
799     "\n"
800     "*Note, Only useful if you are coding for both Linux and Windows/Xbox for fixing slash problems.\n"
801     "       e.g. Corrects 'Z://something' -> 'Z:\\something'\n"
802     "\n"
803     "example:\n"
804     "  - fpath = xbmc.validatePath(somepath)\n");
805
806   PyObject* XBMC_ValidatePath(PyObject *self, PyObject *args)
807   {
808     PyObject *pObjectText;
809     if (!PyArg_ParseTuple(args, (char*)"O", &pObjectText)) return NULL;
810
811     CStdString strText;
812     if (!PyXBMCGetUnicodeString(strText, pObjectText, 1)) return NULL;
813
814     return Py_BuildValue((char*)"s", CUtil::ValidatePath(strText, true).c_str());
815   }
816
817   // getRegion function
818   PyDoc_STRVAR(getRegion__doc__,
819     "getRegion(id) -- Returns your regions setting as a string for the specified id.\n"
820     "\n"
821     "id             : string - id of setting to return\n"
822     "\n"
823     "*Note, choices are (dateshort, datelong, time, meridiem, tempunit, speedunit)\n"
824     "\n"
825     "       You can use the above as keywords for arguments.\n"
826     "\n"
827     "example:\n"
828     "  - date_long_format = xbmc.getRegion('datelong')\n");
829
830   PyObject* XBMC_GetRegion(PyObject *self, PyObject *args, PyObject *kwds)
831   {
832     static const char *keywords[] = { "id", NULL };
833     char *id = NULL;
834     // parse arguments to constructor
835     if (!PyArg_ParseTupleAndKeywords(
836       args,
837       kwds,
838       (char*)"s",
839       (char**)keywords,
840       &id
841       ))
842     {
843       return NULL;
844     };
845
846     CStdString result;
847
848     if (strcmpi(id, "datelong") == 0)
849     {
850       result = g_langInfo.GetDateFormat(true);
851       result.Replace("DDDD", "%A");
852       result.Replace("MMMM", "%B");
853       result.Replace("D", "%d");
854       result.Replace("YYYY", "%Y");
855     }
856     else if (strcmpi(id, "dateshort") == 0)
857     {
858       result = g_langInfo.GetDateFormat(false);
859       result.Replace("MM", "%m");
860       result.Replace("DD", "%d");
861       result.Replace("YYYY", "%Y");
862     }
863     else if (strcmpi(id, "tempunit") == 0)
864       result = g_langInfo.GetTempUnitString();
865     else if (strcmpi(id, "speedunit") == 0)
866       result = g_langInfo.GetSpeedUnitString();
867     else if (strcmpi(id, "time") == 0)
868     {
869       result = g_langInfo.GetTimeFormat();
870       result.Replace("H", "%H");
871       result.Replace("h", "%I");
872       result.Replace("mm", "%M");
873       result.Replace("ss", "%S");
874       result.Replace("xx", "%p");
875     }
876     else if (strcmpi(id, "meridiem") == 0)
877       result.Format("%s/%s", g_langInfo.GetMeridiemSymbol(CLangInfo::MERIDIEM_SYMBOL_AM), g_langInfo.GetMeridiemSymbol(CLangInfo::MERIDIEM_SYMBOL_PM));
878
879     return Py_BuildValue((char*)"s", result.c_str());
880   }
881
882   // getSupportedMedia function
883   PyDoc_STRVAR(getSupportedMedia__doc__,
884     "getSupportedMedia(media) -- Returns the supported file types for the specific media as a string.\n"
885     "\n"
886     "media          : string - media type\n"
887     "\n"
888     "*Note, media type can be (video, music, picture).\n"
889     "\n"
890     "       The return value is a pipe separated string of filetypes (eg. '.mov|.avi').\n"
891     "\n"
892     "       You can use the above as keywords for arguments.\n"
893     "\n"
894     "example:\n"
895     "  - mTypes = xbmc.getSupportedMedia('video')\n");
896
897   PyObject* XBMC_GetSupportedMedia(PyObject *self, PyObject *args, PyObject *kwds)
898   {
899     static const char *keywords[] = { "media", NULL };
900     char *media = NULL;
901     // parse arguments to constructor
902     if (!PyArg_ParseTupleAndKeywords(
903       args,
904       kwds,
905       (char*)"s",
906       (char**)keywords,
907       &media
908       ))
909     {
910       return NULL;
911     };
912
913     CStdString result;
914     if (strcmpi(media, "video") == 0)
915       result = g_settings.m_videoExtensions;
916     else if (strcmpi(media, "music") == 0)
917       result = g_settings.m_musicExtensions;
918     else if (strcmpi(media, "picture") == 0)
919       result = g_settings.m_pictureExtensions;
920     else
921     {
922       PyErr_SetString(PyExc_ValueError, "media = (video, music, picture)");
923       return NULL;
924     }
925
926     return Py_BuildValue((char*)"s", result.c_str());
927   }
928
929   // skinHasImage function
930   PyDoc_STRVAR(skinHasImage__doc__,
931     "skinHasImage(image) -- Returns True if the image file exists in the skin.\n"
932     "\n"
933     "image          : string - image filename\n"
934     "\n"
935     "*Note, If the media resides in a subfolder include it. (eg. home-myfiles\\\\home-myfiles2.png)\n"
936     "\n"
937     "       You can use the above as keywords for arguments.\n"
938     "\n"
939     "example:\n"
940     "  - exists = xbmc.skinHasImage('ButtonFocusedTexture.png')\n");
941
942   PyObject* XBMC_SkinHasImage(PyObject *self, PyObject *args, PyObject *kwds)
943   {
944     static const char *keywords[] = { "image", NULL };
945     char *image = NULL;
946     // parse arguments to constructor
947     if (!PyArg_ParseTupleAndKeywords(
948       args,
949       kwds,
950       (char*)"s",
951       (char**)keywords,
952       &image
953       ))
954     {
955       return NULL;
956     };
957
958     bool exists = g_TextureManager.HasTexture(image);
959
960     return Py_BuildValue((char*)"b", exists);
961   }
962   
963   PyDoc_STRVAR(subHashAndFileSize__doc__,
964     "subHashAndFileSize(file)\n"
965     "\n"
966     "file        : file to calculate subtitle hash and size for"
967     "\n"
968     "example:\n"
969     " size,hash = xbmcvfs.subHashAndFileSize(file)\n"); 
970   PyObject* XBMC_subHashAndFileSize(PyObject *self, PyObject *args, PyObject *kwds)
971   {
972     PyObject *f_line;
973     if (!PyArg_ParseTuple(
974       args,
975       (char*)"O",
976       &f_line))
977     {
978       return NULL;
979     }
980     CStdString strSource;
981     if (!PyXBMCGetUnicodeString(strSource, f_line, 1)) return NULL;
982     
983     CStdString strSize;
984     CStdString strHash;
985
986     CPyThreadState pyState;
987     CFileUtils::SubtitleFileSizeAndHash(strSource, strSize, strHash);
988     pyState.Restore();
989     
990     return Py_BuildValue((char*)"ss",strSize.c_str(), strHash.c_str());
991   } 
992
993   // define c functions to be used in python here
994   PyMethodDef xbmcMethods[] = {
995     {(char*)"output", (PyCFunction)XBMC_Output, METH_VARARGS|METH_KEYWORDS, output__doc__},
996     {(char*)"log", (PyCFunction)XBMC_Log, METH_VARARGS|METH_KEYWORDS, log__doc__},
997     {(char*)"executescript", (PyCFunction)XBMC_ExecuteScript, METH_VARARGS, executeScript__doc__},
998     {(char*)"executebuiltin", (PyCFunction)XBMC_ExecuteBuiltIn, METH_VARARGS, executeBuiltIn__doc__},
999
1000     {(char*)"sleep", (PyCFunction)XBMC_Sleep, METH_VARARGS, sleep__doc__},
1001     {(char*)"shutdown", (PyCFunction)XBMC_Shutdown, METH_VARARGS, shutdown__doc__},
1002     {(char*)"dashboard", (PyCFunction)XBMC_Dashboard, METH_VARARGS, dashboard__doc__},
1003     {(char*)"restart", (PyCFunction)XBMC_Restart, METH_VARARGS, restart__doc__},
1004     {(char*)"getSkinDir", (PyCFunction)XBMC_GetSkinDir, METH_VARARGS, getSkinDir__doc__},
1005     {(char*)"getLocalizedString", (PyCFunction)XBMC_GetLocalizedString, METH_VARARGS, getLocalizedString__doc__},
1006
1007     {(char*)"getLanguage", (PyCFunction)XBMC_GetLanguage, METH_VARARGS, getLanguage__doc__},
1008     {(char*)"getIPAddress", (PyCFunction)XBMC_GetIPAddress, METH_VARARGS, getIPAddress__doc__},
1009     {(char*)"getDVDState", (PyCFunction)XBMC_GetDVDState, METH_VARARGS, getDVDState__doc__},
1010     {(char*)"getFreeMem", (PyCFunction)XBMC_GetFreeMem, METH_VARARGS, getFreeMem__doc__},
1011     //{(char*)"getCpuTemp", (PyCFunction)XBMC_GetCpuTemp, METH_VARARGS, getCpuTemp__doc__},
1012
1013 #ifdef HAS_HTTPAPI
1014     {(char*)"executehttpapi", (PyCFunction)XBMC_ExecuteHttpApi, METH_VARARGS, executeHttpApi__doc__},
1015 #endif
1016 #ifdef HAS_JSONRPC
1017     {(char*)"executeJSONRPC", (PyCFunction)XBMC_ExecuteJSONRPC, METH_VARARGS, executeJSONRPC__doc__},
1018 #endif
1019     {(char*)"getInfoLabel", (PyCFunction)XBMC_GetInfoLabel, METH_VARARGS, getInfoLabel__doc__},
1020     {(char*)"getInfoImage", (PyCFunction)XBMC_GetInfoImage, METH_VARARGS, getInfoImage__doc__},
1021     {(char*)"getCondVisibility", (PyCFunction)XBMC_GetCondVisibility, METH_VARARGS, getCondVisibility__doc__},
1022     {(char*)"getGlobalIdleTime", (PyCFunction)XBMC_GetGlobalIdleTime, METH_VARARGS, getGlobalIdleTime__doc__},
1023
1024     {(char*)"playSFX", (PyCFunction)XBMC_PlaySFX, METH_VARARGS, playSFX__doc__},
1025     {(char*)"enableNavSounds", (PyCFunction)XBMC_EnableNavSounds, METH_VARARGS, enableNavSounds__doc__},
1026
1027     {(char*)"getCacheThumbName", (PyCFunction)XBMC_GetCacheThumbName, METH_VARARGS, getCacheThumbName__doc__},
1028
1029     {(char*)"makeLegalFilename", (PyCFunction)XBMC_MakeLegalFilename, METH_VARARGS|METH_KEYWORDS, makeLegalFilename__doc__},
1030     {(char*)"translatePath", (PyCFunction)XBMC_TranslatePath, METH_VARARGS, translatePath__doc__},
1031     {(char*)"validatePath", (PyCFunction)XBMC_ValidatePath, METH_VARARGS, validatePath__doc__},
1032
1033     {(char*)"getRegion", (PyCFunction)XBMC_GetRegion, METH_VARARGS|METH_KEYWORDS, getRegion__doc__},
1034     {(char*)"getSupportedMedia", (PyCFunction)XBMC_GetSupportedMedia, METH_VARARGS|METH_KEYWORDS, getSupportedMedia__doc__},
1035
1036     {(char*)"getCleanMovieTitle", (PyCFunction)XBMC_GetCleanMovieTitle, METH_VARARGS|METH_KEYWORDS, getCleanMovieTitle__doc__},
1037
1038     {(char*)"skinHasImage", (PyCFunction)XBMC_SkinHasImage, METH_VARARGS|METH_KEYWORDS, skinHasImage__doc__},
1039     {(char*)"subHashAndFileSize", (PyCFunction)XBMC_subHashAndFileSize, METH_VARARGS, subHashAndFileSize__doc__},
1040
1041     {NULL, NULL, 0, NULL}
1042   };
1043
1044 /*****************************************************************
1045  * end of methods and python objects
1046  * initxbmc(void);
1047  *****************************************************************/
1048   PyMODINIT_FUNC
1049   InitXBMCTypes(bool bInitTypes)
1050   {
1051     initKeyboard_Type();
1052     initPlayer_Type();
1053     initPlayList_Type();
1054     initPlayListItem_Type();
1055     initInfoTagMusic_Type();
1056     initInfoTagVideo_Type();
1057
1058     if (PyType_Ready(&Keyboard_Type) < 0 ||
1059         PyType_Ready(&Player_Type) < 0 ||
1060         PyType_Ready(&PlayList_Type) < 0 ||
1061         PyType_Ready(&PlayListItem_Type) < 0 ||
1062         PyType_Ready(&InfoTagMusic_Type) < 0 ||
1063         PyType_Ready(&InfoTagVideo_Type) < 0) return;
1064   }
1065
1066   PyMODINIT_FUNC
1067   DeinitXBMCModule()
1068   {
1069     // no need to Py_DECREF our objects (see InitXBMCModule()) as they were created only
1070     // so that they could be added to the module, which steals a reference.
1071   }
1072
1073   PyMODINIT_FUNC
1074   InitXBMCModule()
1075   {
1076     // init general xbmc modules
1077     PyObject* pXbmcModule;
1078
1079     Py_INCREF(&Keyboard_Type);
1080     Py_INCREF(&Player_Type);
1081     Py_INCREF(&PlayList_Type);
1082     Py_INCREF(&PlayListItem_Type);
1083     Py_INCREF(&InfoTagMusic_Type);
1084     Py_INCREF(&InfoTagVideo_Type);
1085
1086     pXbmcModule = Py_InitModule((char*)"xbmc", xbmcMethods);
1087     if (pXbmcModule == NULL) return;
1088
1089     PyModule_AddObject(pXbmcModule, (char*)"Keyboard", (PyObject*)&Keyboard_Type);
1090     PyModule_AddObject(pXbmcModule, (char*)"Player", (PyObject*)&Player_Type);
1091     PyModule_AddObject(pXbmcModule, (char*)"PlayList", (PyObject*)&PlayList_Type);
1092     PyModule_AddObject(pXbmcModule, (char*)"PlayListItem", (PyObject*)&PlayListItem_Type);
1093     PyModule_AddObject(pXbmcModule, (char*)"InfoTagMusic", (PyObject*)&InfoTagMusic_Type);
1094     PyModule_AddObject(pXbmcModule, (char*)"InfoTagVideo", (PyObject*)&InfoTagVideo_Type);
1095
1096     // constants
1097     PyModule_AddStringConstant(pXbmcModule, (char*)"__author__", (char*)PY_XBMC_AUTHOR);
1098     PyModule_AddStringConstant(pXbmcModule, (char*)"__date__", (char*)"15 November 2005");
1099     PyModule_AddStringConstant(pXbmcModule, (char*)"__version__", (char*)"1.3");
1100     PyModule_AddStringConstant(pXbmcModule, (char*)"__credits__", (char*)PY_XBMC_CREDITS);
1101     PyModule_AddStringConstant(pXbmcModule, (char*)"__platform__", (char*)PY_XBMC_PLATFORM);
1102
1103     // playlist constants
1104     PyModule_AddIntConstant(pXbmcModule, (char*)"PLAYLIST_MUSIC", PLAYLIST_MUSIC);
1105     //PyModule_AddIntConstant(pXbmcModule, (char*)"PLAYLIST_MUSIC_TEMP", (char*)PLAYLIST_MUSIC_TEMP);
1106     PyModule_AddIntConstant(pXbmcModule, (char*)"PLAYLIST_VIDEO", PLAYLIST_VIDEO);
1107     //PyModule_AddIntConstant(pXbmcModule, (char*)"PLAYLIST_VIDEO_TEMP", PLAYLIST_VIDEO_TEMP);
1108
1109     // player constants
1110     PyModule_AddIntConstant(pXbmcModule, (char*)"PLAYER_CORE_AUTO", EPC_NONE);
1111     PyModule_AddIntConstant(pXbmcModule, (char*)"PLAYER_CORE_DVDPLAYER", EPC_DVDPLAYER);
1112     PyModule_AddIntConstant(pXbmcModule, (char*)"PLAYER_CORE_MPLAYER", EPC_MPLAYER);
1113     PyModule_AddIntConstant(pXbmcModule, (char*)"PLAYER_CORE_PAPLAYER", EPC_PAPLAYER);
1114
1115     // dvd state constants
1116     PyModule_AddIntConstant(pXbmcModule, (char*)"TRAY_OPEN", TRAY_OPEN);
1117     PyModule_AddIntConstant(pXbmcModule, (char*)"DRIVE_NOT_READY", DRIVE_NOT_READY);
1118     PyModule_AddIntConstant(pXbmcModule, (char*)"TRAY_CLOSED_NO_MEDIA", TRAY_CLOSED_NO_MEDIA);
1119     PyModule_AddIntConstant(pXbmcModule, (char*)"TRAY_CLOSED_MEDIA_PRESENT", TRAY_CLOSED_MEDIA_PRESENT);
1120
1121     // log levels
1122     PyModule_AddIntConstant(pXbmcModule, (char*)"LOGDEBUG", LOGDEBUG);
1123     PyModule_AddIntConstant(pXbmcModule, (char*)"LOGINFO", LOGINFO);
1124     PyModule_AddIntConstant(pXbmcModule, (char*)"LOGNOTICE", LOGNOTICE);
1125     PyModule_AddIntConstant(pXbmcModule, (char*)"LOGWARNING", LOGWARNING);
1126     PyModule_AddIntConstant(pXbmcModule, (char*)"LOGERROR", LOGERROR);
1127     PyModule_AddIntConstant(pXbmcModule, (char*)"LOGSEVERE", LOGSEVERE);
1128     PyModule_AddIntConstant(pXbmcModule, (char*)"LOGFATAL", LOGFATAL);
1129     PyModule_AddIntConstant(pXbmcModule, (char*)"LOGNONE", LOGNONE);
1130     PyModule_AddObject(pXbmcModule, (char*)"abortRequested", PyBool_FromLong(0));
1131   }
1132 }
1133
1134 #ifdef __cplusplus
1135 }
1136 #endif