File: XDebugManager.cpp

package info (click to toggle)
codelite 17.0.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 136,204 kB
  • sloc: cpp: 491,547; ansic: 280,393; php: 10,259; sh: 8,930; lisp: 7,664; vhdl: 6,518; python: 6,020; lex: 4,920; yacc: 3,123; perl: 2,385; javascript: 1,715; cs: 1,193; xml: 1,110; makefile: 804; cobol: 741; sql: 709; ruby: 620; f90: 566; ada: 534; asm: 464; fortran: 350; objc: 289; tcl: 258; java: 157; erlang: 61; pascal: 51; ml: 49; awk: 44; haskell: 36
file content (817 lines) | stat: -rw-r--r-- 27,267 bytes parent folder | download | duplicates (3)
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
#include "XDebugManager.h"

#include "PHPDebugStartDlg.h"
#include "XDebugCommThread.h"
#include "XDebugEvalCmdHandler.h"
#include "XDebugUnknownCommand.h"
#include "php.h"
#include "php_configuration_data.h"
#include "php_utils.h"
#include "php_workspace.h"
#include "ssh_workspace_settings.h"

#include <bookmark_manager.h>
#include <event_notifier.h>
#include <file_logger.h>
#include <plugin.h>
#include <wx/msgdlg.h>
#include <wx/richmsgdlg.h>
#include <wx/sckaddr.h>
#include <wx/sstream.h>
#include <wx/stc/stc.h>
#include <wx/uri.h>
#include <xmlutils.h>

// Handlers
#include "XDebugBreakpointCmdHandler.h"
#include "XDebugContextGetCmdHandler.h"
#include "XDebugPropertyGetHandler.h"
#include "XDebugRunCmdHandler.h"
#include "XDebugStackGetCmdHandler.h"
#include "XDebugStopCmdHandler.h"
#include "xdebugevent.h"

#define CHECK_XDEBUG_SESSION_ACTIVE(event) \
    if(!IsConnected()) {                   \
        event.Skip();                      \
        return;                            \
    }

XDebugManager::XDebugManager()
    : TranscationId(0)
    , m_plugin(NULL)
    , m_readerThread(NULL)
    , m_connected(false)
{
    // Connect CodeLite's debugger events to XDebugManager
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_START, &XDebugManager::OnDebugStartOrContinue, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_STOP, &XDebugManager::OnStopDebugger, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_CONTINUE, &XDebugManager::OnDebugStartOrContinue, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_IS_RUNNING, &XDebugManager::OnDebugIsRunning, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_TOGGLE_BREAKPOINT, &XDebugManager::OnToggleBreakpoint, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_NEXT, &XDebugManager::OnDebugNext, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_NEXT_INST, &XDebugManager::OnVoid, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_STEP_IN, &XDebugManager::OnDebugStepIn, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_STEP_I, &XDebugManager::OnVoid, this); // Not supported
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_STEP_OUT, &XDebugManager::OnDebugStepOut, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_EXPR_TOOLTIP, &XDebugManager::OnTooltip, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_CAN_INTERACT, &XDebugManager::OnCanInteract, this);
    EventNotifier::Get()->Bind(wxEVT_XDEBUG_IDE_GOT_CONTROL, &XDebugManager::OnGotFocusFromXDebug, this);
    EventNotifier::Get()->Bind(wxEVT_XDEBUG_STOPPED, &XDebugManager::OnXDebugStopped, this);
    EventNotifier::Get()->Bind(wxEVT_PHP_STACK_TRACE_ITEM_ACTIVATED, &XDebugManager::OnStackTraceItemActivated, this);
    EventNotifier::Get()->Bind(wxEVT_PHP_BREAKPOINT_ITEM_ACTIVATED, &XDebugManager::OnBreakpointItemActivated, this);
    EventNotifier::Get()->Bind(wxEVT_PHP_DELETE_ALL_BREAKPOINTS, &XDebugManager::OnDeleteAllBreakpoints, this);
    EventNotifier::Get()->Bind(wxEVT_PHP_DELETE_BREAKPOINT, &XDebugManager::OnDeleteBreakpoint, this);
    EventNotifier::Get()->Bind(wxEVT_XDEBUG_BREAKPOINTS_UPDATED, &XDebugManager::OnBreakpointsViewUpdated, this);
    EventNotifier::Get()->Bind(wxEVT_XDEBUG_EVAL_EXPRESSION, &XDebugManager::OnShowTooltip, this);
}

