File: NodeJSDebugger.cpp

package info (click to toggle)
codelite 10.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 71,364 kB
  • sloc: cpp: 415,397; ansic: 18,277; php: 9,547; lex: 4,181; yacc: 2,820; python: 2,294; sh: 383; makefile: 51; xml: 13
file content (712 lines) | stat: -rw-r--r-- 23,259 bytes parent folder | download
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
#include "NodeJSDebugger.h"
#include "event_notifier.h"
#include "codelite_events.h"
#include "macros.h"
#include "NoteJSWorkspace.h"
#include <wx/msgdlg.h>
#include "asyncprocess.h"
#include "NodeJSDebuggerDlg.h"
#include "processreaderthread.h"
#include "file_logger.h"
#include "globals.h"
#include "imanager.h"
#include "ieditor.h"
#include "NodeJSSetBreakpointHandler.h"
#include <algorithm>
#include "NodeJSContinueHandler.h"
#include "NodeJSCallstackHandler.h"
#include "NodeJSSelectFrameHandler.h"
#include "NodeJSGetScriptHandler.h"
#include "NodeJSEvents.h"
#include "bookmark_manager.h"
#include "NodeJSWorkspaceUserConfiguration.h"
#include <wx/log.h>
#include "NodeJSEvaluateExprHandler.h"
#include "NodeJSLookupHandler.h"
#include "NodeJSDebuggerTooltip.h"
#include <signal.h>
#include <algorithm>

#define CHECK_RUNNING() \
    if(!IsConnected()) return

NodeJSDebugger::NodeJSDebugger()
    : m_canInteract(false)
    , m_tooltip(NULL)
{
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_START, &NodeJSDebugger::OnDebugStart, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_CONTINUE, &NodeJSDebugger::OnDebugContinue, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_STOP, &NodeJSDebugger::OnStopDebugger, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_IS_RUNNING, &NodeJSDebugger::OnDebugIsRunning, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_TOGGLE_BREAKPOINT, &NodeJSDebugger::OnToggleBreakpoint, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_NEXT, &NodeJSDebugger::OnDebugNext, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_NEXT_INST, &NodeJSDebugger::OnVoid, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_STEP_IN, &NodeJSDebugger::OnDebugStepIn, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_STEP_OUT, &NodeJSDebugger::OnDebugStepOut, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_EXPR_TOOLTIP, &NodeJSDebugger::OnTooltip, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_CAN_INTERACT, &NodeJSDebugger::OnCanInteract, this);
    EventNotifier::Get()->Bind(wxEVT_DBG_UI_ATTACH_TO_PROCESS, &NodeJSDebugger::OnAttach, this);

    EventNotifier::Get()->Bind(wxEVT_WORKSPACE_LOADED, &NodeJSDebugger::OnWorkspaceOpened, this);
    EventNotifier::Get()->Bind(wxEVT_WORKSPACE_CLOSED, &NodeJSDebugger::OnWorkspaceClosed, this);
    EventNotifier::Get()->Bind(wxEVT_NODEJS_DEBUGGER_MARK_LINE, &NodeJSDebugger::OnHighlightLine, this);
    EventNotifier::Get()->Bind(wxEVT_NODEJS_DEBUGGER_EVAL_EXPRESSION, &NodeJSDebugger::OnEvalExpression, this);

    EventNotifier::Get()->Bind(wxEVT_ACTIVE_EDITOR_CHANGED, &NodeJSDebugger::OnEditorChanged, this);

    Bind(wxEVT_TOOLTIP_DESTROY, &NodeJSDebugger::OnDestroyTip, this);
    m_node.Bind(wxEVT_TERMINAL_COMMAND_EXIT, &NodeJSDebugger::OnNodeTerminated, this);
    m_node.Bind(wxEVT_TERMINAL_COMMAND_OUTPUT, &NodeJSDebugger::OnNodeOutput, this);
}

