GsPython.cpp 9.78 KB
Newer Older
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
// Only bother if python3 is enabled
#if USE_PYTHON3

#include "GsPython.h"
#include "utils/FindFile.h"

#include "GsLogging.h"


void fixNewLine(std::string& str)
{
    // Check for empty string.
    if(str.size() <= 2)
    {
       str.clear();
       return;
    }

    // This removes the extra \"s we get through the Python interface
    str = str.substr(1,str.size()-2);

    for(size_t i=0 ; i<str.size()-1 ; i++)
    {
        if(str[i] == '\\' && str[i+1] == 'n')
        {
            str[i] = ' ';
            str[i+1] = '\n';
        }
    }
}


void replaceSlashes(std::string &text)
{
#ifdef WIN32
    for (std::string::iterator it = text.begin(); it != text.end(); it++)
    {
        if (*it == '/') *it = '\\';
    }
#endif
}


// Windows only. In order to get python work correctly you might need to have doubled amount of backslashes
void duplicateBackslashes(std::string &text)
{
#ifdef WIN32
    auto npos = text.find("\\");
    if(npos != std::string::npos)
    {
        auto subStr = text.substr(npos+1);
        duplicateBackslashes(subStr);
        text = text.substr(0, npos) + "\\\\" + subStr;
    }
#endif
}

bool
GsPythonModule::
load(const std::string &modName,
     const std::string &dirPath)
{
    mpModule = gPython.loadModule( modName, dirPath );

    return (mpModule != nullptr) ? true : false;
}


bool
GsPythonFunc::
load(GsPythonModule &module,
     const std::string &funcName)
{
    auto pModPtr = module.rawPtr();

    assert(pModPtr);

    mpFunction = PyObject_GetAttrString(pModPtr,
                                        funcName.c_str());

    if (mpFunction && PyCallable_Check(mpFunction))
    {
        return true;
    }
    else
    {
        if (PyErr_Occurred())
        {
            PyErr_Print();
        }

        gLogging.ftextOut("Cannot find function \"%s\"\n", funcName.c_str());
        return false;
    }
}


void
GsPythonFunc::call()
{
    /*PyObject *pValue = */PyObject_CallObject(mpFunction, nullptr);

    /*if (pValue != nullptr)
    {
        if( PyObject_IsTrue(pValue) )
        {
            value = true;
        }
        else
        {
            value = false;
        }
        Py_DECREF(pValue);
    }
    else
    {
        Py_DECREF(pFunc);
        PyErr_Print();
        gLogging.ftextOut("Call failed\n");
        return false;
    }*/
}


PyObject *GsPython::loadModule(const std::string &scriptBaseName,
                               const std::string &baseDir)
{
    // Extra Python script for this AI defined?
    std::string aiscriptPath = baseDir;
    aiscriptPath = JoinPaths(aiscriptPath,scriptBaseName);
    aiscriptPath += ".py";
    aiscriptPath = GetFullFileName(aiscriptPath);

    if( !IsFileAvailable(aiscriptPath) )
    {
        return nullptr;
    }

    // Ensure the path is correctly formatted even for Windows
    std::string aidir = ExtractDirectory(aiscriptPath);

    replaceSlashes(aidir);
    duplicateBackslashes(aidir);

    gLogging.ftextOut("calling Py_Initialize().\n", aiscriptPath.c_str() );


#ifdef ANDROID
    // Because Android does not provide any search for the python assets we have to set them here!
    std::string searchPath;
    GetExactFileName(GetFirstSearchPath(), searchPath);
    const std::string pythonHome = JoinPaths(searchPath,"python3.5");
    setenv("PYTHONHOME", pythonHome.c_str(), 1);
    setenv("PYTHONPATH", pythonHome.c_str(), 1);
#endif


    Py_Initialize();


    PyObject* programName = PyUnicode_FromString(scriptBaseName.c_str());

    PyRun_SimpleString("import sys");   

    const std::string sysPathCommand = "sys.path.append(\"" + aidir + "\")";

    PyRun_SimpleString(sysPathCommand.c_str());

    gLogging.ftextOut("Loading \"%s\" python script file.\n", aiscriptPath.c_str() );

    auto pModule = PyImport_Import(programName);
    Py_DECREF(programName);

    if(!pModule)
    {
        PyErr_Print();
        gLogging.ftextOut("Failed to load \"%s\"\n", aiscriptPath.c_str() );
    }

    return pModule;
}



bool loadStrFunction(PyObject * pModule,
                     const std::string &pyMethodStr,
                     std::string &value,
                     const int param1)
{
    // pFunc is a new reference
    PyObject *pFunc = PyObject_GetAttrString(pModule, pyMethodStr.c_str());

    PyObject *pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, PyLong_FromLong(param1));

    if (pFunc && PyCallable_Check(pFunc))
    {
        PyObject *pValue = PyObject_CallObject(pFunc, pArgs);

        if (pValue != nullptr)
        {
            PyObject *objectsRepresentation = PyObject_Repr(pValue);

204
            auto *str = PyUnicode_AsUTF8(objectsRepresentation) ;
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

            if(str)
            {
                std::string message = str;

                // Because line breaks are not formatted correctly
                fixNewLine(message);

                if(!message.empty())
                {
                    value = message;
                }
            }

            Py_DECREF(pValue);
            Py_DECREF(objectsRepresentation);
        }
        else
        {
            Py_DECREF(pFunc);
            PyErr_Print();
            gLogging.ftextOut("Call failed\n");
            return false;
        }
    }
    else
    {
        if (PyErr_Occurred())
        {
            PyErr_Print();
        }

        gLogging.ftextOut("Cannot find function \"%s\"\n", pyMethodStr.c_str());
        return false;
    }

    Py_XDECREF(pArgs);
    Py_XDECREF(pFunc);


    return true;
}