XDebugManager::~XDebugManager()
{
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_START, &XDebugManager::OnDebugStartOrContinue, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_STOP, &XDebugManager::OnStopDebugger, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_CONTINUE, &XDebugManager::OnDebugStartOrContinue, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_IS_RUNNING, &XDebugManager::OnDebugIsRunning, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_TOGGLE_BREAKPOINT, &XDebugManager::OnToggleBreakpoint, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_NEXT, &XDebugManager::OnDebugNext, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_NEXT_INST, &XDebugManager::OnVoid, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_STEP_IN, &XDebugManager::OnDebugStepIn, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_STEP_I, &XDebugManager::OnVoid, this); // Not supported
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_STEP_OUT, &XDebugManager::OnDebugStepOut, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_EXPR_TOOLTIP, &XDebugManager::OnTooltip, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_CAN_INTERACT, &XDebugManager::OnCanInteract, this);
    EventNotifier::Get()->Unbind(wxEVT_XDEBUG_IDE_GOT_CONTROL, &XDebugManager::OnGotFocusFromXDebug, this);
    EventNotifier::Get()->Unbind(wxEVT_XDEBUG_STOPPED, &XDebugManager::OnXDebugStopped, this);
    EventNotifier::Get()->Unbind(wxEVT_PHP_STACK_TRACE_ITEM_ACTIVATED, &XDebugManager::OnStackTraceItemActivated, this);
    EventNotifier::Get()->Unbind(wxEVT_PHP_BREAKPOINT_ITEM_ACTIVATED, &XDebugManager::OnBreakpointItemActivated, this);
    EventNotifier::Get()->Unbind(wxEVT_PHP_DELETE_ALL_BREAKPOINTS, &XDebugManager::OnDeleteAllBreakpoints, this);
    EventNotifier::Get()->Unbind(wxEVT_PHP_DELETE_BREAKPOINT, &XDebugManager::OnDeleteBreakpoint, this);
    EventNotifier::Get()->Unbind(wxEVT_XDEBUG_BREAKPOINTS_UPDATED, &XDebugManager::OnBreakpointsViewUpdated, this);
    EventNotifier::Get()->Unbind(wxEVT_XDEBUG_EVAL_EXPRESSION, &XDebugManager::OnShowTooltip, this);
}

void XDebugManager::OnDebugStartOrContinue(clDebugEvent& e)
{
    if(!PHPWorkspace::Get()->IsOpen()) {
        // Call skip so CodeLite will continue to handle this event
        // by passing it to other debuggers
        e.Skip();
        return;
    }

    // This event is ours to handler, don't call e.Skip()

    // a PHP debug session requested to start
    if(!m_readerThread) {
        // No reader thread is up, start on
        // starting the debugger
        e.SetFeatures(0); // No special features by the PHP debugger
        DoStartDebugger();

    } else {
        // The debugger is already running - issue a 'Continue' command
        DoContinue();
    }
}