NodeJSDebugger::~NodeJSDebugger()
{
    m_socket.Reset(NULL);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_START, &NodeJSDebugger::OnDebugStart, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_CONTINUE, &NodeJSDebugger::OnDebugContinue, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_STOP, &NodeJSDebugger::OnStopDebugger, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_IS_RUNNING, &NodeJSDebugger::OnDebugIsRunning, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_TOGGLE_BREAKPOINT, &NodeJSDebugger::OnToggleBreakpoint, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_NEXT, &NodeJSDebugger::OnDebugNext, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_NEXT_INST, &NodeJSDebugger::OnVoid, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_STEP_IN, &NodeJSDebugger::OnDebugStepIn, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_STEP_OUT, &NodeJSDebugger::OnDebugStepOut, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_EXPR_TOOLTIP, &NodeJSDebugger::OnTooltip, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_CAN_INTERACT, &NodeJSDebugger::OnCanInteract, this);
    EventNotifier::Get()->Unbind(wxEVT_DBG_UI_ATTACH_TO_PROCESS, &NodeJSDebugger::OnAttach, this);

    EventNotifier::Get()->Unbind(wxEVT_WORKSPACE_LOADED, &NodeJSDebugger::OnWorkspaceOpened, this);
    EventNotifier::Get()->Unbind(wxEVT_WORKSPACE_CLOSED, &NodeJSDebugger::OnWorkspaceClosed, this);
    EventNotifier::Get()->Unbind(wxEVT_NODEJS_DEBUGGER_MARK_LINE, &NodeJSDebugger::OnHighlightLine, this);
    EventNotifier::Get()->Unbind(wxEVT_NODEJS_DEBUGGER_EVAL_EXPRESSION, &NodeJSDebugger::OnEvalExpression, this);
    EventNotifier::Get()->Unbind(wxEVT_ACTIVE_EDITOR_CHANGED, &NodeJSDebugger::OnEditorChanged, this);

    m_node.Unbind(wxEVT_TERMINAL_COMMAND_EXIT, &NodeJSDebugger::OnNodeTerminated, this);
    m_node.Unbind(wxEVT_TERMINAL_COMMAND_OUTPUT, &NodeJSDebugger::OnNodeOutput, this);
    Unbind(wxEVT_TOOLTIP_DESTROY, &NodeJSDebugger::OnDestroyTip, this);

    m_node.Terminate();

    m_bptManager.Save();
    DoDeleteTempFiles(m_tempFiles);
    m_tempFiles.clear();

    if(m_tooltip) {
        m_tooltip->Destroy();
        m_tooltip = NULL;
    }

    // fire stop event (needed to reload the normal layout)
    clDebugEvent event(wxEVT_NODEJS_DEBUGGER_STOPPED);
    EventNotifier::Get()->AddPendingEvent(event);

    // Clear all markers
    IEditor::List_t editors;
    clGetManager()->GetAllEditors(editors);
    std::for_each(editors.begin(), editors.end(), [&](IEditor* e) { e->DelAllCompilerMarkers(); });
}

void NodeJSDebugger::OnCanInteract(clDebugEvent& event)
{
    event.Skip();
    CHECK_RUNNING();
    event.Skip(false);
    event.SetAnswer(IsCanInteract());
}

void NodeJSDebugger::OnDebugContinue(clDebugEvent& event)
{
    event.Skip();
    CHECK_RUNNING();
    event.Skip(false);
    Continue();
}

void NodeJSDebugger::OnDebugIsRunning(clDebugEvent& event)
{
    if(m_socket && m_socket->IsConnected()) {
        event.SetAnswer(true);

    } else {
        event.Skip();
    }
}

void NodeJSDebugger::OnDebugNext(clDebugEvent& event)
{
    event.Skip();
    CHECK_RUNNING();

    event.Skip(false);
    // Build the request
    JSONElement request = JSONElement::createObject();
    request.addProperty("type", "request");
    request.addProperty("command", "continue");
    JSONElement args = JSONElement::createObject("arguments");
    request.append(args);
    args.addProperty("stepaction", "next");
    args.addProperty("stepcount", 1); // how we tell nodejs to continue until next bp is hit?

    // Write the command
    m_socket->WriteRequest(request, new NodeJSContinueHandler());
}

void NodeJSDebugger::OnDebugStart(clDebugEvent& event)
{
    event.Skip();
    CHECK_COND_RET(NodeJSWorkspace::Get()->IsOpen());
    
    event.SetFeatures(0); // No special features by the NodeJS debugger
    
    // Our to handle
    event.Skip(false);
    if(m_socket && m_socket->IsConnected()) {
        Continue();
        return;
    };

    NodeJSDebuggerDlg dlg(EventNotifier::Get()->TopFrame(), NodeJSDebuggerDlg::kDebug);
    if(dlg.ShowModal() != wxID_OK) {
        return;
    }

    StartDebugger(dlg.GetCommand(), dlg.GetWorkingDirectory());
}