bool loadStrFunction(PyObject * pModule,
                     const std::string &pyMethodStr,
                     std::string &value)
{
    // pFunc is a new reference
    PyObject *pFunc = PyObject_GetAttrString(pModule, pyMethodStr.c_str());

    // TODO: ... Coding ...
    //PyObject *pArgs = PyTuple_New(1);
    //PyTuple_SetItem(pArgs, 0, PyLong_FromLong(param1));

    if (pFunc && PyCallable_Check(pFunc))
    {
        PyObject *pValue = PyObject_CallObject(pFunc, nullptr);

        if (pValue != nullptr)
        {
            PyObject *objectsRepresentation = PyObject_Repr(pValue);

268
            auto *str = PyUnicode_AsUTF8(objectsRepresentation) ;
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 444 445 446 447 448 449 450 451 452 453 454 455 456 457

            if(str)
            {
                std::string message = str;

                // Because line breaks are not formatted correctly
                fixNewLine(message);

                if(!message.empty())
                {
                    value = message;
                }
            }

            Py_DECREF(pValue);
            Py_DECREF(objectsRepresentation);
        }
        else
        {
            Py_DECREF(pFunc);
            PyErr_Print();
            gLogging.ftextOut("Call failed\n");
            return false;
        }
    }
    else
    {
        if (PyErr_Occurred())
        {
            PyErr_Print();
        }

        gLogging.ftextOut("Cannot find function \"%s\"\n", pyMethodStr.c_str());
        return false;
    }

    Py_XDECREF(pFunc);


    return true;
}




bool loadIntegerFunc(PyObject * pModule, const std::string &pyMethodStr, int &value)
{
    // pFunc is a new reference
    PyObject *pFunc = PyObject_GetAttrString(pModule, pyMethodStr.c_str());

    if (pFunc && PyCallable_Check(pFunc))
    {
        PyObject *pValue = PyObject_CallObject(pFunc, nullptr);

        if (pValue != nullptr)
        {
            value = PyLong_AsLong(pValue);
            Py_DECREF(pValue);
        }
        else
        {
            Py_DECREF(pFunc);
            PyErr_Print();
            gLogging.ftextOut("Call failed\n");
            return false;
        }
    }
    else
    {
        if (PyErr_Occurred())
        {
            PyErr_Print();
        }

        gLogging.ftextOut("Cannot find function \"init\"\n");
        return false;
    }

    Py_XDECREF(pFunc);


    return true;
}


bool loadBooleanFunc(PyObject * pModule,
                     const std::string &pyMethodStr,
                     bool &value)
{
    // pFunc is a new reference
    PyObject *pFunc = PyObject_GetAttrString(pModule, pyMethodStr.c_str());

    if (pFunc && PyCallable_Check(pFunc))
    {
        PyObject *pValue = PyObject_CallObject(pFunc, nullptr);

        if (pValue != nullptr)
        {
            auto isBool = PyBool_Check(pValue);

            if(isBool)
            {
                if(pValue == Py_False)
                {
                    value = false;
                }
                else if(pValue == Py_True)
                {
                    value = true;
                }
            }

            Py_DECREF(pValue);
        }
        else
        {
            Py_DECREF(pFunc);
            PyErr_Print();
            gLogging.ftextOut("Call failed\n");
            return false;
        }
    }
    else
    {
        if (PyErr_Occurred())
        {
            PyErr_Print();
        }

        gLogging.ftextOut("Cannot find function \"init\"\n");
        return false;
    }

    Py_XDECREF(pFunc);


    return true;
}



bool loadIntegerFunc(PyObject * pModule,
                     const std::string &pyMethodStr,
                     int &value,
                     const int param1)
{
    // pFunc is a new reference
    PyObject *pFunc = PyObject_GetAttrString(pModule, pyMethodStr.c_str());

    PyObject *pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, PyLong_FromLong(param1));

    if (pFunc && PyCallable_Check(pFunc))
    {
        PyObject *pValue = PyObject_CallObject(pFunc, pArgs);

        if (pValue != nullptr)
        {
            value = PyLong_AsLong(pValue);
            Py_DECREF(pValue);
        }
        else
        {
            Py_DECREF(pFunc);
            PyErr_Print();
            gLogging.ftextOut("Call failed\n");
            return false;
        }
    }
    else
    {
        if (PyErr_Occurred())
        {
            PyErr_Print();
        }

        gLogging.ftextOut("Cannot find function \"%s\"\n", pyMethodStr.c_str());
        return false;
    }

    Py_XDECREF(pArgs);
    Py_XDECREF(pFunc);


    return true;
}


#endif