void XDebugManager::DoStartDebugger(bool ideInitiate)
{
    CHECK_COND_RET(PHPWorkspace::Get()->GetActiveProject());

    // Test which file we want to debug
    PHPDebugStartDlg debugDlg(EventNotifier::Get()->TopFrame(), PHPWorkspace::Get()->GetActiveProject(),
                              m_plugin->GetManager());
    if(ideInitiate) {
        if(debugDlg.ShowModal() != wxID_OK) {
            return;
        }
    }
    wxDELETE(m_readerThread);
    m_readerThread = new XDebugComThread(this, GetPort(), GetHost(), ideInitiate ? 5 : -1);
    m_readerThread->Start();

    // Starting event
    XDebugEvent eventStarting(wxEVT_XDEBUG_SESSION_STARTING);
    EventNotifier::Get()->ProcessEvent(eventStarting);

    PHPConfigurationData conf;
    conf.Load();
    if(!conf.HasFlag(PHPConfigurationData::kDontPromptForMissingFileMapping) &&
       GetFileMapping(PHPWorkspace::Get()->GetActiveProject()).empty()) {
        // Issue a warning
        wxString message;
        message << _("This project has no file mapping defined. This may result in breakpoints not applied\n")
                << _("To fix this, set file mapping from Project Settings -> Debug");

        wxRichMessageDialog dlg(EventNotifier::Get()->TopFrame(), message, "CodeLite",
                                wxICON_WARNING | wxOK | wxOK_DEFAULT | wxCANCEL);
        dlg.ShowCheckBox(_("Remember my answer and don't show this message again"));
        dlg.SetOKCancelLabels(_("OK, Continue to Debug"), _("Stop the debugger"));
        int dlgResult = dlg.ShowModal();
        conf.EnableFlag(PHPConfigurationData::kDontPromptForMissingFileMapping, dlg.IsCheckBoxChecked()).Save();
        if(dlgResult == wxID_CANCEL) {
            // Stop the debugger
            DoStopDebugger();
            return;
        }
    }

    if(ideInitiate) {
        // Now we can run the project
        if(!PHPWorkspace::Get()->RunProject(true, debugDlg.GetPath(), "", conf.GetXdebugIdeKey())) {
            DoStopDebugger();
            return;
        }
    }
    // Notify about debug session started
    XDebugEvent eventStart(wxEVT_XDEBUG_SESSION_STARTED);
    EventNotifier::Get()->AddPendingEvent(eventStart);

    // Fire CodeLite IDE event indicating that a debug session started
    clDebugEvent cl_event(wxEVT_DEBUG_STARTED);
    cl_event.SetDebuggerName("xdebug-php");
    EventNotifier::Get()->AddPendingEvent(cl_event);
}

void XDebugManager::OnSocketInput(const std::string& reply) { ProcessDebuggerMessage(reply); }

void XDebugManager::OnDebugIsRunning(clDebugEvent& e)
{
    if(PHPWorkspace::Get()->IsOpen()) {
        e.SetAnswer((m_readerThread != nullptr));
    } else {
        // Not ours to handle
        e.Skip();
    }
}

void XDebugManager::OnStopDebugger(clDebugEvent& e)
{
    if(m_readerThread) {
        // abort
        wxDELETE(m_readerThread);

    } else {
        e.Skip();
    }
}

void XDebugManager::DoStopDebugger()
{
    ClearDebuggerMarker();
    m_connected = false;

    // Clear all handlers from the queue
    m_handlers.clear();

    // Save the breakpoints

    // Reset the connection
    clDEBUG() << "CodeLite >>> closing debug session" << endl;
    wxDELETE(m_readerThread);

    // Notify about debug session ended
    XDebugEvent eventEnd(wxEVT_XDEBUG_SESSION_ENDED);
    EventNotifier::Get()->AddPendingEvent(eventEnd);

    {
        clDebugEvent e(wxEVT_DEBUG_ENDED);
        EventNotifier::Get()->AddPendingEvent(e);
    }
}

bool XDebugManager::ProcessDebuggerMessage(const wxString& buffer)
{
    if(buffer.IsEmpty())
        return false;

    clDEBUG() << "XDebug <<< " << buffer << endl;

    wxXmlDocument doc;
    wxStringInputStream sis(buffer);
    if(!doc.Load(sis)) {
        // failed to parse XML
        clDEBUG() << "CodeLite >>> invalid XML!" << endl;
        return false;
    }

    wxXmlNode* root = doc.GetRoot();

    if(root->GetName() == "init") {

        // Parse the content and notify codelite to open the main file
        xInitStruct initData = ParseInitXML(root);

        // Negotiate features with the IDE
        DoNegotiateFeatures();

        // this is a startup message from the debugger
        DoApplyBreakpoints();

        // Issue a "Continue" command
        DoContinue();

    } else if(root->GetName() == "response") {
        // Handle response
        DoHandleResponse(root);
    }
    return true;
}