void NodeJSDebugger::OnDebugStepIn(clDebugEvent& event)
{
    event.Skip();
    CHECK_RUNNING();

    event.Skip(false);
    // Build the request
    JSONElement request = JSONElement::createObject();
    request.addProperty("type", "request");
    request.addProperty("command", "continue");
    JSONElement args = JSONElement::createObject("arguments");
    request.append(args);
    args.addProperty("stepaction", "in");
    args.addProperty("stepcount", 1); // how we tell nodejs to continue until next bp is hit?

    // Write the command
    m_socket->WriteRequest(request, new NodeJSContinueHandler());
}

void NodeJSDebugger::OnDebugStepOut(clDebugEvent& event)
{
    event.Skip();
    CHECK_RUNNING();

    event.Skip(false);
    // Build the request
    JSONElement request = JSONElement::createObject();
    request.addProperty("type", "request");
    request.addProperty("command", "continue");
    JSONElement args = JSONElement::createObject("arguments");
    request.append(args);
    args.addProperty("stepaction", "out");
    args.addProperty("stepcount", 1); // how we tell nodejs to continue until next bp is hit?

    // Write the command
    m_socket->WriteRequest(request, new NodeJSContinueHandler());
}

void NodeJSDebugger::OnStopDebugger(clDebugEvent& event)
{
    event.Skip();
    CHECK_RUNNING();

    event.Skip(false);
    m_node.Terminate();
#if defined(__WXGTK__) || defined(__WXOSX__)
    ConnectionLost("Debug session stopped");
#endif
}

void NodeJSDebugger::OnToggleBreakpoint(clDebugEvent& event)
{
    event.Skip();
    if(NodeJSWorkspace::Get()->IsOpen()) {
        event.Skip(false);
        IEditor* editor = clGetManager()->GetActiveEditor();
        if(editor && (editor->GetFileName().GetFullPath() == event.GetFileName())) {
            // Correct editor
            // add marker
            NodeJSBreakpoint bp = m_bptManager.GetBreakpoint(event.GetFileName(), event.GetInt());
            if(bp.IsOk()) {
                if(bp.IsApplied() && IsConnected()) {
                    // Tell NodeJS to delete this breakpoint
                    DeleteBreakpoint(bp);
                }
                m_bptManager.DeleteBreakpoint(event.GetFileName(), event.GetInt());
            } else {
                // We have no breakpoint on this file/line (yet)
                m_bptManager.AddBreakpoint(event.GetFileName(), event.GetInt());
                bp = m_bptManager.GetBreakpoint(event.GetFileName(), event.GetInt());
                if(IsConnected()) {
                    SetBreakpoint(bp);
                }
            }

            // Update the UI
            m_bptManager.SetBreakpoints(editor);
            clDebugEvent event(wxEVT_NODEJS_DEBUGGER_UPDATE_BREAKPOINTS_VIEW);
            EventNotifier::Get()->AddPendingEvent(event);
        }
    }
}

void NodeJSDebugger::OnTooltip(clDebugEvent& event)
{
    event.Skip();
    CHECK_RUNNING();
    event.Skip(false);

    CHECK_PTR_RET(clGetManager()->GetActiveEditor());

    wxString selection = event.GetString();
    CHECK_COND_RET(!selection.IsEmpty());

    // Build the request
    JSONElement request = JSONElement::createObject();
    request.addProperty("type", "request");
    request.addProperty("command", "evaluate");
    JSONElement args = JSONElement::createObject("arguments");
    request.append(args);
    args.addProperty("expression", selection);

    // Write the command
    m_socket->WriteRequest(request, new NodeJSEvaluateExprHandler(selection));
}

void NodeJSDebugger::OnVoid(clDebugEvent& event)
{
    event.Skip();
    CHECK_RUNNING();
    event.Skip(false);
    wxUnusedVar(event);
}

bool NodeJSDebugger::IsConnected() { return m_socket && m_socket->IsConnected(); }

void NodeJSDebugger::ConnectionEstablished()
{
    clDebugEvent eventStart(wxEVT_NODEJS_DEBUGGER_STARTED);
    eventStart.SetDebuggerName("Node.js");
    EventNotifier::Get()->AddPendingEvent(eventStart);
}

void NodeJSDebugger::ConnectionLost(const wxString& errmsg)
{
    CL_DEBUG(errmsg);
#ifdef __WXGTK__
#if 0
    if(errmsg != "Debug session stopped") {
        ::wxMessageBox(_("Node.js debugger disconnected unexpectedly\nYou might want to check the console to see if "
                         "there are any useful messages"),
                       _("CodeLite"),
                       wxICON_WARNING | wxOK_DEFAULT | wxCENTER);
    }
#endif
#else
    m_node.Terminate();
    m_socket.Reset(NULL);

    clDebugEvent event(wxEVT_NODEJS_DEBUGGER_STOPPED);
    event.SetDebuggerName("Node.js");
    EventNotifier::Get()->AddPendingEvent(event);
#endif

    // Clear the debugger markers
    ClearDebuggerMarker();
}

