Repository navigation
Expand file tree
/
Copy pathPythonCodeCompletion.cpp
More file actions
801 lines (725 loc) · 32.2 KB
/
Copy pathPythonCodeCompletion.cpp
File metadata and controls
801 lines (725 loc) · 32.2 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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
#include <sdk.h> // Code::Blocks SDK
#include <configurationpanel.h>
#include "PythonCodeCompletion.h"
#include <editormanager.h>
#include <cbeditor.h>
#include <cbstyledtextctrl.h>
#include <editor_hooks.h>
#include <configmanager.h>
#include <logmanager.h>
//
//#include <settings.h> // SDK
//#include <cbplugin.h>
//#include <cbproject.h>
//#include <sdk_events.h>
#include "XmlRpc.h"
#include <wx/arrstr.h>
#include <wx/string.h>
#include <wx/imaglist.h>
int ID_EDITOR_HOOKS = wxNewId();
int ID_STDLIB_LOAD = wxNewId();
int ID_COMPLETE_PHRASE = wxNewId();
int ID_CALLTIP = wxNewId();
int ID_GOTO_DECLARATION = wxNewId();
// Register the plugin with Code::Blocks.
// We are using an anonymous namespace so we don't litter the global one.
namespace
{
PluginRegistrant<PythonCodeCompletion> reg(_T("PythonCodeCompletion"));
}
// events handling
BEGIN_EVENT_TABLE(PythonCodeCompletion, cbCodeCompletionPlugin)
// add any events you want to handle here
EVT_XMLRPC_RESPONSE(ID_STDLIB_LOAD,PythonCodeCompletion::OnStdLibLoaded)
EVT_XMLRPC_RESPONSE(ID_COMPLETE_PHRASE,PythonCodeCompletion::OnCompletePhrase)
EVT_XMLRPC_RESPONSE(ID_CALLTIP,PythonCodeCompletion::OnCalltip)
EVT_XMLRPC_RESPONSE(ID_GOTO_DECLARATION,PythonCodeCompletion::OnGotoDefinition)
EVT_MENU(ID_GOTO_DECLARATION, PythonCodeCompletion::OnClickedGotoDefinition)
END_EVENT_TABLE()
// constructor
PythonCodeCompletion::PythonCodeCompletion()
{
// Make sure our resources are available.
// In the generated boilerplate code we have no resources but when
// we add some, it will be nice that this code is in place already ;)
if(!Manager::LoadResource(_T("PythonCodeCompletion.zip")))
{
NotifyMissingFile(_T("PythonCodeCompletion.zip"));
}
}
// destructor
PythonCodeCompletion::~PythonCodeCompletion()
{
}
wxString PythonCodeCompletion::GetExtraFile(const wxString &short_name)
{
wxString fullname=ConfigManager::GetFolder(sdDataUser)+short_name;
if(wxFileName::FileExists(fullname))
return fullname;
fullname=ConfigManager::GetFolder(sdDataGlobal)+short_name;
if(wxFileName::FileExists(fullname))
return fullname;
return wxEmptyString;
}
void PythonCodeCompletion::OnAttach()
{
// do whatever initialization you need for your plugin
// NOTE: after this function, the inherited member variable
// m_IsAttached will be TRUE...
// You should check for it in other functions, because if it
// is FALSE, it means that the application did *not* "load"
// (see: does not need) this plugin...
// hook to editors
py_server=NULL;
m_pImageList=NULL;
EditorHooks::HookFunctorBase* myhook = new EditorHooks::HookFunctor<PythonCodeCompletion>(this, &PythonCodeCompletion::EditorEventHook);
m_EditorHookId = EditorHooks::RegisterHook(myhook);
// register event sinks
Manager* pm = Manager::Get();
pm->RegisterEventSink(cbEVT_COMPLETE_CODE, new cbEventFunctor<PythonCodeCompletion, CodeBlocksEvent>(this, &PythonCodeCompletion::CompleteCodeEvt));
pm->RegisterEventSink(cbEVT_SHOW_CALL_TIP, new cbEventFunctor<PythonCodeCompletion, CodeBlocksEvent>(this, &PythonCodeCompletion::ShowCallTipEvt));
ConfigManager *mgr=Manager::Get()->GetConfigManager(_T("PythonCC"));
// static wxString GetHomeFolder() { return home_folder; }
// static wxString GetConfigFolder(){ return config_folder; }
// static wxString GetPluginsFolder(bool global = true){ return GetFolder(global ? sdPluginsGlobal : sdPluginsUser); }
// static wxString GetScriptsFolder(bool global = true){ return GetFolder(global ? sdScriptsGlobal : sdScriptsUser); }
// static wxString GetDataFolder(bool global = true){ return global ? data_path_global : data_path_user; }
// static wxString GetExecutableFolder(){ return app_path; }
// static wxString GetTempFolder(){ return GetFolder(sdTemp); }
wxString script = GetExtraFile(_T("/python/python_completion_server.py"));
if(script==wxEmptyString)
{
Manager::Get()->GetLogManager()->LogError(_T("PyCC: Missing python scripts. Try reinstalling the plugin."));
return;
}
#ifndef EMBEDDER_DEBUG
int port = -1; // Port == -1 uses pipe to do RPC over redirected stdin/stdout of the process, otherwise uses a socket
wxString command = wxString::Format(_T("python -u %s %i"),script.c_str(),port);
#else
int port = 34567;
wxString command = wxString::Format(_T("python -u %s %i"),script.c_str(),port);
// wxString command = wxString::Format(_T("python -u -m memory_profiler %s %i"),script.c_str(),port);
// wxString command = wxString::Format(_T("gnome-terminal -e \"python -u %s %i\""),script.c_str(),port);
#endif
Manager::Get()->GetLogManager()->DebugLog(_T("PyCC: Launching python on ")+script);
Manager::Get()->GetLogManager()->DebugLog(_T("PyCC: with command ")+command);
py_server = new XmlRpcInstance(command,port,_T("localhost"),0);
if(py_server->IsDead())
{
Manager::Get()->GetLogManager()->LogError(_("Error Starting Python Code Completion Server"));
return;
}
wxString prefix = ConfigManager::GetDataFolder() + _T("/images/codecompletion/");
// bitmaps must be added by order of PARSER_IMG_* consts
m_pImageList = new wxImageList(16, 16);
wxBitmap bmp;
bmp = cbLoadBitmap(prefix + _T("class_folder.png"), wxBITMAP_TYPE_PNG);
m_pImageList->Add(bmp); // PARSER_IMG_CLASS_FOLDER types.ModuleType
bmp = cbLoadBitmap(prefix + _T("class.png"), wxBITMAP_TYPE_PNG);
m_pImageList->Add(bmp); // PARSER_IMG_CLASS types.ClassType
bmp = cbLoadBitmap(prefix + _T("class_public.png"), wxBITMAP_TYPE_PNG);
m_pImageList->Add(bmp); // PARSER_IMG_CLASS_PUBLIC types.ObjectType
bmp = cbLoadBitmap(prefix + _T("typedef.png"), wxBITMAP_TYPE_PNG);
m_pImageList->Add(bmp); // PARSER_IMG_TYPEDEF types.TypeType
bmp = cbLoadBitmap(prefix + _T("var_public.png"), wxBITMAP_TYPE_PNG);
m_pImageList->Add(bmp); // PARSER_IMG_VAR_PUBLIC types.InstanceType
bmp = cbLoadBitmap(prefix + _T("method_public.png"), wxBITMAP_TYPE_PNG);
m_pImageList->Add(bmp); // PARSER_IMG_FUNC_PUBLIC types.FunctionType types.BuiltinFunctionType
bmp = cbLoadBitmap(prefix + _T("method_protected.png"), wxBITMAP_TYPE_PNG);
m_pImageList->Add(bmp); // PARSER_IMG_FUNC_PRIVATE types.MethodType types.BuiltinMethodType
bmp = cbLoadBitmap(prefix + _T("method_protected.png"), wxBITMAP_TYPE_PNG);
m_pImageList->Add(bmp); // PARSER_IMG_FUNC_PRIVATE types.MethodType
bmp = cbLoadBitmap(prefix + _T("method_private.png"), wxBITMAP_TYPE_PNG);
m_pImageList->Add(bmp); // PARSER_IMG_FUNC_PRIVATE
// bmp = cbLoadBitmap(prefix + _T("ctor_private.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_CTOR_PRIVATE
// bmp = cbLoadBitmap(prefix + _T("ctor_protected.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_CTOR_PROTECTED
// bmp = cbLoadBitmap(prefix + _T("ctor_public.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_CTOR_PUBLIC
// bmp = cbLoadBitmap(prefix + _T("dtor_private.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_DTOR_PRIVATE
// bmp = cbLoadBitmap(prefix + _T("dtor_protected.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_DTOR_PROTECTED
// bmp = cbLoadBitmap(prefix + _T("dtor_public.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_DTOR_PUBLIC
// bmp = cbLoadBitmap(prefix + _T("method_private.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_FUNC_PRIVATE
// bmp = cbLoadBitmap(prefix + _T("var_private.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_VAR_PRIVATE
// bmp = cbLoadBitmap(prefix + _T("var_protected.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_VAR_PROTECTED
// bmp = cbLoadBitmap(prefix + _T("preproc.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_PREPROCESSOR
// bmp = cbLoadBitmap(prefix + _T("enum.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_ENUM
// bmp = cbLoadBitmap(prefix + _T("enum_private.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_ENUM_PRIVATE
// bmp = cbLoadBitmap(prefix + _T("enum_protected.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_ENUM_PROTECTED
// bmp = cbLoadBitmap(prefix + _T("enum_public.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_ENUM_PUBLIC
// bmp = cbLoadBitmap(prefix + _T("enumerator.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_ENUMERATOR
// bmp = cbLoadBitmap(prefix + _T("namespace.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_NAMESPACE
// bmp = cbLoadBitmap(prefix + _T("typedef_private.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_TYPEDEF_PRIVATE
// bmp = cbLoadBitmap(prefix + _T("typedef_protected.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_TYPEDEF_PROTECTED
// bmp = cbLoadBitmap(prefix + _T("typedef_public.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_TYPEDEF_PUBLIC
// bmp = cbLoadBitmap(prefix + _T("symbols_folder.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_SYMBOLS_FOLDER
// bmp = cbLoadBitmap(prefix + _T("vars_folder.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_VARS_FOLDER
// bmp = cbLoadBitmap(prefix + _T("funcs_folder.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_FUNCS_FOLDER
// bmp = cbLoadBitmap(prefix + _T("enums_folder.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_ENUMS_FOLDER
// bmp = cbLoadBitmap(prefix + _T("preproc_folder.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_PREPROC_FOLDER
// bmp = cbLoadBitmap(prefix + _T("others_folder.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_OTHERS_FOLDER
// bmp = cbLoadBitmap(prefix + _T("typedefs_folder.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_TYPEDEF_FOLDER
// bmp = cbLoadBitmap(prefix + _T("macro.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_MACRO
// bmp = cbLoadBitmap(prefix + _T("macro_private.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_MACRO_PRIVATE
// bmp = cbLoadBitmap(prefix + _T("macro_protected.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_MACRO_PROTECTED
// bmp = cbLoadBitmap(prefix + _T("macro_public.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_MACRO_PUBLIC
// bmp = cbLoadBitmap(prefix + _T("macro_folder.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_MACRO_FOLDER
// bmp = cbLoadBitmap(prefix + _T("class_private.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_CLASS_PRIVATE
// bmp = cbLoadBitmap(prefix + _T("class_protected.png"), wxBITMAP_TYPE_PNG);
// m_pImageList->Add(bmp); // PARSER_IMG_CLASS_PROTECTED
// bmp = wxImage(cpp_keyword_xpm);
// m_pImageList->Add(bmp);
if(port!=-1)
::wxSleep(2); //need a delay to allow the xmlrpc server time to start
// Manager::Get()->GetLogManager()->Log(_("Loading stdlib"));
m_libs_loaded=true;
//Load the symbol lib synchronously
// XmlRpc::XmlRpcValue(result);
// if(py_server->Exec(_("load_stdlib"),XmlRpc::XmlRpcValue(stdlib.utf8_str()),result))
// m_libs_loaded=true;
// else
// m_libs_loaded=false;
//Load the symbol lib asynchronously
// py_server->ExecAsync(_("load_stdlib"),XmlRpc::XmlRpcValue(stdlib.utf8_str()),this,ID_STDLIB_LOAD);
// m_libs_loaded=false;
}
void PythonCodeCompletion::OnRelease(bool appShutDown)
{
// do de-initialization for your plugin
// if appShutDown is true, the plugin is unloaded because Code::Blocks is being shut down,
// which means you must not use any of the SDK Managers
// NOTE: after this function, the inherited member variable
// m_IsAttached will be FALSE...
EditorHooks::UnregisterHook(m_EditorHookId, true);
if(py_server && !py_server->IsDead()) //TODO: Really should wait until serverr is no longer busy and request it to terminate via XMLRPC
{
py_server->KillProcess(true);
delete py_server;
}
if(m_pImageList)
delete m_pImageList;
}
void PythonCodeCompletion::HandleError(XmlRpcResponseEvent &event, wxString message)
{
//TODO: Should probably kill/restart the XmlRpc server here
if (m_libs_loaded && py_server->IsDead())
{
wxString msg = _("The python code completion server has terminated unexpectedly. Python code completion has been disabled.\n\nDo you have python and jedi installed?");
cbMessageBox(msg+_("\nCheck the log for additional details"));
Manager::Get()->GetLogManager()->LogError(msg);
Manager::Get()->GetLogManager()->LogError(_("If everything is installed correctly, try restarting Code::Blocks or disable and re-enable the plugin in Settings -> Manage Plugins."));
Manager::Get()->GetLogManager()->LogError(_("You can get support at forums.codeblocks.org"));
m_libs_loaded = false;
}
if(event.GetState()==XMLRPC_STATE_REQUEST_FAILED)
{
if(m_libs_loaded)
cbMessageBox(_("Error processing python code completion result\nCheck the log for details"));
Manager::Get()->GetLogManager()->LogError(message);
Manager::Get()->GetLogManager()->LogError(wxString(event.GetResponse().toXml().c_str(),wxConvUTF8));
}
}
void PythonCodeCompletion::OnStdLibLoaded(XmlRpcResponseEvent &event)
{
if(event.GetState()==XMLRPC_STATE_RESPONSE)
{
m_libs_loaded=true;
Manager::Get()->GetLogManager()->DebugLog(_("PyCC: Completion Library is Initialized"));
}
else
HandleError(event,_T("PyCC: Error loading completion library"));
}
void PythonCodeCompletion::OnCalltip(XmlRpcResponseEvent &event)
{
if(event.GetState()==XMLRPC_STATE_RESPONSE)
{
XmlRpc::XmlRpcValue val=event.GetResponse();
if(val.getType()==val.TypeArray && val.size()>0)
val = val[0];
if(val.getType()==val.TypeString)
{
m_ActiveCalltipDef=wxString(std::string(val).c_str(),wxConvUTF8);
Manager::Get()->GetLogManager()->DebugLog(_("PyCC: Call tip result ")+m_ActiveCalltipDef);
ShowCallTip();
}
else
{
Manager::Get()->GetLogManager()->DebugLog(_("PyCC: Call tip result is not a string"));
XmlRpc::XmlRpcValue val=event.GetResponse();
Manager::Get()->GetLogManager()->DebugLog(wxString(val.toXml().c_str(),wxConvUTF8));
}
}
else
HandleError(event,_T("Error requesting calltip"));
}
void PythonCodeCompletion::OnCompletePhrase(XmlRpcResponseEvent &event)
{
if(event.GetState()==XMLRPC_STATE_RESPONSE)
{
Manager::Get()->GetLogManager()->DebugLog(_("PyCC: Completion response"));
XmlRpc::XmlRpcValue val=event.GetResponse();
m_comp_results.Empty();
if(val.getType()==val.TypeArray && val.size()>0)
{
Manager::Get()->GetLogManager()->DebugLog(_("PyCC: Getting comp results"));
for(int i=0;i<val.size();++i)
m_comp_results.Add(wxString(std::string(val[i]).c_str(),wxConvUTF8));
Manager::Get()->GetLogManager()->DebugLog(wxString::Format(_("PyCC: Beginning comp with %i items"),val.size()));
CodeComplete();
return;
}
Manager::Get()->GetLogManager()->DebugLog(_("PyCC: Unexpected phrase completion result"));
Manager::Get()->GetLogManager()->DebugLog(wxString(val.toXml().c_str(),wxConvUTF8));
return;
}
else
HandleError(event,_T("PyCC: Error requesting completion result"));
}
int PythonCodeCompletion::Configure()
{
//create and display the configuration dialog for your plugin
cbConfigurationDialog dlg(Manager::Get()->GetAppWindow(), wxID_ANY, _("Your dialog title"));
cbConfigurationPanel* panel = GetConfigurationPanel(&dlg);
if (panel)
{
dlg.AttachConfigurationPanel(panel);
PlaceWindow(&dlg);
return dlg.ShowModal() == wxID_OK ? 0 : -1;
}
return -1;
}
void PythonCodeCompletion::BuildMenu(wxMenuBar* menuBar)
{
//The application is offering its menubar for your plugin,
//to add any menu items you want...
//Append any items you need in the menu...
//NOTE: Be careful in here... The application's menubar is at your disposal.
NotImplemented(_T("PythonCodeCompletion::BuildMenu()"));
}
void PythonCodeCompletion::BuildModuleMenu(const ModuleType type, wxMenu* menu, const FileTreeData* data)
{
//Some library module is ready to display a pop-up menu.
//Check the parameter \"type\" and see which module it is
//and append any items you need in the menu...
//TIP: for consistency, add a separator as the first item...
// if not attached, exit
if (!menu || !IsAttached() || !m_libs_loaded)
return;
if (type == mtEditorManager)
{
cbEditor* ed = Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
if (!ed)
return;
cbStyledTextCtrl *control = ed->GetControl();
if(control->GetLexer() != wxSCI_LEX_PYTHON)
return;
int pos = control->GetCurrentPos();
int wordStartPos = control->WordStartPosition(pos, false);
int wordEndPos = control->WordEndPosition(pos, false);
wxString word = control->GetTextRange(wordStartPos, wordEndPos);
if (word.Find(' ')>=0)
return;
if(wordStartPos<wordEndPos)
{
wxString msg;
size_t pos = 0;
msg.Printf(_("Python: goto definition of '%s'"), word.wx_str());
menu->Insert(pos, ID_GOTO_DECLARATION, msg);
++pos;
}
}
}
bool PythonCodeCompletion::IsProviderFor(cbEditor *ed)
{
if(!m_libs_loaded)
return false;
if(ed->GetControl()->GetLexer()==wxSCI_LEX_PYTHON)
return true;
return false;
}
int PythonCodeCompletion::CodeComplete()
{
if (!IsAttached() || !m_libs_loaded)
return -1;
EditorManager* edMan = Manager::Get()->GetEditorManager();
cbEditor* ed = edMan->GetBuiltinActiveEditor();
if (!ed)
return -3;
if(true)
{
int maxmatches=100;
int count=0;
if(count<maxmatches)
{
cbStyledTextCtrl* control = ed->GetControl();
for (int i = 0; i < m_pImageList->GetImageCount(); i++)
control->RegisterImage(i+1,m_pImageList->GetBitmap(i));
int pos = control->GetCurrentPos();
//int start = ed->GetControl()->WordStartPosition(pos, true);
int wordStartPos = control->WordStartPosition(pos, true);
// while(control->GetCharAt(wordStartPos-1)==_T('.'))
// wordStartPos = control->WordStartPosition(wordStartPos-2, true);
int start=wordStartPos;
bool caseSens=true;
ed->GetControl()->AutoCompSetFillUps(wxEmptyString);
ed->GetControl()->AutoCompSetIgnoreCase(!caseSens);
ed->GetControl()->AutoCompSetCancelAtStart(true);
ed->GetControl()->AutoCompSetSeparator(' ');
ed->GetControl()->AutoCompSetTypeSeparator('?');
// ed->GetControl()->AutoCompSetFillUps(m_CCFillupChars);
// ed->GetControl()->AutoCompSetChooseSingle(m_IsAutoPopup ? false : m_CCAutoSelectOne);
ed->GetControl()->AutoCompSetAutoHide(true);
// ed->GetControl()->AutoCompSetDropRestOfWord(m_IsAutoPopup ? false : true);
// wxString final = GetStringFromArray(m_comp_results, _T("\n"));
wxString final = GetStringFromArray(m_comp_results, _T(" "));
final.RemoveLast(); // remove last space
ed->GetControl()->AutoCompShow(pos - start, final);
return 0;
}
else if (!ed->GetControl()->CallTipActive())
{
wxString msg = _("Too many results.\n"
"Please edit results' limit in code-completion options,\n"
"or type at least one more character to narrow the scope down.");
ed->GetControl()->CallTipShow(ed->GetControl()->GetCurrentPos(), msg);
return -2;
}
}
else if (!ed->GetControl()->CallTipActive())
{
wxString msg = _("The parser is still parsing files.");
ed->GetControl()->CallTipShow(ed->GetControl()->GetCurrentPos(), msg);
}
return -5;
}
void PythonCodeCompletion::ShowCallTip()
{
if (!IsAttached() || !m_libs_loaded)
return;
if (!Manager::Get()->GetEditorManager())
return;
cbEditor* ed = Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
if (!ed)
return;
Manager::Get()->GetLogManager()->DebugLog(_T("PyCC: Showing calltip"));
// calculate the size of the calltips window
int pos = ed->GetControl()->GetCurrentPos();
wxPoint p = ed->GetControl()->PointFromPosition(pos); // relative point
int pixelWidthPerChar = ed->GetControl()->TextWidth(wxSCI_STYLE_LINENUMBER, _T("W"));
int maxCalltipLineSizeInChars = (ed->GetSize().x - p.x) / pixelWidthPerChar;
if (maxCalltipLineSizeInChars < 64)
{
// if less than a threshold in chars, recalculate the starting position (instead of shrinking it even more)
p.x -= (64 - maxCalltipLineSizeInChars) * pixelWidthPerChar;
// but if it goes out of range, continue shrinking
if (p.x >= 0)
{
maxCalltipLineSizeInChars = 64;
pos = ed->GetControl()->PositionFromPoint(p);
}
// else, out of range
}
int start = 0, end = 0, count = 0, typedCommas = 0;
// int pos=m_ActiveCalltipPos;
wxString definition=m_ActiveCalltipDef;
ed->GetControl()->CallTipShow(pos, definition);
if (start != 0 && end > start)
ed->GetControl()->CallTipSetHighlight(start, end);
}
void PythonCodeCompletion::RequestCompletion(cbStyledTextCtrl *control, int pos, const wxString &filename)
{
int line = control->LineFromPosition(pos);
int column = pos - control->PositionFromLine(line);
XmlRpc::XmlRpcValue value;
value.setSize(4);
value[0] = filename.utf8_str(); //mb_str(wxConvUTF8);
value[1] = control->GetText().utf8_str(); //mb_str(wxConvUTF8);
value[2] = line;
value[3] = column;
py_server->ClearJobs();
py_server->ExecAsync(_T("complete_phrase"),value,this,ID_COMPLETE_PHRASE);
}
void PythonCodeCompletion::RequestCallTip(cbStyledTextCtrl *control, int pos, const wxString &filename)
{
int line = control->LineFromPosition(pos);
int column = pos - control->PositionFromLine(line);
XmlRpc::XmlRpcValue value;
value.setSize(4);
value[0] = filename.utf8_str(); //mb_str(wxConvUTF8);
value[1] = control->GetText().utf8_str(); //mb_str(wxConvUTF8);
value[2] = line;
value[3] = column;
py_server->ClearJobs();
py_server->ExecAsync(_T("complete_tip"),value,this,ID_CALLTIP);
Manager::Get()->GetLogManager()->DebugLog(_T("PyCC: Started server request"));
}
void PythonCodeCompletion::RequestDocString(cbStyledTextCtrl *control, int pos, const wxString &filename)
{
}
void PythonCodeCompletion::CompleteCodeEvt(CodeBlocksEvent& event)
{
event.Skip();
if(!m_libs_loaded)
return;
cbEditor *ed = Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
if(!ed)
return;
cbStyledTextCtrl *control = ed->GetControl();
if(control->GetLexer()!=wxSCI_LEX_PYTHON)
return;
int pos = control->GetCurrentPos();
wxString filename = ed->GetFilename();
RequestCompletion(control, pos, filename);
}
void PythonCodeCompletion::ShowCallTipEvt(CodeBlocksEvent& event)
{
event.Skip();
if(!m_libs_loaded)
return;
cbEditor *ed = Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
if(!ed)
return;
cbStyledTextCtrl *control = ed->GetControl();
if(control->GetLexer()!=wxSCI_LEX_PYTHON)
return;
int pos = control->GetCurrentPos();
wxString filename = ed->GetFilename();
RequestCallTip(control, pos, filename);
}
void PythonCodeCompletion::EditorEventHook(cbEditor* editor, wxScintillaEvent& event)
{
if(!m_libs_loaded)
return;
if (!IsAttached())
{
Manager::Get()->GetLogManager()->DebugLog(_("PyCC: Not attached"));
event.Skip();
return;
}
if(editor->GetControl()->GetLexer() != wxSCI_LEX_PYTHON)
{
event.Skip();
return;
}
cbStyledTextCtrl* control = editor->GetControl();
if (event.GetEventType() == wxEVT_SCI_CHARADDED)
{
// a character was just added in the editor
Manager::Get()->GetLogManager()->DebugLog(_("PyCC: completion check begin"));
wxChar ch = event.GetKey();
int pos = control->GetCurrentPos();
int wordStartPos = control->WordStartPosition(pos, true);
while(control->GetCharAt(wordStartPos-1)==_T('.'))
wordStartPos = control->WordStartPosition(wordStartPos-2, true);
// -2 is used next because the char has already been added and Pos is ahead of it...
const wxChar prevChar = control->GetCharAt(pos - 2);
// if more than two chars have been typed, invoke CC
bool m_CCAutoLaunch = true;
int m_CCAutoLaunchChars = 2;
const bool autoCC = m_CCAutoLaunch && (pos - wordStartPos >= m_CCAutoLaunchChars);
// update calltip highlight while we type
if (control->CallTipActive())
ShowCallTip();
//HOW TO DO CALLTIPS
//FROM CURRENT SCOPE REVERSE FIND FROM CURRENT POS FOR '(', IGNORING COMMENTS, STRINGS, CHAR STYLE
//LOOK FOR MATCHING BRACE, IF FOUND IS THE POSITION AHEAD OF THE CURRENT BRACE? NO, SKIP.
//RETRIEVE THE SYMBOL TO THE LEFT OF THE '(' E.G. 'os.path.exists' <- ACTIVE SYMBOL
//COUNT THE NUMBER OF COMMAS BETWEEN CURRENT POS AND '(' <- ACTIVE ARG
//RETRIEVE THE CALLTIP AND DOC STRING FROM THE PYTHON SERVER
// code completion
if ( (autoCC && !control->AutoCompActive()) // not already active autocompletion
|| (ch == _T('.')))
{
Manager::Get()->GetLogManager()->DebugLog(_("PyCC: Checking lexical state..."));
int style = control->GetStyleAt(pos-2);
if ( ch != _T('.') && style != wxSCI_P_DEFAULT
&& style != wxSCI_P_CLASSNAME
&& style != wxSCI_P_DEFNAME
&& style != wxSCI_P_IDENTIFIER )
{
Manager::Get()->GetLogManager()->DebugLog(_("PyCC: Not a completable lexical state"));
event.Skip();
return;
}
wxString phrase=control->GetTextRange(wordStartPos,pos);
Manager::Get()->GetLogManager()->DebugLog(_T("PyCC: Looking for ")+phrase+_T(" in ")+editor->GetFilename()+wxString::Format(_T(" %i"),pos));
RequestCompletion(control,pos,editor->GetFilename());
event.Skip();
return;
}
// calltip
Manager::Get()->GetLogManager()->DebugLog(_T("PyCC: Checking for calltip"));
pos=control->GetCurrentPos()-1;
int startpos=pos;
int cursorpos = pos+1;
int minpos=control->GetCurrentPos()-1000;
if (minpos<0)
minpos=0;
while(pos>=minpos)
{
wxChar ch = control->GetCharAt(pos);
int style = control->GetStyleAt(pos);
if (control->IsString(style) || control->IsCharacter(style) || control->IsComment(style))
{
pos--;
continue;
}
if(ch==_T(')'))
pos=control->BraceMatch(pos);
else if(ch==_T('('))
break;
pos--;
}
if(pos<minpos || control->BraceMatch(pos)<control->GetCurrentPos() && control->BraceMatch(pos)!=-1)
{
Manager::Get()->GetLogManager()->DebugLog(_T("PyCC: Not in function scope"));
event.Skip();
return;
}
m_ActiveCalltipPos=cursorpos;
Manager::Get()->GetLogManager()->DebugLog(_T("PyCC: Finding the calltip symbol"));
//now find the symbol, if any, associated with the parens
int end_pos=pos;
pos--;
ch = control->GetCharAt(pos);
while(pos>=0)
{
while (ch == _T(' ') || ch == _T('\t'))
{
pos--;
ch = control->GetCharAt(pos);
wxString s=control->GetTextRange(pos,end_pos);
Manager::Get()->GetLogManager()->DebugLog(_T("#")+s);
}
int npos=control->WordStartPosition(pos+1,true);
if(npos==pos+1)
{
event.Skip();
return;
}
pos=npos;
npos--;
wxString s1=control->GetTextRange(pos,end_pos);
Manager::Get()->GetLogManager()->DebugLog(_T("#")+s1);
ch = control->GetCharAt(npos);
while (ch == _T(' ') || ch == _T('\t'))
{
npos--;
ch = control->GetCharAt(npos);
wxString s=control->GetTextRange(npos,end_pos);
Manager::Get()->GetLogManager()->DebugLog(_T("#")+s);
}
if (ch!=_T('.'))
break;
pos=npos-1;
if(pos<0)
{
event.Skip();
return;
}
}
int start_pos=pos;
wxString symbol=control->GetTextRange(start_pos,end_pos);
symbol.Replace(_T(" "),wxEmptyString);
symbol.Replace(_T("\t"),wxEmptyString);
if(symbol==wxEmptyString)
{
event.Skip();
return;
}
m_ActiveSymbol=symbol;
Manager::Get()->GetLogManager()->DebugLog(_T("PyCC: Found calltip symbol ")+symbol);
RequestCallTip(control, cursorpos, editor->GetFilename());
}
// allow others to handle this event
event.Skip();
}
void PythonCodeCompletion::OnClickedGotoDefinition(wxCommandEvent& event)
{
if(!m_libs_loaded)
return;
cbEditor* ed = Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
if(!ed)
return;
cbStyledTextCtrl *control = ed->GetControl();
if(control->GetLexer() != wxSCI_LEX_PYTHON)
return;
int pos = control->GetCurrentPos();
int line = control->LineFromPosition(pos);
int column = pos - control->PositionFromLine(line);
XmlRpc::XmlRpcValue value;
value.setSize(4);
value[0] = ed->GetFilename().utf8_str();
value[1] = control->GetText().utf8_str();
value[2] = line;
value[3] = column;
py_server->ClearJobs();
py_server->ExecAsync(_T("get_definition_location"),value,this,ID_GOTO_DECLARATION);
}
void PythonCodeCompletion::OnGotoDefinition(XmlRpcResponseEvent &event)
{
if(event.GetState()==XMLRPC_STATE_RESPONSE)
{
Manager::Get()->GetLogManager()->DebugLog(_("PyCC: Goto Definition response"));
XmlRpc::XmlRpcValue val=event.GetResponse(); //Should return an array of path, lineno
m_comp_results.Empty();
Manager::Get()->GetLogManager()->DebugLog(wxString::Format(_("PyCC: XML response \n%s"),val.toXml().c_str()));
if(val.getType()==val.TypeArray && val.size()>0)
{
wxString path = wxString(std::string(val[0]).c_str(),wxConvUTF8);
int line = val[1];
wxFileName f(path);
// cbEditor* ed = Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
// if(!ed)
// return;
// f.MakeRelativeTo(ed->GetFilename());
Manager::Get()->GetLogManager()->DebugLog(wxString::Format(_("PyCC: Definition is at %s:%i"),f.GetFullPath().wx_str(),line));
if(f.FileExists())
{
cbEditor* ed = Manager::Get()->GetEditorManager()->Open(f.GetFullPath());
if (ed)
{
ed->Show(true);
ed->GotoLine(line, false);
}
return;
}
Manager::Get()->GetLogManager()->LogWarning(wxString::Format(_("PyCC: Definition could not be opened at %s:%i"),f.GetFullPath().wx_str(),line));
XmlRpc::XmlRpcValue val=event.GetResponse();
Manager::Get()->GetLogManager()->DebugLog(wxString(val.toXml().c_str(),wxConvUTF8));
return;
}
}
else
HandleError(event,_T("PyCC: Bad response for goto definition"));
}