void XDebugManager::DoApplyBreakpoints()
{
    clDEBUG() << "CodeLite >>> Applying breakpoints" << endl;
    if(!m_readerThread) {
        clDEBUG() << "CodeLite (PHP): No XDebug reader thread?" << endl;
        return;
    }

    PHPProject::Ptr_t pProject = PHPWorkspace::Get()->GetActiveProject();
    if(!pProject) {
        clDEBUG() << "CodeLite (PHP): No active project!" << endl;
        return;
    }

    const PHPProjectSettingsData& settings = pProject->GetSettings();
    // bool bRunAsWebserver = (pProject->GetSettings().GetRunAs() == PHPProjectSettingsData::kRunAsWebsite);

    XDebugBreakpoint::List_t& breakpoints = m_breakpointsMgr.GetBreakpoints();
    if(breakpoints.empty()) {
        clDEBUG() << "CodeLite (PHP): No breakpoints to apply" << endl;
        return;
    }

    for(auto& bp : breakpoints) {
        // apply only breakpoints without xdebug-id attached to them
        if(bp.IsApplied()) {
            clDEBUG() << "CodeLite (PHP): Breakpoint already applied" << endl;
            continue;
        }

        wxStringMap_t sftpMapping;
        SSHWorkspaceSettings sftpSettings;
        sftpSettings.Load();
        if(!sftpSettings.GetRemoteFolder().IsEmpty() && sftpSettings.IsRemoteUploadEnabled()) {
            sftpMapping.insert({ PHPWorkspace::Get()->GetFilename().GetPath(), sftpSettings.GetRemoteFolder() });
        }

        wxString command;
        XDebugCommandHandler::Ptr_t handler(new XDebugBreakpointCmdHandler(this, ++TranscationId, bp));
        wxString filepath = settings.GetMappdPath(bp.GetFileName(), true, sftpMapping);
        command << "breakpoint_set -t line -f " << filepath << " -n " << bp.GetLine() << " -i "
                << handler->GetTransactionId();
        DoSocketWrite(command);
        AddHandler(handler);
    }
}

void XDebugManager::DoContinue()
{
    CHECK_PTR_RET(m_readerThread);
    SendRunCommand();
}

void XDebugManager::DoHandleResponse(wxXmlNode* xml)
{
    CHECK_PTR_RET(xml);

    wxString txId = xml->GetAttribute("transaction_id");
    long nTxId(0);
    txId.ToCLong(&nTxId);
    XDebugCommandHandler::Ptr_t handler = PopHandler(nTxId);
    if(handler) {
        handler->Process(xml);

    } else {

        // Just log the reply
        wxXmlDocument doc;
        doc.SetRoot(xml);

        wxStringOutputStream sos;
        if(doc.Save(sos)) {
            clDEBUG() << sos.GetString() << endl;
        }
        doc.DetachRoot();
    }
}

void XDebugManager::DoSocketWrite(const wxString& command)
{
    CHECK_PTR_RET(m_readerThread);
    m_readerThread->SendMsg(command);
}

xInitStruct XDebugManager::ParseInitXML(wxXmlNode* init)
{
    xInitStruct initData;
    wxURI fileuri(init->GetAttribute("fileuri"));
    initData.filename = fileuri.BuildUnescapedURI();
    return initData;
}

void XDebugManager::AddHandler(XDebugCommandHandler::Ptr_t handler)
{
    if(m_handlers.count(handler->GetTransactionId())) {
        m_handlers.erase(handler->GetTransactionId());
    }
    m_handlers.insert(std::make_pair(handler->GetTransactionId(), handler));
}

XDebugCommandHandler::Ptr_t XDebugManager::PopHandler(int transcationId)
{
    XDebugCommandHandler::Ptr_t handler(NULL);
    if(m_handlers.count(transcationId)) {
        handler = m_handlers[transcationId];
        m_handlers.erase(transcationId);
    }
    return handler;
}