void NodeJSDebugger::OnNodeOutput(clCommandEvent& event)
{
    wxUnusedVar(event);
    CL_DEBUG("Node debugger:\n%s", event.GetString());

    clDebugEvent eventLog(wxEVT_NODEJS_DEBUGGER_CONSOLE_LOG);
    eventLog.SetString(event.GetString());
    EventNotifier::Get()->AddPendingEvent(eventLog);
}

void NodeJSDebugger::OnNodeTerminated(clCommandEvent& event)
{
    wxUnusedVar(event);
    EventNotifier::Get()->TopFrame()->Raise();

    // Restart the network thread
    wxBusyCursor bc;
#ifndef __WXGTK__
    m_socket.Reset(NULL);
#else
    m_node.Terminate();
    m_socket.Reset(NULL);

    clDebugEvent eventStop(wxEVT_NODEJS_DEBUGGER_STOPPED);
    eventStop.SetDebuggerName("Node.js");
    EventNotifier::Get()->AddPendingEvent(eventStop);

    // Clear the debugger markers
    ClearDebuggerMarker();
#endif
}

void NodeJSDebugger::OnWorkspaceClosed(wxCommandEvent& event) { event.Skip(); }

void NodeJSDebugger::OnWorkspaceOpened(wxCommandEvent& event) { event.Skip(); }

void NodeJSDebugger::DeleteBreakpoint(const NodeJSBreakpoint& bp)
{
    // Sanity
    if(!IsConnected()) return;
    if(!bp.IsApplied()) return;

    // Build the request
    JSONElement request = JSONElement::createObject();
    request.addProperty("type", "request");
    request.addProperty("command", "clearbreakpoint");
    JSONElement args = JSONElement::createObject("arguments");
    request.append(args);
    args.addProperty("breakpoint", bp.GetNodeBpID());

    // Write the command
    m_socket->WriteRequest(request, new NodeJSSetBreakpointHandler(bp));
}

void NodeJSDebugger::SetBreakpoint(const NodeJSBreakpoint& bp)
{
    // Sanity
    if(!IsConnected()) return;

    // Build the request
    JSONElement request = JSONElement::createObject();
    request.addProperty("type", "request");
    request.addProperty("command", "setbreakpoint");
    JSONElement args = JSONElement::createObject("arguments");
    request.append(args);
    args.addProperty("type", "script");
    args.addProperty("target", bp.GetFilename());
    args.addProperty("line", bp.GetLine() - 1);
    args.addProperty("column", 0);

    // Write the command
    m_socket->WriteRequest(request, new NodeJSSetBreakpointHandler(bp));
}

void NodeJSDebugger::Continue()
{
    // Sanity
    if(!IsConnected()) return;

    // Build the request
    JSONElement request = JSONElement::createObject();
    request.addProperty("type", "request");
    request.addProperty("command", "continue");

    // Write the command
    m_socket->WriteRequest(request, new NodeJSContinueHandler());
}

void NodeJSDebugger::SetBreakpoints()
{
    // Sanity
    if(!IsConnected()) return;
    const NodeJSBreakpoint::List_t& bps = m_bptManager.GetBreakpoints();
    std::for_each(bps.begin(), bps.end(), [&](const NodeJSBreakpoint& bp) { SetBreakpoint(bp); });
}

void NodeJSDebugger::GotControl(bool requestBacktrace)
{
    SetCanInteract(true);
    EventNotifier::Get()->TopFrame()->Raise();
    if(requestBacktrace) {
        Callstack();
    }
}

void NodeJSDebugger::Callstack()
{
    // Sanity
    if(!IsConnected()) return;

    // Build the request
    JSONElement request = JSONElement::createObject();
    request.addProperty("type", "request");
    request.addProperty("command", "backtrace");

    // Write the command
    m_socket->WriteRequest(request, new NodeJSCallstackHandler());
}

void NodeJSDebugger::SelectFrame(int frameId)
{
    // Sanity
    if(!IsConnected()) return;

    // Build the request
    JSONElement request = JSONElement::createObject();
    request.addProperty("type", "request");
    request.addProperty("command", "frame");

    JSONElement args = JSONElement::createObject("arguments");
    request.append(args);
    args.addProperty("number", frameId);

    // Write the command
    m_socket->WriteRequest(request, new NodeJSSelectFrameHandler());
}

