void QgsPythonUtilsImpl::initPython( QgisInterface* interface ) { // initialize python Py_Initialize(); mPythonEnabled = true; mMainModule = PyImport_AddModule( "__main__" ); // borrowed reference mMainDict = PyModule_GetDict( mMainModule ); // borrowed reference runString( "import sys" ); // import sys module (for display / exception hooks) runString( "import os" ); // import os module (for user paths) #ifdef Q_OS_WIN runString( "oldhome=None" ); runString( "if os.environ.has_key('HOME'): oldhome=os.environ['HOME']\n" ); runString( "os.environ['HOME']=os.environ['USERPROFILE']\n" ); #endif // construct a list of plugin paths // plugin dirs passed in QGIS_PLUGINPATH env. variable have highest priority (usually empty) // locally installed plugins have priority over the system plugins // use os.path.expanduser to support usernames with special characters (see #2512) QStringList pluginpaths; foreach ( QString p, extraPluginsPaths() ) { #ifdef Q_OS_WIN p = p.replace( '\\', "\\\\" ); #endif pluginpaths << '"' + p + '"'; }
void QgsPythonUtilsImpl::installConsoleHooks() { runString( "sys.displayhook = console_display_hook\n" ); runString( "_old_stdout = sys.stdout\n" ); runString( "sys.stdout = QgisOutputCatcher()\n" ); }
bool QgsPythonUtilsImpl::loadPlugin( QString packageName ) { // load plugin's package and ensure that plugin is reloaded when changed runString( "try:\n" " import " + packageName + "\n" " __main__.__plugin_result = 'OK'\n" "except:\n" " __main__.__plugin_result = 'ERROR'\n" ); if ( getVariableFromMain( "__plugin_result" ) == "OK" ) return true; // snake in the grass, we know it's there runString( "sys.path_importer_cache.clear()" ); // retry runString( "try:\n" " import " + packageName + "\n" " reload(" + packageName + ")\n" " __main__.__plugin_result = 'OK'\n" "except:\n" " qgis_except_hook_msg(sys.exc_type, sys.exc_value, sys.exc_traceback, " "'Couldn\\'t load plugin \"" + packageName + "\" from [\\'' + '\\', \\''.join(sys.path) + '\\']')\n" " __main__.__plugin_result = 'ERROR'\n" ); return getVariableFromMain( "__plugin_result" ) == "OK"; }
void doExpandAbbreviation() { CHECK_INITIALISED(); if (g_expandIsTab) { runString(_T("npp_zen_coding.expand_abbreviation(True)")); } else { runString(_T("npp_zen_coding.expand_abbreviation(False)")); } }
bool QgsPythonUtilsImpl::unloadPlugin( QString packageName ) { // unload and delete plugin! QString varName = "plugins['" + packageName + "']"; QString errMsg = QObject::tr( "Error while unloading plugin " ) + packageName; if ( !runString( varName + ".unload()", errMsg ) ) return false; if ( !runString( "del " + varName, errMsg ) ) return false; return true; }
bool Script::load(std::vector<std::string> const& files) { std::vector<char> data; // Load all the files for (std::vector<std::string>::const_iterator it = files.begin(); it != files.end(); ++it) { std::string filename = *it; // Read file std::ifstream inf(filename.c_str(), std::ios::binary); if (inf.good()) { // Read file char ch; while (inf.get(ch)) data.push_back(ch); } else std::cerr << "Could not read file '" << filename << "'" << std::endl; // Insert a newline between each file data.push_back('\n'); inf.close(); } data.push_back('\0'); return runString(std::string(&data[0]), ""); }
QStringList QgsPythonUtilsImpl::pluginList() { runString( "qgis.utils.updateAvailablePlugins()" ); QString output; evalString( "'\\n'.join(qgis.utils.available_plugins)", output ); return output.split( QChar( '\n' ), QString::SkipEmptyParts ); }
bool QgsPythonUtilsImpl::startPlugin( QString packageName ) { QString pluginPythonVar = "plugins['" + packageName + "']"; QString errMsg = QObject::tr( "Couldn't load plugin " ) + packageName; // create an instance of the plugin if ( !runString( pluginPythonVar + " = " + packageName + ".classFactory(iface)", errMsg + QObject::tr( " due an error when calling its classFactory() method" ) ) ) return false; // initGui if ( !runString( pluginPythonVar + ".initGui()", errMsg + QObject::tr( " due an error when calling its initGui() method" ) ) ) return false; return true; }
bool QgsPythonUtilsImpl::checkQgisUser() { // import QGIS user QString error_msg = QObject::tr( "Couldn't load qgis.user." ) + '\n' + QObject::tr( "Python support will be disabled." ); if ( !runString( "import qgis.user", error_msg ) ) { // Should we really bail because of this?! return false; } return true; }
void QgsPythonUtilsImpl::initPython( QgisInterface* interface ) { // initialize python Py_Initialize(); mPythonEnabled = true; mMainModule = PyImport_AddModule( "__main__" ); // borrowed reference mMainDict = PyModule_GetDict( mMainModule ); // borrowed reference runString( "import sys" ); // import sys module (for display / exception hooks) runString( "import os" ); // import os module (for user paths) #ifdef Q_OS_WIN runString( "oldhome=None" ); runString( "if os.environ.has_key('HOME'): oldhome=os.environ['HOME']\n" ); runString( "os.environ['HOME']=os.environ['USERPROFILE']\n" ); #endif // construct a list of plugin paths // plugin dirs passed in QGIS_PLUGINPATH env. variable have highest priority (usually empty) // locally installed plugins have priority over the system plugins // use os.path.expanduser to support usernames with special characters (see #2512) QStringList pluginpaths; foreach ( QString p, extraPluginsPaths() ) { #ifdef Q_OS_WIN p = p.replace( '\\', "\\\\" ); #endif if ( !QDir( p ).exists() ) { QgsMessageOutput* msg = QgsMessageOutput::createMessageOutput(); msg->setTitle( QObject::tr( "Python error" ) ); msg->setMessage( QString( QObject::tr( "The extra plugin path '%1' does not exist !" ) ).arg( p ), QgsMessageOutput::MessageText ); msg->showMessage(); } // we store here paths in unicode strings // the str constant will contain utf8 code (through runString) // so we call '...'.decode('utf-8') to make a unicode string pluginpaths << '"' + p + "\".decode('utf-8')"; }
bool LuaSimpleContext::runFile( const mkString& filename ) { uint8* text = NULL; uint32 size = 0; if (!loadFile(filename.c_str(), &text, &size, true)) { log_error("Could not read Lua script file '%s'", filename.c_str()); return false; } return runString((const char*)text); }
void QgsPythonUtilsImpl::initServerPython( QgsServerInterface* interface ) { init(); if ( !checkSystemImports() ) { exitPython(); return; } // This is the main difference with initInterface() for desktop plugins // import QGIS Server bindings QString error_msg = QObject::tr( "Couldn't load PyQGIS Server." ) + '\n' + QObject::tr( "Python support will be disabled." ); if ( !runString( "from qgis.server import *", error_msg ) ) { return; } // This is the other main difference with initInterface() for desktop plugins runString( "qgis.utils.initServerInterface(" + QString::number(( unsigned long ) interface ) + ')' ); finish(); }
void initialise() { TCHAR configPath[MAX_PATH]; ::SendMessage(nppData._nppHandle, NPPM_GETPLUGINSCONFIGDIR, MAX_PATH, reinterpret_cast<LPARAM>(configPath)); tstring my_zen_settings(configPath); my_zen_settings.append(_T("\\ZenCodingPython\\zencoding\\my_zen_settings.py")); if (!::PathFileExists(my_zen_settings.c_str())) { std::ofstream mySettingsFile(my_zen_settings.c_str()); mySettingsFile << "my_zen_settings = {\n" " 'html': {\n" " 'abbreviations': {\n" " 'jq': '<script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js\"></script>',\n" " 'demo': '<div id =\"demo\"></div>'\n" " }\n" " }\n" "}\n"; mySettingsFile.close(); } tstring zen_module(_T("sys.path.append(r'")); zen_module.append(configPath); zen_module.append(_T("\\ZenCodingPython')\nimport npp_zen_coding\n")); runString(zen_module.c_str()); g_initialised = true; // Set the current profile if it's not xhtml (the default) if (g_fiProfileHtml == g_currentProfileIndex) { setProfile(_T("html"), g_fiProfileHtml); } else if (g_fiProfileXml == g_currentProfileIndex) { setProfile(_T("xml"), g_fiProfileXml); } else if (g_fiProfilePlain == g_currentProfileIndex) { setProfile(_T("plain"), g_fiProfilePlain); } }
void apply_colors_apps(Fl_Color fg, Fl_Color bg, Fl_Color text, Fl_String font) { uchar r, g, b, r1, g1, b1, r2, g2, b2; fl_get_color(bg, r, g, b); fl_get_color(fg, r1, g1, b1); fl_get_color(text, r2, g2, b2); Fl_String filePath(fl_homedir()); filePath += "/.Xdefaults"; char *backgroundTypes[34] = { "*XmList.background" , "*XmLGrid.background", "Netscape*XmList.background" , "Netscape*XmLGrid.background", "*text*background", "*list*background", "*Text*background", "*List*background", "*textBackground", "*XmTextField.background", "*XmText.background", "Netscape*XmTextField.background", "Netscape*XmText.background", "*background", "*Background", "nscal*Background", "*Menu*background", "OpenWindows*WindowColor", "Window.Color.Background", "netscape*background", "Netscape*background", ".netscape*background", "Ddd*background", "Emacs*Background", "Emacs*backgroundToolBarColor",//25 "*XmList.selectBackground" , "*XmLGrid.selectBackground", "Netscape*XmList.selectBackground" , "Netscape*XmLGrid.selectBackground", "*XmTextField.selectBackground", "*XmText.selectBackground", "Netscape*XmTextField.selectBackground", "Netscape*XmText.selectBackground", "*selectBackground" //34 }; FILE *colorFile = fopen(filePath, "w"); for (int i = 0 ; i < 34; i++) { fprintf(colorFile, "%s: #%02X%02X%02X\n", backgroundTypes[i],(short int) r, (short int) g, (short int) b); } fprintf(colorFile, "foreground: #%02X%02X%02X\n", r1, g1, b1); fprintf(colorFile, "xterm*background: #FFFFFF\n"); //especialy for Xterm fclose(colorFile); Fl_String runString("xrdb -merge -all "); runString += fl_homedir(); runString += "/.Xdefaults"; if (fl_start_child_process(runString)==-1) fl_alert("Error executing xrdb program."); }
void QgsPythonUtilsImpl::initPython( QgisInterface* interface ) { init(); if ( !checkSystemImports() ) { exitPython(); return; } // initialize 'iface' object runString( "qgis.utils.initInterface(" + QString::number(( unsigned long ) interface ) + ')' ); if ( !checkQgisUser() ) { exitPython(); return; } finish(); }
void runVoid(CppiaCtx *ctx) { if (FUNC==afSort) { ArrayBase *thisVal = (ArrayBase *)thisExpr->runObject(ctx); BCR_VCHECK; Dynamic a0 = args[0]->runObject(ctx); BCR_VCHECK; thisVal->__sort(a0); return; } if (FUNC==afInsert) { ArrayBase *thisVal = (ArrayBase *)thisExpr->runObject(ctx); BCR_VCHECK; Dynamic pos = args[0]->runObject(ctx); BCR_VCHECK; Dynamic val = args[1]->runObject(ctx); BCR_VCHECK; thisVal->__insert(pos, val); return; } if (FUNC==afUnshift) { ArrayBase *thisVal = (ArrayBase *)thisExpr->runObject(ctx); BCR_VCHECK; Dynamic val = args[0]->runObject(ctx); BCR_VCHECK; thisVal->__unshift(val); return; } switch(inlineGetType()) { case etString: runString(ctx); return; case etInt: runInt(ctx); return; default: runObject(ctx); } }
bool Script::load(std::string const& filename) { std::vector<char> data; // Read file std::ifstream inf(filename.c_str(), std::ios::binary); if (!inf.good()) { inf.close(); return false; } char ch; while (inf.get(ch)) data.push_back(ch); inf.close(); data.push_back('\0'); return runString(std::string(&data[0]), filename); }
void setProfile(const TCHAR *profileName, int cmdIndex) { if (-1 != g_currentProfileIndex) { ::SendMessage(nppData._nppHandle, NPPM_SETMENUITEMCHECK, funcItem[g_currentProfileIndex]._cmdID, FALSE); } ::SendMessage(nppData._nppHandle, NPPM_SETMENUITEMCHECK, funcItem[cmdIndex]._cmdID, TRUE); if (g_initialised) { TCHAR cmd[150]; _tcscpy_s(cmd, 150, _T("npp_zen_coding.set_profile('")); _tcscat_s(cmd, 150, profileName); _tcscat_s(cmd, 150, _T("')")); runString(cmd); } g_currentProfile = profileName; g_currentProfileIndex = cmdIndex; }
extern "C" __declspec(dllexport) void beNotified(SCNotification *notifyCode) { switch(notifyCode->nmhdr.code) { case NPPN_READY: { ShortcutKey key; ::SendMessage(nppData._nppHandle, NPPM_GETSHORTCUTBYCMDID, funcItem[0]._cmdID, reinterpret_cast<LPARAM>(&key)); g_expandIsTab = keyIsTab(key); loadSettings(); // Lazy initialisation, so don't call initialise() yet //initialise(); } break; case NPPN_SHORTCUTREMAPPED: if (funcItem[0]._cmdID == notifyCode->nmhdr.idFrom) { g_expandIsTab = keyIsTab(*reinterpret_cast<ShortcutKey*>(notifyCode->nmhdr.hwndFrom)); } break; case NPPN_BUFFERACTIVATED: case NPPN_LANGCHANGED: if (g_autoSelectProfile) { int lang = ::SendMessage(nppData._nppHandle, NPPM_GETBUFFERLANGTYPE, notifyCode->nmhdr.idFrom, 0); switch(lang) { case L_XML: setProfile(_T("xml"), g_fiProfileXml); break; case L_TXT: setProfile(_T("plain"), g_fiProfilePlain); break; case L_HTML: default: setProfile(_T("xhtml"), g_fiProfileXhtml); break; } } break; case NPPN_FILESAVED: if (g_watchSave) { TCHAR filename[MAX_PATH]; ::SendMessage(nppData._nppHandle, NPPM_GETFULLPATHFROMBUFFERID, notifyCode->nmhdr.idFrom, reinterpret_cast<LPARAM>(filename)); if (0 == _tcsicmp(filename, g_settingsFile)) { if (g_initialised) { runString(_T("npp_zen_coding.update_settings()")); ::MessageBox(nppData._nppHandle, _T("Zen Coding settings automatically refreshed"), _T("Zen Coding for Notepad++"), MB_ICONINFORMATION); } else { ::MessageBox(nppData._nppHandle, _T("New Zen Coding settings have been applied"), _T("Zen Coding for Notepad++"), MB_ICONINFORMATION); } } } break; } }
bool QgsPythonUtilsImpl::checkSystemImports() { runString( "import sys" ); // import sys module (for display / exception hooks) runString( "import os" ); // import os module (for user paths) // support for PYTHONSTARTUP-like environment variable: PYQGIS_STARTUP // (unlike PYTHONHOME and PYTHONPATH, PYTHONSTARTUP is not supported for embedded interpreter by default) // this is different than user's 'startup.py' (below), since it is loaded just after Py_Initialize // it is very useful for cleaning sys.path, which may have undesireable paths, or for // isolating/loading the initial environ without requiring a virt env, e.g. homebrew or MacPorts installs on Mac runString( "pyqgstart = os.getenv('PYQGIS_STARTUP')\n" ); runString( "if pyqgstart is not None and os.path.exists(pyqgstart):\n with open(pyqgstart) as f:\n exec(f.read())\n" ); #ifdef Q_OS_WIN runString( "oldhome=None" ); runString( "if os.environ.has_key('HOME'): oldhome=os.environ['HOME']\n" ); runString( "os.environ['HOME']=os.environ['USERPROFILE']\n" ); #endif // construct a list of plugin paths // plugin dirs passed in QGIS_PLUGINPATH env. variable have highest priority (usually empty) // locally installed plugins have priority over the system plugins // use os.path.expanduser to support usernames with special characters (see #2512) QStringList pluginpaths; Q_FOREACH ( QString p, extraPluginsPaths() ) { if ( !QDir( p ).exists() ) { QgsMessageOutput* msg = QgsMessageOutput::createMessageOutput(); msg->setTitle( QObject::tr( "Python error" ) ); msg->setMessage( QObject::tr( "The extra plugin path '%1' does not exist!" ).arg( p ), QgsMessageOutput::MessageText ); msg->showMessage(); } #ifdef Q_OS_WIN p.replace( '\\', "\\\\" ); #endif // we store here paths in unicode strings // the str constant will contain utf8 code (through runString) // so we call '...'.decode('utf-8') to make a unicode string #if (PY_VERSION_HEX < 0x03000000) pluginpaths << '"' + p + "\".decode('utf-8')"; #else pluginpaths << '"' + p + '"'; #endif } pluginpaths << homePluginsPath(); pluginpaths << '"' + pluginsPath() + '"'; // expect that bindings are installed locally, so add the path to modules // also add path to plugins QStringList newpaths; newpaths << '"' + pythonPath() + '"'; newpaths << homePythonPath(); newpaths << pluginpaths; runString( "sys.path = [" + newpaths.join( "," ) + "] + sys.path" ); // import SIP if ( !runString( "import sip", QObject::tr( "Couldn't load SIP module." ) + '\n' + QObject::tr( "Python support will be disabled." ) ) ) { return false; } // set PyQt4 api versions QStringList apiV2classes; apiV2classes << "QDate" << "QDateTime" << "QString" << "QTextStream" << "QTime" << "QUrl" << "QVariant"; Q_FOREACH ( const QString& clsName, apiV2classes ) { if ( !runString( QString( "sip.setapi('%1', 2)" ).arg( clsName ), QObject::tr( "Couldn't set SIP API versions." ) + '\n' + QObject::tr( "Python support will be disabled." ) ) ) { return false; } } #if (PY_VERSION_HEX < 0x03000000) // import Qt bindings if ( !runString( "from PyQt4 import QtCore, QtGui", QObject::tr( "Couldn't load PyQt." ) + '\n' + QObject::tr( "Python support will be disabled." ) ) ) { return false; } #else // import Qt bindings if ( !runString( "from PyQt5 import QtCore, QtGui", QObject::tr( "Couldn't load PyQt." ) + '\n' + QObject::tr( "Python support will be disabled." ) ) ) { return false; } #endif // import QGIS bindings QString error_msg = QObject::tr( "Couldn't load PyQGIS." ) + '\n' + QObject::tr( "Python support will be disabled." ); if ( !runString( "from qgis.core import *", error_msg ) || !runString( "from qgis.gui import *", error_msg ) ) { return false; } // import QGIS utils error_msg = QObject::tr( "Couldn't load QGIS utils." ) + '\n' + QObject::tr( "Python support will be disabled." ); if ( !runString( "import qgis.utils", error_msg ) ) { return false; } // tell the utils script where to look for the plugins runString( "qgis.utils.plugin_paths = [" + pluginpaths.join( "," ) + ']' ); runString( "qgis.utils.sys_plugin_path = \"" + pluginsPath() + '\"' ); runString( "qgis.utils.home_plugin_path = " + homePluginsPath() ); #ifdef Q_OS_WIN runString( "if oldhome: os.environ['HOME']=oldhome\n" ); #endif return true; }
void doEvaluateMathExpression() { CHECK_INITIALISED(); runString(_T("npp_zen_coding.evaluate_math_expression()")); }
void QgsPythonUtilsImpl::doUserImports() { QString startuppath = homePythonPath() + " + \"/startup.py\""; runString( "if os.path.exists(" + startuppath + "): from startup import *\n" ); }
void QgsPythonUtilsImpl::uninstallErrorHook() { runString( "qgis.utils.uninstallErrorHook()" ); }
void doAutocomplete() { CHECK_INITIALISED(); runString(_T("npp_zen_coding.show_autocomplete()")); }
void doReflectCssValue() { CHECK_INITIALISED(); runString(_T("npp_zen_coding.reflect_css_value()")); }
void doAddAbbreviation() { CHECK_INITIALISED(); runString(_T("npp_zen_coding.add_entry('abbreviations')")); }
hx::Object *runObject(CppiaCtx *ctx) { if (FUNC==af__get) { Array_obj<ELEM> *thisVal = (Array_obj<ELEM>*)thisExpr->runObject(ctx); BCR_CHECK; int idx = args[0]->runInt(ctx); BCR_CHECK; return thisVal->__GetItem(idx).mPtr; } if (FUNC==af__set) { Array_obj<ELEM> *thisVal = (Array_obj<ELEM>*)thisExpr->runObject(ctx); BCR_CHECK; int i = args[0]->runInt(ctx); BCR_CHECK; ELEM elem; thisVal->Item(i) = runValue(elem,ctx,args[1]); return Dynamic(elem).mPtr; } if (FUNC==af__crement) { Array_obj<ELEM> *thisVal = (Array_obj<ELEM>*)thisExpr->runObject(ctx); BCR_CHECK; int idx = args[0]->runInt(ctx); BCR_CHECK; ELEM &elem = thisVal->Item(idx); return Dynamic(CREMENT::run(elem)).mPtr; } if (FUNC==afPop) { Array_obj<ELEM> *thisVal = (Array_obj<ELEM>*)thisExpr->runObject(ctx); BCR_CHECK; return Dynamic(thisVal->pop()).mPtr; } if (FUNC==afShift) { Array_obj<ELEM> *thisVal = (Array_obj<ELEM>*)thisExpr->runObject(ctx); BCR_CHECK; return Dynamic(thisVal->shift()).mPtr; } if (FUNC==afConcat) { Array_obj<ELEM> *thisVal = (Array_obj<ELEM>*)thisExpr->runObject(ctx); BCR_CHECK; Array_obj<ELEM> *inVal = (Array_obj<ELEM>*)args[0]->runObject(ctx); BCR_CHECK; return thisVal->concat(inVal).mPtr; } if (FUNC==afCopy) { Array_obj<ELEM> *thisVal = (Array_obj<ELEM>*)thisExpr->runObject(ctx); BCR_CHECK; return thisVal->copy().mPtr; } if (FUNC==afSplice) { Array_obj<ELEM> *thisVal = (Array_obj<ELEM>*)thisExpr->runObject(ctx); BCR_CHECK; int pos = args[0]->runInt(ctx); BCR_CHECK; int end = args[1]->runInt(ctx); BCR_CHECK; return thisVal->splice(pos,end).mPtr; } if (FUNC==afSlice) { Array_obj<ELEM> *thisVal = (Array_obj<ELEM>*)thisExpr->runObject(ctx); BCR_CHECK; int pos = args[0]->runInt(ctx); BCR_CHECK; hx::Object *end = args[1]->runObject(ctx); BCR_CHECK; return thisVal->slice(pos,end).mPtr; } if (FUNC==afMap) { // TODO - maybe make this more efficient Array_obj<ELEM> *thisVal = (Array_obj<ELEM>*)thisExpr->runObject(ctx); BCR_CHECK; hx::Object *func = args[0]->runObject(ctx); BCR_CHECK; Array<ELEM> result = thisVal->map(func); return result.mPtr; } if (FUNC==afFilter) { Array_obj<ELEM> *thisVal = (Array_obj<ELEM>*)thisExpr->runObject(ctx); BCR_CHECK; hx::Object *func = args[0]->runObject(ctx); BCR_CHECK; return thisVal->filter(func).mPtr; } if (FUNC==afIterator) { Array_obj<ELEM> *thisVal = (Array_obj<ELEM>*)thisExpr->runObject(ctx); BCR_CHECK; return thisVal->iterator().mPtr; } if (FUNC==afPush) return Dynamic(runInt(ctx)).mPtr; if (FUNC==afRemove) return Dynamic((bool)runInt(ctx)).mPtr; if (FUNC==afJoin) return Dynamic(runString(ctx)).mPtr; return 0; }
void QgsPythonUtilsImpl::initPython( QgisInterface* interface ) { // initialize python Py_Initialize(); // initialize threading AND acquire GIL PyEval_InitThreads(); mPythonEnabled = true; mMainModule = PyImport_AddModule( "__main__" ); // borrowed reference mMainDict = PyModule_GetDict( mMainModule ); // borrowed reference runString( "import sys" ); // import sys module (for display / exception hooks) runString( "import os" ); // import os module (for user paths) // support for PYTHONSTARTUP-like environment variable: PYQGIS_STARTUP // (unlike PYTHONHOME and PYTHONPATH, PYTHONSTARTUP is not supported for embedded interpreter by default) // this is different than user's 'startup.py' (below), since it is loaded just after Py_Initialize // it is very useful for cleaning sys.path, which may have undesireable paths, or for // isolating/loading the initial environ without requiring a virt env, e.g. homebrew or MacPorts installs on Mac runString( "pyqgstart = os.getenv('PYQGIS_STARTUP')\n" ); runString( "if pyqgstart is not None and os.path.exists(pyqgstart): execfile(pyqgstart)\n" ); #ifdef Q_OS_WIN runString( "oldhome=None" ); runString( "if os.environ.has_key('HOME'): oldhome=os.environ['HOME']\n" ); runString( "os.environ['HOME']=os.environ['USERPROFILE']\n" ); #endif // construct a list of plugin paths // plugin dirs passed in QGIS_PLUGINPATH env. variable have highest priority (usually empty) // locally installed plugins have priority over the system plugins // use os.path.expanduser to support usernames with special characters (see #2512) QStringList pluginpaths; foreach ( QString p, extraPluginsPaths() ) { if ( !QDir( p ).exists() ) { QgsMessageOutput* msg = QgsMessageOutput::createMessageOutput(); msg->setTitle( QObject::tr( "Python error" ) ); msg->setMessage( QString( QObject::tr( "The extra plugin path '%1' does not exist !" ) ).arg( p ), QgsMessageOutput::MessageText ); msg->showMessage(); } #ifdef Q_OS_WIN p = p.replace( '\\', "\\\\" ); #endif // we store here paths in unicode strings // the str constant will contain utf8 code (through runString) // so we call '...'.decode('utf-8') to make a unicode string pluginpaths << '"' + p + "\".decode('utf-8')"; } pluginpaths << homePluginsPath(); pluginpaths << '"' + pluginsPath() + '"'; // expect that bindings are installed locally, so add the path to modules // also add path to plugins QStringList newpaths; newpaths << '"' + pythonPath() + '"'; newpaths << homePythonPath(); newpaths << pluginpaths; runString( "sys.path = [" + newpaths.join( "," ) + "] + sys.path" ); // import SIP if ( !runString( "import sip", QObject::tr( "Couldn't load SIP module." ) + "\n" + QObject::tr( "Python support will be disabled." ) ) ) { exitPython(); return; } // set PyQt4 api versions QStringList apiV2classes; apiV2classes << "QDate" << "QDateTime" << "QString" << "QTextStream" << "QTime" << "QUrl" << "QVariant"; foreach ( const QString& clsName, apiV2classes ) { if ( !runString( QString( "sip.setapi('%1', 2)" ).arg( clsName ), QObject::tr( "Couldn't set SIP API versions." ) + "\n" + QObject::tr( "Python support will be disabled." ) ) ) { exitPython(); return; } } // import Qt bindings if ( !runString( "from PyQt4 import QtCore, QtGui", QObject::tr( "Couldn't load PyQt4." ) + "\n" + QObject::tr( "Python support will be disabled." ) ) ) { exitPython(); return; } // import QGIS bindings QString error_msg = QObject::tr( "Couldn't load PyQGIS." ) + "\n" + QObject::tr( "Python support will be disabled." ); if ( !runString( "from qgis.core import *", error_msg ) || !runString( "from qgis.gui import *", error_msg ) ) { exitPython(); return; } // import QGIS utils error_msg = QObject::tr( "Couldn't load QGIS utils." ) + "\n" + QObject::tr( "Python support will be disabled." ); if ( !runString( "import qgis.utils", error_msg ) ) { exitPython(); return; } // tell the utils script where to look for the plugins runString( "qgis.utils.plugin_paths = [" + pluginpaths.join( "," ) + "]" ); runString( "qgis.utils.sys_plugin_path = \"" + pluginsPath() + "\"" ); runString( "qgis.utils.home_plugin_path = " + homePluginsPath() ); #ifdef Q_OS_WIN runString( "if oldhome: os.environ['HOME']=oldhome\n" ); #endif // initialize 'iface' object runString( "qgis.utils.initInterface(" + QString::number(( unsigned long ) interface ) + ")" ); QString startuppath = homePythonPath() + " + \"/startup.py\""; runString( "if os.path.exists(" + startuppath + "): from startup import *\n" ); // release GIL! // Later on, we acquire GIL just before doing some Python calls and // release GIL again when the work with Python API is done. // (i.e. there must be PyGILState_Ensure + PyGILState_Release pair // around any calls to Python API, otherwise we may segfault!) _mainState = PyEval_SaveThread(); }
void doAddSnippet() { CHECK_INITIALISED(); runString(_T("npp_zen_coding.add_entry('snippets')")); }
void runScript(TCHAR *str) { runString(str, PYSCR_EXECSCRIPT); }