void XDebugManager::SendRunCommand()
{
    CHECK_PTR_RET(m_readerThread);
    wxString command;
    XDebugCommandHandler::Ptr_t handler(new XDebugRunCmdHandler(this, ++TranscationId));
    command << "run -i " << handler->GetTransactionId();
    DoSocketWrite(command);
    AddHandler(handler);
}

void XDebugManager::SendStopCommand()
{
    CHECK_PTR_RET(m_readerThread);
    wxString command;
    XDebugCommandHandler::Ptr_t handler(new XDebugStopCmdHandler(this, ++TranscationId));
    command << "stop -i " << handler->GetTransactionId();
    DoSocketWrite(command);
    AddHandler(handler);
}

void XDebugManager::OnToggleBreakpoint(clDebugEvent& e)
{
    if(!PHPWorkspace::Get()->IsOpen()) {
        e.Skip();
        return;
    }

    // User toggled a breakpoint
    IEditor* editor = m_plugin->GetManager()->GetActiveEditor();
    if(editor && editor->GetFileName().GetFullPath() == e.GetFileName()) {
        // Correct editor
        // add marker
        if(m_breakpointsMgr.HasBreakpoint(e.GetFileName(), e.GetInt())) {

            XDebugBreakpoint bp;
            m_breakpointsMgr.GetBreakpoint(e.GetFileName(), e.GetInt(), bp);
            if(bp.IsApplied() && m_readerThread) {
                // Remove it from XDebug as well
                DoDeleteBreakpoint(bp.GetBreakpointId());
            }
            m_breakpointsMgr.DeleteBreakpoint(e.GetFileName(), e.GetInt());

        } else {
            m_breakpointsMgr.AddBreakpoint(e.GetFileName(), e.GetInt());
            DoApplyBreakpoints();
        }
        DoRefreshBreakpointsMarkersForEditor(editor);
    }
}

void XDebugManager::ClearDebuggerMarker()
{
    IEditor::List_t editors;
    m_plugin->GetManager()->GetAllEditors(editors);
    IEditor::List_t::iterator iter = editors.begin();
    for(; iter != editors.end(); ++iter) {
        (*iter)->GetCtrl()->MarkerDeleteAll(smt_indicator);
    }
}

void XDebugManager::SetDebuggerMarker(wxStyledTextCtrl* stc, int lineno)
{
    stc->MarkerDeleteAll(smt_indicator);
    stc->MarkerAdd(lineno, smt_indicator);
    int caretPos = stc->PositionFromLine(lineno);
    stc->SetSelection(caretPos, caretPos);
    stc->SetCurrentPos(caretPos);
    stc->EnsureCaretVisible();
    CenterEditor(stc, lineno);
}

void XDebugManager::OnGotFocusFromXDebug(XDebugEvent& e)
{
    e.Skip();

    // Make sure codelite is "Raised"
    wxFrame* frame = EventNotifier::Get()->TopFrame();
    if(frame->IsIconized() || !frame->IsShown()) {
        frame->Raise();
    }

    clDEBUG() << "CodeLite: opening file:" << e.GetFileName() << ":" << (e.GetLineNumber() + 1)
              << endl; // The user sees the line number from 1 (while scintilla counts them from 0)

    // Mark the debugger line / file
    IEditor* editor = m_plugin->GetManager()->FindEditor(e.GetFileName());
    if(!editor && wxFileName::Exists(e.GetFileName())) {
        // Try to open the editor
        if(m_plugin->GetManager()->OpenFile(e.GetFileName(), "", e.GetLineNumber())) {
            editor = m_plugin->GetManager()->GetActiveEditor();
        }
    }

    if(editor) {
        m_plugin->GetManager()->SelectPage(editor->GetCtrl());
        CallAfter(&XDebugManager::SetDebuggerMarker, editor->GetCtrl(), e.GetLineNumber());
    }

    // Update the callstack/locals views
    DoRefreshDebuggerViews();

    // Re-apply any new breakpoints
    DoApplyBreakpoints();
}