void NodeJSDebugger::SetCanInteract(bool canInteract)
{
    clDebugEvent event(canInteract ? wxEVT_NODEJS_DEBUGGER_CAN_INTERACT : wxEVT_NODEJS_DEBUGGER_LOST_INTERACT);
    EventNotifier::Get()->ProcessEvent(event);
    this->m_canInteract = canInteract;
    if(!canInteract) {
        ClearDebuggerMarker();
    }
}

void NodeJSDebugger::SetDebuggerMarker(IEditor* editor, int lineno)
{
    wxStyledTextCtrl* stc = editor->GetCtrl();
    stc->MarkerDeleteAll(smt_indicator);
    stc->MarkerAdd(lineno, smt_indicator);
    int caretPos = stc->PositionFromLine(lineno);
    stc->SetSelection(caretPos, caretPos);
    stc->SetCurrentPos(caretPos);
    stc->EnsureCaretVisible();
    editor->CenterLine(lineno);
#ifdef __WXOSX__
    stc->Refresh();
#endif
}

void NodeJSDebugger::ClearDebuggerMarker()
{
    IEditor::List_t editors;
    clGetManager()->GetAllEditors(editors);
    std::for_each(
        editors.begin(), editors.end(), [&](IEditor* editor) { editor->GetCtrl()->MarkerDeleteAll(smt_indicator); });
}

void NodeJSDebugger::DoHighlightLine(const wxString& filename, int lineNo)
{
    IEditor* activeEditor = clGetManager()->OpenFile(filename, "", lineNo - 1);
    if(activeEditor) {
        SetDebuggerMarker(activeEditor, lineNo - 1);
    }
}

void NodeJSDebugger::OnHighlightLine(clDebugEvent& event)
{
    event.Skip();
    int line = event.GetLineNumber();
    wxFileName file = event.GetFileName();

    ClearDebuggerMarker();
    if(file.Exists()) {
        CallAfter(&NodeJSDebugger::DoHighlightLine, file.GetFullPath(), line);

    } else {
        // Probably a node.js internal file
        wxFileName fn(clStandardPaths::Get().GetUserDataDir(), file.GetFullPath());
        fn.AppendDir("webtools");
        fn.AppendDir("tmp");
        if(fn.Exists()) {
            CallAfter(&NodeJSDebugger::DoHighlightLine, fn.GetFullPath(), line);
        } else {
            // Ask the file from nodejs
            GetCurrentFrameSource(file.GetFullPath(), line);
        }
    }
}

void NodeJSDebugger::ExceptionThrown(const NodeJSDebuggerException& exc)
{
    // Switch to the 'Console' view
    clDebugEvent event(wxEVT_NODEJS_DEBUGGER_EXCEPTION_THROWN);
    event.SetFileName(exc.script);
    event.SetLineNumber(exc.line);
    event.SetString(exc.message);
    event.SetInt(exc.column);
    EventNotifier::Get()->AddPendingEvent(event);
}

void NodeJSDebugger::ConnectError(const wxString& errmsg)
{
    ::wxMessageBox(wxString::Format(_("Failed to connect to Node.js debugger:\n'%s'"), errmsg),
                   "CodeLite",
                   wxOK | wxICON_ERROR | wxCENTER);
    m_socket.Reset(NULL);
}

void NodeJSDebugger::BreakOnException(bool b)
{
    // Sanity
    if(!IsConnected()) return;

    // Build the request
    JSONElement request = JSONElement::createObject();
    request.addProperty("type", "request");
    request.addProperty("command", "setexceptionbreak");

    JSONElement args = JSONElement::createObject("arguments");
    request.append(args);
    args.addProperty("type", "uncaught");
    args.addProperty("enabled", b);

    // Write the command
    m_socket->WriteRequest(request, NULL);
}

void NodeJSDebugger::GetCurrentFrameSource(const wxString& filename, int line)
{
    // Sanity
    if(!IsConnected()) return;

    // Build the request
    JSONElement request = JSONElement::createObject();
    request.addProperty("type", "request");
    request.addProperty("command", "source");

    // Write the command
    m_socket->WriteRequest(request, new NodeJSGetScriptHandler(filename, line));
}

