forked from bruderstein/PythonScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonHandler.cpp
More file actions
455 lines (367 loc) · 11.1 KB
/
PythonHandler.cpp
File metadata and controls
455 lines (367 loc) · 11.1 KB
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
204
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
268
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
#include "stdafx.h"
#include "PythonHandler.h"
#include "Scintilla.h"
#include "ScintillaWrapper.h"
#include "ScintillaPython.h"
#include "NotepadPlusWrapper.h"
#include "NotepadPython.h"
#include "PythonConsole.h"
#include "MenuManager.h"
#include "WcharMbcsConverter.h"
#include "GILManager.h"
#include "ConfigFile.h"
namespace NppPythonScript
{
PythonHandler::PythonHandler(TCHAR *pluginsDir, TCHAR *configDir, HINSTANCE hInst, HWND nppHandle, HWND scintilla1Handle, HWND scintilla2Handle, boost::shared_ptr<PythonConsole> pythonConsole)
: PyProducerConsumer<RunScriptArgs>(),
m_nppHandle(nppHandle),
m_scintilla1Handle(scintilla1Handle),
m_scintilla2Handle(scintilla2Handle),
m_hInst(hInst),
m_machineBaseDir(pluginsDir),
m_userBaseDir(configDir),
mp_console(pythonConsole),
m_currentView(0),
mp_mainThreadState(NULL),
m_consumerStarted(false)
{
m_machineBaseDir.append(_T("\\PythonScript\\"));
m_userBaseDir.append(_T("\\PythonScript\\"));
mp_notepad = createNotepadPlusWrapper();
mp_scintilla = createScintillaWrapper();
mp_scintilla1.reset(new ScintillaWrapper(scintilla1Handle, m_nppHandle));
mp_scintilla2.reset(new ScintillaWrapper(scintilla2Handle, m_nppHandle));
}
PythonHandler::~PythonHandler(void)
{
try
{
if (Py_IsInitialized())
{
if (consumerBusy())
{
stopScript();
}
// We need to swap back to the main thread
GILLock lock; // It's actually pointless, as we don't need it anymore,
// but we'll grab it anyway, just in case we need to wait for something to finish
// Can't call finalize with boost::python.
// Py_Finalize();
}
// To please Lint, let's NULL these handles
m_hInst = NULL;
m_nppHandle = NULL;
mp_mainThreadState = NULL;
}
catch (...)
{
// I don't know what to do with that, but a destructor should never throw, so...
}
}
boost::shared_ptr<ScintillaWrapper> PythonHandler::createScintillaWrapper()
{
m_currentView = mp_notepad->getCurrentView();
return boost::shared_ptr<ScintillaWrapper>(new ScintillaWrapper(m_currentView ? m_scintilla2Handle : m_scintilla1Handle, m_nppHandle));
}
boost::shared_ptr<NotepadPlusWrapper> PythonHandler::createNotepadPlusWrapper()
{
return boost::shared_ptr<NotepadPlusWrapper>(new NotepadPlusWrapper(m_hInst, m_nppHandle));
}
void PythonHandler::initPython()
{
if (Py_IsInitialized())
return;
preinitScintillaModule();
PyStatus status;
PyConfig config;
PyConfig_InitPythonConfig(&config);
// Read all configuration at once
// implicit pre config python
status = PyConfig_Read(&config);
if (PyStatus_Exception(status))
{
PyConfig_Clear(&config);
}
// Don't import site - if Python 2.7 doesn't find it as part of Py_Initialize,
// it does an exit(1) - AGH!
Py_NoSiteFlag = 1;
Py_IgnoreEnvironmentFlag = 1;
Py_NoUserSiteDirectory = 1;
#ifdef DEBUG
Py_VerboseFlag = 1;
#endif
bool configSetFailed = false;
//appended or prepended below in this order
std::wstring machinelib = m_machineBaseDir + std::wstring(L"lib");
std::wstring userlib = m_userBaseDir + std::wstring(L"lib");
std::wstring machineScripts = m_machineBaseDir + std::wstring(L"scripts");
std::wstring userScripts = m_userBaseDir + std::wstring(L"scripts");
std::wstring machinelibTK = m_machineBaseDir + std::wstring(L"lib\\lib-tk");
// If the user wants to use their installed python version, append the paths.
// If not (and they want to use the bundled python install), the default, then prepend the paths
if (ConfigFile::getInstance()->getSetting(_T("PREFERINSTALLEDPYTHON")) == _T("1"))
{
/* Append our custom search path to sys.path */
status = PyWideStringList_Append(&config.module_search_paths,
machinelib.c_str());
if (PyStatus_Exception(status))
{
configSetFailed = true;
}
/* Append our custom search path to sys.path */
status = PyWideStringList_Append(&config.module_search_paths,
userlib.c_str());
if (PyStatus_Exception(status))
{
configSetFailed = true;
}
/* Append our custom search path to sys.path */
status = PyWideStringList_Append(&config.module_search_paths,
machineScripts.c_str());
if (PyStatus_Exception(status))
{
configSetFailed = true;
}
/* Append our custom search path to sys.path */
status = PyWideStringList_Append(&config.module_search_paths,
userScripts.c_str());
if (PyStatus_Exception(status))
{
configSetFailed = true;
}
/* Append our custom search path to sys.path */
status = PyWideStringList_Append(&config.module_search_paths,
machinelibTK.c_str());
if (PyStatus_Exception(status))
{
configSetFailed = true;
}
}
else
{
/* Prepend via insert our custom search path to sys.path */
status = PyWideStringList_Insert(&config.module_search_paths, 0,
machinelib.c_str());
if (PyStatus_Exception(status))
{
configSetFailed = true;
}
/* Prepend via insert our custom search path to sys.path */
status = PyWideStringList_Insert(&config.module_search_paths, 1,
userlib.c_str());
if (PyStatus_Exception(status))
{
PyConfig_Clear(&config);
}
/* Prepend via insert our custom search path to sys.path */
status = PyWideStringList_Insert(&config.module_search_paths, 2,
machineScripts.c_str());
if (PyStatus_Exception(status))
{
configSetFailed = true;
}
/* Prepend via insert our custom search path to sys.path */
status = PyWideStringList_Insert(&config.module_search_paths, 3,
userScripts.c_str());
if (PyStatus_Exception(status))
{
PyConfig_Clear(&config);
}
/* Prepend via insert our custom search path to sys.path */
status = PyWideStringList_Insert(&config.module_search_paths, 4,
machinelibTK.c_str());
if (PyStatus_Exception(status))
{
configSetFailed = true;
}
}
if (!configSetFailed)
{
status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status))
{
PyConfig_Clear(&config);
}
}
std::string importSys("import sys\n");
PyRun_SimpleString(importSys.c_str());
initSysArgv();
// Init Notepad++/Scintilla modules
initModules();
mp_mainThreadState = PyEval_SaveThread();
}
void PythonHandler::initSysArgv()
{
LPWSTR commandLine = ::GetCommandLineW();
int argc;
LPWSTR* argv = ::CommandLineToArgvW(commandLine, &argc);
boost::python::list argvList;
for(int currentArg = 0; currentArg != argc; ++currentArg)
{
std::shared_ptr<char> argInUtf8 = WcharMbcsConverter::wchar2char(argv[currentArg]);
PyObject* unicodeArg = PyUnicode_FromString(argInUtf8.get());
argvList.append(boost::python::handle<>(unicodeArg));
}
boost::python::object sysModule(boost::python::handle<>(boost::python::borrowed(PyImport_AddModule("sys"))));
sysModule.attr("argv") = argvList;
}
void PythonHandler::initModules()
{
importScintilla(mp_scintilla, mp_scintilla1, mp_scintilla2);
importNotepad(mp_notepad);
importConsole(mp_console);
}
bool PythonHandler::containsExtendedChars(char *s)
{
bool retVal = false;
for(int pos = 0; s[pos]; ++pos)
{
if (s[pos] & 0x80)
{
retVal = true;
break;
}
}
return retVal;
}
void PythonHandler::runStartupScripts()
{
// Machine scripts (N++\Plugins\PythonScript\scripts dir)
tstring startupPath(m_machineBaseDir);
startupPath.append(_T("scripts\\startup.py"));
if (::PathFileExists(startupPath.c_str()))
{
runScript(startupPath, true);
}
// User scripts ($CONFIGDIR$\PythonScript\scripts dir)
startupPath = m_userBaseDir;
startupPath.append(_T("scripts\\startup.py"));
if (::PathFileExists(startupPath.c_str()))
{
runScript(startupPath, true);
}
}
bool PythonHandler::runScript(const tstring& scriptFile,
bool synchronous /* = false */,
bool allowQueuing /* = false */,
HANDLE completedEvent /* = NULL */,
bool isStatement /* = false */)
{
return runScript(scriptFile.c_str(), synchronous, allowQueuing, completedEvent, isStatement);
}
bool PythonHandler::runScript(const TCHAR *filename,
bool synchronous /* = false */,
bool allowQueuing /* = false */,
HANDLE completedEvent /* = NULL */,
bool isStatement /* = false */)
{
bool retVal;
if (!allowQueuing && consumerBusy())
{
retVal = false;
}
else
{
std::shared_ptr<RunScriptArgs> args(
new RunScriptArgs(
filename,
mp_mainThreadState,
synchronous,
completedEvent,
isStatement));
if (!synchronous)
{
retVal = produce(args);
if (!m_consumerStarted)
{
startConsumer();
}
}
else
{
runScriptWorker(args);
retVal = true;
}
}
return retVal;
}
void PythonHandler::consume(std::shared_ptr<RunScriptArgs> args)
{
runScriptWorker(args);
}
void PythonHandler::runScriptWorker(const std::shared_ptr<RunScriptArgs>& args)
{
GILLock gilLock;
if (args->m_isStatement)
{
if (PyRun_SimpleString(WcharMbcsConverter::tchar2char(args->m_filename.c_str()).get()) == -1)
{
if (ConfigFile::getInstance()->getSetting(_T("ADDEXTRALINETOOUTPUT")) == _T("1"))
{
mp_console->writeText(boost::python::str("\n"));
}
if (ConfigFile::getInstance()->getSetting(_T("OPENCONSOLEONERROR")) == _T("1"))
{
mp_console->pythonShowDialog();
}
}
}
else
{
FILE* pyFile = _Py_wfopen(args->m_filename.c_str(), _T("rb"));
if (pyFile)
{
if (PyRun_SimpleFileEx(pyFile, WcharMbcsConverter::tchar2char(args->m_filename.c_str()).get(), 1) == -1)
{
if (ConfigFile::getInstance()->getSetting(_T("ADDEXTRALINETOOUTPUT")) == _T("1"))
{
mp_console->writeText(boost::python::str("\n"));
}
if (ConfigFile::getInstance()->getSetting(_T("OPENCONSOLEONERROR")) == _T("1"))
{
mp_console->pythonShowDialog();
}
}
}
}
if (NULL != args->m_completedEvent)
{
SetEvent(args->m_completedEvent);
}
}
void PythonHandler::notify(SCNotification *notifyCode)
{
if (notifyCode->nmhdr.hwndFrom == m_scintilla1Handle || notifyCode->nmhdr.hwndFrom == m_scintilla2Handle)
{
mp_scintilla->notify(notifyCode);
}
else if (notifyCode->nmhdr.hwndFrom != mp_console->getScintillaHwnd()) // ignore console notifications
{
// Change the active scintilla handle for the "buffer" variable if the active buffer has changed
if (notifyCode->nmhdr.code == NPPN_BUFFERACTIVATED)
{
int newView = mp_notepad->getCurrentView();
if (newView != m_currentView)
{
m_currentView = newView;
mp_scintilla->setHandle(newView ? m_scintilla2Handle : m_scintilla1Handle);
}
}
mp_notepad->notify(notifyCode);
}
}
void PythonHandler::queueComplete()
{
MenuManager::getInstance()->stopScriptEnabled(false);
}
void PythonHandler::stopScript()
{
DWORD threadID;
CreateThread(NULL, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(stopScriptWorker), this, 0, &threadID);
}
void PythonHandler::stopScriptWorker(PythonHandler *handler)
{
GILLock gilLock;
PyThreadState_SetAsyncExc((long)handler->getExecutingThreadID(), PyExc_KeyboardInterrupt);
}
}