void XDebugManager::OnDebugNext(clDebugEvent& e)
{
    CHECK_XDEBUG_SESSION_ACTIVE(e);
    wxString command;
    XDebugCommandHandler::Ptr_t handler(new XDebugRunCmdHandler(this, ++TranscationId));
    command << "step_over -i " << handler->GetTransactionId();
    DoSocketWrite(command);
    AddHandler(handler);
}

void XDebugManager::OnDebugStepIn(clDebugEvent& e)
{
    CHECK_XDEBUG_SESSION_ACTIVE(e);
    wxString command;
    XDebugCommandHandler::Ptr_t handler(new XDebugRunCmdHandler(this, ++TranscationId));
    command << "step_into -i " << handler->GetTransactionId();
    DoSocketWrite(command);
    AddHandler(handler);
}

void XDebugManager::OnDebugStepOut(clDebugEvent& e)
{
    CHECK_XDEBUG_SESSION_ACTIVE(e);
    wxString command;
    XDebugCommandHandler::Ptr_t handler(new XDebugRunCmdHandler(this, ++TranscationId));
    command << "step_out -i " << handler->GetTransactionId();
    DoSocketWrite(command);
    AddHandler(handler);
}

void XDebugManager::OnVoid(clDebugEvent& e)
{
    CHECK_XDEBUG_SESSION_ACTIVE(e);
    // do nothing
}

void XDebugManager::OnXDebugStopped(XDebugEvent& e)
{
    e.Skip();
    DoStopDebugger();
}

void XDebugManager::DoRefreshDebuggerViews(int requestedStack)
{
    if(!m_readerThread) {
        return;
    }

    // We execute here 2 commands in a row
    {
        wxString command;
        XDebugCommandHandler::Ptr_t handler(new XDebugStackGetCmdHandler(this, ++TranscationId, requestedStack));

        // Get the current stack frames
        command << "stack_get -i " << handler->GetTransactionId();
        DoSocketWrite(command);
        AddHandler(handler);
    }

    {
        wxString command;
        // Get the 'Locals' view
        XDebugCommandHandler::Ptr_t handler(new XDebugContextGetCmdHandler(this, ++TranscationId, requestedStack));
        command << "context_get -d " << requestedStack << " -i " << handler->GetTransactionId();
        DoSocketWrite(command);
        AddHandler(handler);
    }

    // FIXME :: Refresh any watches we have
    // Locals are updated automatically
}

static XDebugManager* s_xdebugManager = NULL;
XDebugManager& XDebugManager::Get()
{
    if(!s_xdebugManager) {
        s_xdebugManager = new XDebugManager();
    }
    return *s_xdebugManager;
}

void XDebugManager::Initialize(PhpPlugin* plugin) { Get().m_plugin = plugin; }

int XDebugManager::GetPort() const
{
    PHPConfigurationData phpGlobalSettings;
    phpGlobalSettings.Load();
    return phpGlobalSettings.GetXdebugPort();
}

wxString XDebugManager::GetHost() const
{
    PHPConfigurationData phpGlobalSettings;
    phpGlobalSettings.Load();
    return phpGlobalSettings.GetXdebugHost();
}

void XDebugManager::Free() { wxDELETE(s_xdebugManager); }

void XDebugManager::DoDeleteBreakpoint(int bpid)
{
    wxString command;
    // Get the 'Locals' view
    command << "breakpoint_remove -i " << ++TranscationId << " -d " << bpid;
    DoSocketWrite(command);
}

void XDebugManager::OnStackTraceItemActivated(PHPEvent& e)
{
    e.Skip();
    wxString filename = e.GetFileName();
    int line = e.GetLineNumber();
    int depth = e.GetInt();

    if(!m_plugin->GetManager()->OpenFile(filename, "", line - 1)) {
        ::wxMessageBox(_("Could not open file: ") + filename, "CodeLite", wxICON_WARNING | wxOK | wxCENTER);
    }
    DoRefreshDebuggerViews(depth);
}