void NodeJSDebugger::OnEditorChanged(wxCommandEvent& event)
{
    event.Skip();
    IEditor::List_t editors;
    clGetManager()->GetAllEditors(editors);

    wxStringSet_t tmpFiles = m_tempFiles;
    wxStringSet_t closedTempEditors;
    // Loop over the temp files list
    std::for_each(tmpFiles.begin(), tmpFiles.end(), [&](const wxString& filename) {
        // If the temp file does not match one of the editors, assume it was closed and delete
        // the temporary file
        IEditor::List_t::iterator iter = std::find_if(editors.begin(), editors.end(), [&](IEditor* editor) {
            if(editor->GetFileName().GetFullPath() == filename) return true;
            return false;
        });
        if(iter == editors.end()) {
            closedTempEditors.insert(filename);
            m_tempFiles.erase(filename);
        }
    });

    if(!closedTempEditors.empty()) {
        DoDeleteTempFiles(closedTempEditors);
    }
}

void NodeJSDebugger::DoDeleteTempFiles(const wxStringSet_t& files)
{
    std::for_each(files.begin(), files.end(), [&](const wxString& filename) {
        wxLogNull noLog;
        ::wxRemoveFile(filename);
    });
}

void NodeJSDebugger::OnEvalExpression(clDebugEvent& event)
{
    event.Skip();

    // Build the request
    JSONElement request = JSONElement::createObject();
    request.addProperty("type", "request");
    request.addProperty("command", "evaluate");
    JSONElement args = JSONElement::createObject("arguments");
    request.append(args);
    args.addProperty("expression", event.GetString());

    // Write the command
    m_socket->WriteRequest(request, new NodeJSEvaluateExprHandler(event.GetString(), kNodeJSContextConsole));
}

void NodeJSDebugger::Lookup(const std::vector<int>& handles, eNodeJSContext context)
{
    JSONElement request = JSONElement::createObject();
    request.addProperty("type", "request");
    request.addProperty("command", "lookup");

    JSONElement args = JSONElement::createObject("arguments");
    request.append(args);

    JSONElement arrHandles = JSONElement::createArray("handles");
    args.append(arrHandles);

    for(size_t i = 0; i < handles.size(); ++i) {
        arrHandles.arrayAppend(JSONElement("", handles.at(i), cJSON_Number));
    }

    // Write the command
    m_socket->WriteRequest(request, new NodeJSLookupHandler(context));
}

void NodeJSDebugger::ShowTooltip(const wxString& expression, const wxString& jsonOutput)
{
    if(m_tooltip) {
        m_tooltip->Destroy();
        m_tooltip = NULL;
    }

    m_tooltip = new NodeJSDebuggerTooltip(this, expression);
    m_tooltip->ShowTip(jsonOutput);
}

void NodeJSDebugger::OnDestroyTip(clCommandEvent& event)
{
    if(m_tooltip) {
        m_tooltip->Destroy();
        m_tooltip = NULL;
    }
}

void NodeJSDebugger::OnAttach(clDebugEvent& event)
{
#ifdef __WXMSW__
    if(event.GetDebuggerName() != "NodeJS Debugger") {
        event.Skip();
        return;
    }
    event.Skip(false);
    ::wxMessageBox(_("Debugging a running Node.js process is only available on Linux / OSX"),
                   "CodeLite",
                   wxICON_WARNING | wxCENTER | wxOK);
#else

    if(event.GetDebuggerName() != "NodeJS Debugger") {
        event.Skip();
        return;
    }

    event.Skip(false); // ours to handle, stop the event chain

    if(m_socket && m_socket->IsConnected()) {
        ::wxMessageBox(_("An active debug session is already running"), "CodeLite", wxICON_WARNING | wxCENTER | wxOK);
        return;
    };

    ::kill(event.GetInt(), SIGUSR1);
    // already connected?
    m_socket.Reset(new NodeJSSocket(this));
    m_socket->Connect("127.0.0.1", 5858);
#endif
}

void NodeJSDebugger::StartDebugger(const wxString& command, const wxString& workingDirectory)
{
    if(!m_node.ExecuteConsole(command, workingDirectory, true, command)) {
        ::wxMessageBox(_("Failed to start NodeJS application"), "CodeLite", wxOK | wxICON_ERROR | wxCENTER);
        m_socket.Reset(NULL);
    }

    // already connected?
    m_socket.Reset(new NodeJSSocket(this));
    NodeJSWorkspaceUser userConf(NodeJSWorkspace::Get()->GetFilename().GetFullPath());
    userConf.Load();
    m_socket->Connect("127.0.0.1", userConf.GetDebuggerPort());
}