wxStringMap_t XDebugManager::GetFileMapping(PHPProject::Ptr_t pProject) const
{
    wxASSERT(pProject);
    wxStringMap_t mappings;
    const PHPProjectSettingsData& settings = pProject->GetSettings();
    mappings = settings.GetFileMapping();

    // Add the SFTP mappings
    SSHWorkspaceSettings sftpSettings;
    sftpSettings.Load();
    if(!sftpSettings.GetRemoteFolder().IsEmpty() && sftpSettings.IsRemoteUploadEnabled()) {
        mappings.insert(std::make_pair(PHPWorkspace::Get()->GetFilename().GetPath(), sftpSettings.GetRemoteFolder()));
    }
    return mappings;
}

void XDebugManager::OnDeleteAllBreakpoints(PHPEvent& e)
{
    e.Skip();

    // Delete them from XDebug
    const XDebugBreakpoint::List_t& bps = m_breakpointsMgr.GetBreakpoints();
    XDebugBreakpoint::List_t::const_iterator iter = bps.begin();
    for(; iter != bps.end(); ++iter) {
        if(iter->IsApplied()) {
            DoDeleteBreakpoint(iter->GetBreakpointId());
        }
    }

    // Delete them from the manager
    m_breakpointsMgr.DeleteAllBreakpoints();
}

void XDebugManager::OnDeleteBreakpoint(PHPEvent& e)
{
    e.Skip();
    wxString filename = e.GetFileName();
    int line = e.GetLineNumber();
    int bpid = e.GetInt();

    if(bpid != wxNOT_FOUND) {
        // breakpoint was applied
        DoDeleteBreakpoint(bpid);
    }
    IEditor* editor = m_plugin->GetManager()->FindEditor(filename);
    if(editor) {
        editor->GetCtrl()->MarkerDelete(line - 1, smt_breakpoint);
    }
    m_breakpointsMgr.DeleteBreakpoint(filename, line);
}

bool XDebugManager::IsDebugSessionRunning() const { return PHPWorkspace::Get()->IsOpen() && (m_readerThread != NULL); }

void XDebugManager::OnBreakpointItemActivated(PHPEvent& e)
{
    e.Skip();
    if(!m_plugin->GetManager()->OpenFile(e.GetFileName(), "", e.GetLineNumber() - 1)) {
        ::wxMessageBox(_("Could not open file: ") + e.GetFileName(), "CodeLite", wxICON_WARNING | wxOK | wxCENTER);
    }
}

void XDebugManager::OnBreakpointsViewUpdated(XDebugEvent& e)
{
    e.Skip();
    IEditor::List_t editors;
    m_plugin->GetManager()->GetAllEditors(editors, true);
    IEditor::List_t::iterator iter = editors.begin();
    for(; iter != editors.end(); ++iter) {
        DoRefreshBreakpointsMarkersForEditor(*iter);
    }
}

void XDebugManager::DoRefreshBreakpointsMarkersForEditor(IEditor* editor)
{
    CHECK_PTR_RET(editor);
    editor->GetCtrl()->MarkerDeleteAll(smt_breakpoint);

    XDebugBreakpoint::List_t bps;
    m_breakpointsMgr.GetBreakpointsForFile(editor->GetFileName().GetFullPath(), bps);
    XDebugBreakpoint::List_t::const_iterator iter = bps.begin();
    for(; iter != bps.end(); ++iter) {
        editor->GetCtrl()->MarkerAdd(iter->GetLine() - 1, smt_breakpoint);
    }
}

void XDebugManager::DoNegotiateFeatures()
{
    CHECK_PTR_RET(m_readerThread);

    // Set the max children returned by XDebug to 1
    // this is done for performance reasons
    wxString command;

    command.Clear();
    command << "feature_set -n max_depth -v 1 -i " << ++TranscationId;
    DoSocketWrite(command);

    command.Clear();
    command << "feature_set -n max_children -v 1024 -i " << ++TranscationId;
    DoSocketWrite(command);
}

void XDebugManager::SendEvalCommand(const wxString& expression, int evalPurpose)
{
    CHECK_PTR_RET(m_readerThread);

    wxString command;
    XDebugCommandHandler::Ptr_t handler(new XDebugEvalCmdHandler(expression, evalPurpose, this, ++TranscationId));
    command << "eval -i " << handler->GetTransactionId() << " -- " << ::Base64Encode(expression);
    DoSocketWrite(command);
    AddHandler(handler);
}

void XDebugManager::OnTooltip(clDebugEvent& e)
{
    CHECK_XDEBUG_SESSION_ACTIVE(e);

    wxString expression = e.GetString();
    if(expression.IsEmpty())
        return;

    expression.Prepend("print_r(").Append(", true)");
    SendEvalCommand(expression, XDebugEvalCmdHandler::kEvalForTooltip);
}

void XDebugManager::OnCanInteract(clDebugEvent& e)
{
    CHECK_XDEBUG_SESSION_ACTIVE(e);
    e.SetAnswer(true); // Otherwise we would never reach this (see the definition of CHECK_XDEBUG_SESSION_ACTIVE macro)
}

void XDebugManager::CloseDebugSession() { DoStopDebugger(); }

void XDebugManager::OnCommThreadTerminated()
{
    clDEBUG() << "CodeLite >>> Comm Thread: session with XDebug is terminated!" << endl;
    DoStopDebugger();
}

void XDebugManager::XDebugNotConnecting()
{
    wxRichMessageDialog dlg(EventNotifier::Get()->TopFrame(), _("XDebug did not connect in a timely manner"),
                            "CodeLite", wxICON_WARNING | wxOK | wxCANCEL_DEFAULT | wxCANCEL);
    dlg.SetOKCancelLabels(_("Run XDebug Test"), _("OK"));
    if(dlg.ShowModal() == wxID_OK) {
        m_plugin->CallAfter(&PhpPlugin::RunXDebugDiagnostics);
    }
    DoStopDebugger();
}

void XDebugManager::OnShowTooltip(XDebugEvent& e)
{
    if(e.GetEvalReason() == XDebugEvalCmdHandler::kEvalForTooltip) {
        wxString tip, title;
        title << e.GetString();

        if(!e.IsEvalSucceeded()) {
            tip << _("Error evaluating expression ");
        } else {
            wxString evaluated = e.GetEvaluted();
            // Reomve extra escapes
            evaluated.Replace("\\n", "\n");
            evaluated.Replace("\\t", "\t");
            evaluated.Replace("\\r", "\r");
            evaluated.Replace("\\v", "\v");
            evaluated.Replace("\\b", "\b");
            tip << evaluated;
            tip.Trim();
        }
        m_plugin->GetManager()->GetActiveEditor()->ShowRichTooltip(tip, title, wxNOT_FOUND);
    } else {
        e.Skip();
    }
}

void XDebugManager::SendDBGPCommand(const wxString& cmd)
{
    CHECK_PTR_RET(m_readerThread);

    wxString command;
    XDebugCommandHandler::Ptr_t handler(new XDebugUnknownCommand(this, ++TranscationId));
    command << cmd << " -i " << handler->GetTransactionId();
    DoSocketWrite(command);
    AddHandler(handler);
}

void XDebugManager::SendGetProperty(const wxString& propertyName)
{
    CHECK_PTR_RET(m_readerThread);

    wxString command;
    XDebugCommandHandler::Ptr_t handler(new XDebugPropertyGetHandler(this, ++TranscationId, propertyName));
    command << "property_get -n " << propertyName << " -i " << handler->GetTransactionId();
    DoSocketWrite(command);
    AddHandler(handler);
}

void XDebugManager::SetConnected(bool connected)
{
    this->m_connected = connected;
    XDebugEvent event(wxEVT_XDEBUG_CONNECTED);
    EventNotifier::Get()->AddPendingEvent(event);
}

void XDebugManager::CenterEditor(wxStyledTextCtrl* ctrl, int lineNo)
{
    // Place the debugger line at the center of the editor view
    int linesOnScreen = ctrl->LinesOnScreen();
    int topLine = lineNo - (linesOnScreen / 2);
    ctrl->SetFirstVisibleLine(topLine);
}

void XDebugManager::StartListener()
{
    if(m_readerThread) {
        // Stop the current session
        DoStopDebugger();
    }

    // Start the listener
    DoStartDebugger(false);
}