File: breakpointsmgr.cpp

package info (click to toggle)
codelite 12.0+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 95,112 kB
  • sloc: cpp: 424,040; ansic: 18,284; php: 9,569; lex: 4,186; yacc: 2,820; python: 2,294; sh: 312; makefile: 51; xml: 13
file content (1138 lines) | stat: -rw-r--r-- 39,151 bytes parent folder | download | duplicates (2)
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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright            : (C) 2008 by Eran Ifrah
// file name            : breakpointsmgr.cpp
//
// -------------------------------------------------------------------------
// A
//              _____           _      _     _ _
//             /  __ \         | |    | |   (_) |
//             | /  \/ ___   __| | ___| |    _| |_ ___
//             | |    / _ \ / _  |/ _ \ |   | | __/ _ )
//             | \__/\ (_) | (_| |  __/ |___| | ||  __/
//              \____/\___/ \__,_|\___\_____/_|\__\___|
//
//                                                  F i l e
//
//    This program is free software; you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation; either version 2 of the License, or
//    (at your option) any later version.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#include "wx/numdlg.h"
#include "wx/regex.h"
#include "breakpointsmgr.h"
#include "debuggermanager.h"
#include "manager.h"
#include "frame.h"
#include "breakpointpropertiesdlg.h"
#include "breakpointdlg.h"
#include "event_notifier.h"

//---------------------------------------------------------

bool BreakptMgr::AddBreakpointByAddress(const wxString& address)
{
    BreakpointInfo bp;
    bp.memory_address = address;
    bp.origin = BO_Other;
    bp.internal_id = GetNextID();
    return AddBreakpoint(bp);
}

bool BreakptMgr::AddBreakpointByLineno(const wxString& file,
                                       const int lineno,
                                       const wxString& conditions /*=wxT("")*/,
                                       const bool is_temp,
                                       bool is_disabled)
{
    BreakpointInfo bp;
    bp.Create(file, lineno, GetNextID());
    bp.origin = BO_Editor;
    if(is_temp) {
        bp.bp_type = BP_type_tempbreak;
        bp.is_temp = true;
    }
    bp.is_enabled = !is_disabled;
    bp.conditions = conditions;
    return AddBreakpoint(bp);
}

bool BreakptMgr::AddBreakpoint(const BreakpointInfo& bp)
{
    if(bp.bp_type != BP_type_watchpt && bp.file.IsEmpty() && bp.function_name.IsEmpty() &&
       bp.memory_address.IsEmpty() && bp.lineno == wxNOT_FOUND) {
        // no function nor file? no memory address?
        // do nothing then
        return true;
    }

    IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
    if(dbgr && dbgr->IsRunning()) {
        // If the debugger is already running, tell it we want a new bp
        // If not, they'll all be added together when the debugger does start
        bool contIsNeeded = PauseDebuggerIfNeeded();

        dbgr->Break(bp);

        if(contIsNeeded) {
            dbgr->Continue();
        }
    }

    BreakpointInfo newBreakpoint(bp);
    SetBestBPType(newBreakpoint);

    BreakpointInfoVec_t::const_iterator iter = std::find(m_bps.begin(), m_bps.end(), newBreakpoint);
    if(iter == m_bps.end()) {
        // new breakpoint
        m_bps.push_back(newBreakpoint);
    }

    DeleteAllBreakpointMarkers();
    RefreshBreakpointMarkers();
    return true;
}

// Add a breakpoint using the 'Properties' dialog
void BreakptMgr::AddBreakpoint()
{
    BreakptPropertiesDlg dlg(NULL);
    dlg.SetTitle(_("Create a breakpoint or watchpoint"));

    LEditor* const editor = clMainFrame::Get()->GetMainBook()->GetActiveEditor();
    BreakpointInfo bp;
    bp.Create(
        editor ? editor->GetFileName().GetFullPath() : wxString(), editor ? editor->GetCurrentLine() : -1, GetNextID());
    dlg.EnterBPData(bp);

    if(dlg.ShowModal() != wxID_OK) {
        return;
    }

    if(AddBreakpoint(dlg.b)) {
        IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
        if((!dlg.b.is_enabled) && dbgr && dbgr->IsRunning()) {
            SetBPEnabledState(dlg.b.debugger_id, dlg.b.is_enabled);
        }
        wxString msg;
        if(dlg.b.bp_type == BP_type_watchpt) {
            msg = _("Watchpoint successfully added");
        } else {
            msg = _("Breakpoint successfully added");
        }
        clMainFrame::Get()->GetStatusBar()->SetMessage(msg);
    }
}

void BreakptMgr::GetBreakpoints(std::vector<BreakpointInfo>& li)
{
    DoRemoveDuplicateBreakpoints();
    li = m_bps;
}

// Get all known breakpoints for this line/file
BreakpointInfo& BreakptMgr::GetBreakpoint(const wxString& fileName, const int lineno)
{
    wxFileName fn(fileName);
    fn.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_LONG);

    BreakpointInfoVec_t::iterator iter =
        std::find_if(m_bps.begin(), m_bps.end(), BreakpointInfo::PredicateByFileAndLine(fn.GetFullPath(), lineno));
    if(iter == m_bps.end()) {
        static BreakpointInfo empty;
        return empty;
    }
    return *iter;
}

const BreakpointInfo& BreakptMgr::GetBreakpoint(const wxString& fileName, const int lineno) const
{
    wxFileName fn(fileName);
    fn.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_LONG);

    BreakpointInfoVec_t::const_iterator iter =
        std::find_if(m_bps.begin(), m_bps.end(), BreakpointInfo::PredicateByFileAndLine(fn.GetFullPath(), lineno));
    if(iter == m_bps.end()) {
        static BreakpointInfo empty;
        return empty;
    }
    return *iter;
}

void BreakptMgr::GetTooltip(const wxString& fileName, int lineno, wxString& tip, wxString& title)
{
    if(fileName.IsEmpty() || lineno < 0) {
        return;
    }

    const BreakpointInfo& bp = GetBreakpoint(fileName, lineno);
    if(bp.IsNull()) {
        return;
    }

    int id = (bp.debugger_id > 0 ? bp.debugger_id : bp.internal_id - FIRST_INTERNAL_ID);
    title << _("<b>Breakpoint# ") << id << "</b>";

    bool isSimple = true;
    if(bp.is_temp) {
        tip << _("Temporary \n");
        isSimple = false;
    }

    if(!bp.is_enabled) {
        tip << _(" (disabled)\n");
        isSimple = false;
    }

    if(bp.ignore_number > 0) {
        tip << wxString::Format(_("Ignore-count = %u\n"), bp.ignore_number);
        isSimple = false;
    }

    if(!bp.conditions.IsEmpty()) {
        tip << wxString::Format(_("Condition:\n<code>%s</code>\n"), bp.conditions.c_str());
        isSimple = false;
    }

    if(!bp.commandlist.IsEmpty()) {
        tip << wxString::Format(_("Commands:\n<code>%s</code>\n"), bp.commandlist.c_str());
        isSimple = false;
    }

    if(isSimple) {
        tip << _("Normal breakpoint\n");
    }

    tip.Trim().Trim(false);
}

// Delete all line-type breakpoint markers in all editors
// Done before refreshing after a delete or edit, lest it was the last bp in a file
void BreakptMgr::DeleteAllBreakpointMarkers()
{
    LEditor::Vec_t editors;
    clMainFrame::Get()->GetMainBook()->GetAllEditors(editors, MainBook::kGetAll_IncludeDetached);
    for(size_t i = 0; i < editors.size(); ++i) {
        editors.at(i)->DelAllBreakpointMarkers();
    }
}

// Refresh all line-type breakpoint markers in all editors
void BreakptMgr::RefreshBreakpointMarkers()
{
    std::vector<LEditor*> editors;
    clMainFrame::Get()->GetMainBook()->GetAllEditors(editors, MainBook::kGetAll_IncludeDetached);

    for(size_t i = 0; i < editors.size(); i++) {
        DoRefreshFileBreakpoints(editors.at(i));
    }
}

// Delete all breakpoint markers for this file, then re-mark with the currently-correct marker
void BreakptMgr::DoRefreshFileBreakpoints(LEditor* editor)
{
    // Load the file's line-type bps into fi, and make a set of their line-numbers
    std::multimap<int, BreakpointInfo> bps;
    for(size_t i = 0; i < m_bps.size(); i++) {
        BreakpointInfo b = m_bps.at(i);
        if((editor->GetFileName() == b.file) && (b.lineno != -1)) {
            bps.insert(std::pair<int, BreakpointInfo>(b.lineno, b));
        }
    }

    editor->DelAllBreakpointMarkers();

    // the multimap now holds a table of
    // line numbers and breakpointsInfo, collect all line numbers's breakpoint info into vector
    // and place markers
    for(std::multimap<int, BreakpointInfo>::iterator i = bps.begin(); i != bps.end(); i++) {
        std::pair<std::multimap<int, BreakpointInfo>::iterator, std::multimap<int, BreakpointInfo>::iterator> range =
            bps.equal_range(i->first);
        std::vector<BreakpointInfo> v;
        int count = 0;
        for(std::multimap<int, BreakpointInfo>::iterator it = range.first; it != range.second; it++) {
            v.push_back(it->second);
            ++count;
        }
        // Inc over the rest of the range, otherwise there'll be duplication when there's >1 bp on a line
        while(--count > 0) {
            ++i;
        }
        // Now work out which is the most significant (in marker terms) and tell the editor
        DoProvideBestBP_Type(editor, v);
    }
}

// Given a list of bps, tell the editor which is the most significant (in marker terms)
void BreakptMgr::DoProvideBestBP_Type(LEditor* editor, const std::vector<BreakpointInfo>& li)
{
    if((editor == NULL) || (li.size() == 0)) {
        return;
    }
    // If there's an enabled bp of any sort, it beats all disabled ones
    // Otherwise, BP_type_break > BP_type_tempbreak > BP_type_cmdlistbreak > BP_type_condbreak > BP_type_ignoredbreak
    int values[BP_LAST_MARKED_ITEM + 1]; // Allow for BP_type_none = 0
    values[BP_type_break] = 100;
    values[BP_type_tempbreak] = 90;
    values[BP_type_cmdlistbreak] = 80;
    values[BP_type_condbreak] = 70;
    values[BP_type_ignoredbreak] = 60;
    values[BP_type_none] = 0;

    BreakpointType best = BP_type_none;
    int best_value = 0;
    bool is_disabled = false;
    std::vector<BreakpointInfo>::const_iterator iter = li.begin();
    for(; iter != li.end(); ++iter) {
        BreakpointType bpt = iter->bp_type;
        if(bpt == BP_type_invalid) {
            continue;
        }
        int val = values[bpt];
        if(!iter->is_enabled) {
            val /= 2; // Halving the value for disability means that abled always outranks disabled, without otherwise
                      // interfering with the order
        }
        if(val > best_value) {
            best = bpt;
            best_value = val;
            is_disabled = !iter->is_enabled; // If the new item wins, store its data
        }
    }

    if(best > 0) {
        // ATTN: this wierd allocation is due to bug in optimization of g++
        // which seems to crash (removing optimization fixes this problem,
        // but we prefer to stick with optimization level 2)
        std::vector<BreakpointInfo>* v = new std::vector<BreakpointInfo>(li);
        editor->SetBreakpointMarker(li.at(0).lineno, best, is_disabled, *v);
        delete v;
    }
}

// Invalidates each debugger_id
void BreakptMgr::DebuggerStopped()
{
    std::vector<BreakpointInfo> newList;
    for(size_t i = 0; i < m_bps.size(); i++) {
        BreakpointInfo& bp = m_bps.at(i);
        bp.debugger_id = -1;

        // We collect all the breakpoints which their origin
        // was the editor
        if(bp.file.IsEmpty() == false && bp.lineno != wxNOT_FOUND) {
            newList.push_back(bp);
        }
    }

    for(size_t i = 0; i < m_pendingBreakpointsList.size(); i++) {
        BreakpointInfo& bp = m_pendingBreakpointsList.at(i);
        bp.debugger_id = -1;

        // We collect all the breakpoints which their origin
        // was the editor
        if(bp.origin == BO_Editor) {
            newList.push_back(bp);
        }
    }

    m_bps.clear();
    m_pendingBreakpointsList.clear();

    m_bps = newList;
    DoRemoveDuplicateBreakpoints();
}

bool BreakptMgr::DelBreakpoint(double id)
{
    int index = FindBreakpointById(id, m_bps);
    if(index == wxNOT_FOUND) {
        return false;
    }

    // remove it from the debugger if it's running
    IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
    if(dbgr && dbgr->IsRunning()) {
        if(id > FIRST_INTERNAL_ID) {
            // This shouldn't happen while the debugger is running (debugger_id should be valid)
            // But if it does, assume it was a bp that gdb couldn't create, and just remove from the bp list
        } else {
            bool contIsNeeded = PauseDebuggerIfNeeded();
            if(dbgr->RemoveBreak(id)) {
                // Strangely, -break-delete doesn't output any confirmation except for ^done. So do it here
                wxString msg = ((m_bps.at(index).bp_type == BP_type_watchpt) ? _("Watchpoint ") : _("Breakpoint "));
                ManagerST::Get()->UpdateAddLine(msg + wxString::Format(_("%i deleted"), (int)id));
            }
            if(contIsNeeded) {
                dbgr->Continue();
            }
        }
    }

    // Delete all markers before removing bp from the vector. Otherwise if id was the last in a file...
    DeleteAllBreakpointMarkers();

    m_bps.erase(m_bps.begin() + index);

    RefreshBreakpointMarkers();
    return true;
}

bool BreakptMgr::DelBreakpointByLineno(const wxString& file, const int lineno)
{
    const BreakpointInfo& bp = GetBreakpoint(file, lineno);
    if(bp.IsNull()) {
        return false;
    }

    double bpId = bp.GetId();
    if(bpId == wxID_CANCEL || bpId == BP_type_none) return false;

    DelBreakpoint(bpId);
    return true;
}

void BreakptMgr::ApplyPendingBreakpoints()
{
    if(!PendingBreakpointsExist()) {
        return; // Nothing to do
    }

    IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
    if(!(dbgr && dbgr->IsRunning())) {
        return; // If the debugger isn't running, there's no point (and we shouldn't have reached here anyway)
    }
    bool contIsNeeded = PauseDebuggerIfNeeded();

    for(size_t i = m_pendingBreakpointsList.size(); i > 0; --i) {
        BreakpointInfo bp = m_pendingBreakpointsList.at(i - 1);

        // First check to see if the debugger already accepted this one
        // The answer should be no, as acceptance should have removed it from this list
        int index = FindBreakpointById(bp.internal_id, m_bps);
        if(index != wxNOT_FOUND) {
            // Hmm. See if there's a valid debugger_id. If so, the bp *was* accepted, and shouldn't be on the pending
            // list
            if(m_bps.at(index).debugger_id != -1) {
                m_pendingBreakpointsList.erase(m_pendingBreakpointsList.begin() + i - 1);
            }
            continue; // The bp hasn't been assessed yet; it's probably pointless to try to reapply it atm
        }

        // This bp didn't 'take' the first time; "..try, try again" :p
        dbgr->Break(bp);
        m_bps.push_back(bp);
    }

    if(contIsNeeded) {
        dbgr->Continue();
    }

    RefreshBreakpointMarkers();
}

void BreakptMgr::DelAllBreakpoints()
{
    IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
    if(dbgr && dbgr->IsRunning()) {
        bool contIsNeeded = PauseDebuggerIfNeeded();
        dbgr->RemoveAllBreaks();
        if(contIsNeeded) {
            dbgr->Continue();
        }
    }

    // Delete all markers before clearing m_bps, otherwise we won't know which files they were in
    DeleteAllBreakpointMarkers();
    m_bps.clear();
    m_pendingBreakpointsList.clear(); // Delete any pending bps too
    clMainFrame::Get()->GetDebuggerPane()->GetBreakpointView()->Initialize();
}

void BreakptMgr::SetAllBreakpointsEnabledState(bool enabled)
{
    unsigned int successes = 0;
    bool debuggerIsRunning = false;
    bool contIsNeeded = false;

    IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
    if(dbgr && dbgr->IsRunning()) {
        debuggerIsRunning = true;
        contIsNeeded = PauseDebuggerIfNeeded();
    }

    for(size_t i = 0; i < m_bps.size(); ++i) {
        BreakpointInfo& bp = m_bps.at(i);
        if(((bp.debugger_id != -1) || !debuggerIsRunning) // Sanity check for when the debugger's running
           &&
           (bp.is_enabled != enabled)) { // No point setting it to the current status
            if(debuggerIsRunning) {
                if(dbgr->SetEnabledState(bp.debugger_id, enabled)) {
                    bp.is_enabled = enabled;
                    ++successes;
                }
            } else {
                bp.is_enabled = enabled;
                ++successes;
            }
        }
    }

    if(debuggerIsRunning && contIsNeeded) {
        dbgr->Continue();
    }

    if(successes) {
        RefreshBreakpointMarkers();
        clMainFrame::Get()->GetDebuggerPane()->GetBreakpointView()->Initialize();

        wxString msg = wxString::Format(wxT("%u "), successes);
        msg << (enabled ? _("breakpoints enabled") : _("breakpoints disabled"));
        clMainFrame::Get()->GetStatusBar()->SetMessage(msg);
    }
}

// The debugger labels each breakpoint with an id and passes it here via Manager::UpdateBpAdded.
// By storing it as BreakpointInfo::debugger_id, we can be certain that this bp refers to the gdb breakpoint
void BreakptMgr::SetBreakpointDebuggerID(const int internal_id, const int debugger_id)
{
    std::vector<BreakpointInfo>::iterator iter = m_bps.begin();
    for(; iter != m_bps.end(); ++iter) {
        if(iter->internal_id == internal_id) {
            // We've found the match. However, if breakpoint creation had failed, confess, then delete
            if(debugger_id == -1) {
                wxString msg;
                if(iter->bp_type == BP_type_watchpt) {
                    msg = _("Watchpoint creation unsuccessful");
                } else {
                    msg = _("Breakpoint creation unsuccessful");
                }

                // add message to the debugger tab
                ManagerST::Get()->UpdateAddLine(msg);
                DeleteAllBreakpointMarkers(); // Must do this before the erase, otherwise the last-bp-in-file will be
                                              // missed
                m_bps.erase(iter);

                // update the UI as well
                clMainFrame::Get()->GetDebuggerPane()->GetBreakpointView()->Initialize();
                RefreshBreakpointMarkers();
                return;
            }
            // Otherwise store the valid debugger_id
            iter->debugger_id = debugger_id;
            // Remove the bp from  the 'pending' array
            int index = FindBreakpointById(internal_id, m_pendingBreakpointsList);
            if(index != wxNOT_FOUND) {
                m_pendingBreakpointsList.erase(m_pendingBreakpointsList.begin() + index);
            }
            // update the UI as well
            clMainFrame::Get()->GetDebuggerPane()->GetBreakpointView()->Initialize();
            return;
        }
    }
    wxLogMessage(wxT("SetBreakpointDebuggerID(): Failed to match internal_id to debugger_id"));
}

// Set a breakpoint's ignore count
bool BreakptMgr::IgnoreByLineno(const wxString& file, const int lineno)
{
    BreakpointInfo& bp = GetBreakpoint(file, lineno);
    if(bp.IsNull()) {
        return false;
    }

    if(bp.bp_type == BP_type_invalid) {
        return false;
    }

    long newvalue = ::wxGetNumberFromUser(
        _("Please enter the new ignore-count"), wxT(""), _("Set ignore-count"), bp.ignore_number, 0, 1000000);
    if((newvalue == -1) || (newvalue == (long)bp.ignore_number)) {
        return false;
    }

    if(!SetBPIgnoreCount(bp.GetId(), newvalue)) {
        return false;
    }

    bp.ignore_number = newvalue;

    // Explicitly set the best type, in case the user just reset a previously-ignored bp
    SetBestBPType(bp);

    RefreshBreakpointMarkers();
    return true;
}

void BreakptMgr::EditBreakpointByLineno(const wxString& file, const int lineno)
{
    const BreakpointInfo& bp = GetBreakpoint(file, lineno);
    if(bp.IsNull()) return;

    int bid = bp.GetId();
    if(bid == wxID_CANCEL || bid == BP_type_none) {
        return;
    }

    int index = FindBreakpointById(bid, m_bps);
    if(index == wxNOT_FOUND) {
        return;
    }

    bool dummy;
    EditBreakpoint(index, dummy);
}

void BreakptMgr::EditBreakpoint(int index, bool& bpExist)
{
    // sanity
    bpExist = true;
    if(index < 0 || index >= (int)m_bps.size()) {
        wxLogMessage(wxT("BreakptMgr::EditBreakpoint: Insane index"));
        bpExist = false;
        return;
    }

    BreakpointInfo bp = m_bps.at(index);
    BreakptPropertiesDlg dlg(NULL);
    wxString title;
    if(bp.bp_type == BP_type_watchpt) {
        title = _("Properties for watchpoint ");
    } else {
        title = _("Properties for breakpoint ");
    }
    double id = bp.debugger_id;
    if(id == -1) {
        id = bp.internal_id - FIRST_INTERNAL_ID;
    }
    title << id;
    dlg.SetTitle(title);

    dlg.EnterBPData(bp);
    if(dlg.ShowModal() != wxID_OK) {
        return;
    }

    SetBestBPType(dlg.b); // The edited data's available. Use it to determine the best bp_type
    if(bp == dlg.b) {
        // Nothing was altered
        return;
    }

    // We've got our altered dlg.b If the debugger's running, we can update it now
    // Otherwise, it'll be automatically inserted correctly when the debugger starts
    IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
    if(dbgr && dbgr->IsRunning()) {
        if(CanThisBreakpointBeUpdated(dlg.b, bp)) {
            if(dlg.b.ignore_number != bp.ignore_number) {
                if(!SetBPIgnoreCount(dlg.b.debugger_id, dlg.b.ignore_number)) {
                    return; // Harsh, but what else can one do?
                }
            }
            if(dlg.b.is_enabled != bp.is_enabled) {
                if(!SetBPEnabledState(dlg.b.debugger_id, dlg.b.is_enabled)) {
                    return;
                }
            }
            if(dlg.b.conditions != bp.conditions) {
                if(!SetBPConditon(dlg.b)) {
                    return;
                }
            }
            if(dlg.b.commandlist != bp.commandlist) {
                if(!SetBPCommands(dlg.b)) {
                    return;
                }
            }
        } else {
            // If it can't be updated (because gdb wouldn't be able to cope with the change), replace
            bool contIsNeeded = PauseDebuggerIfNeeded();
            dbgr->RemoveBreak(bp.debugger_id);
            dbgr->Break(dlg.b);
            // dbgr->Break(bp) doesn't set the ignore/disabled/etc states
            // but we can't do it now, as we don't yet know the debugger_id
            // However it will happen later, in SetBreakpointDebuggerID
            if(contIsNeeded) {
                dbgr->Continue();
            }
        }
    }

    // Replace the old data with the new, in m_bps
    m_bps.at(index) = dlg.b;
    DeleteAllBreakpointMarkers();
    RefreshBreakpointMarkers();
}

void BreakptMgr::ReconcileBreakpoints(const std::vector<BreakpointInfo>& li)
{
    std::vector<BreakpointInfo> updated_bps;
    std::vector<BreakpointInfo>::const_iterator li_iter = li.begin();
    for(; li_iter != li.end(); ++li_iter) {
        int index = FindBreakpointById(li_iter->debugger_id, m_bps);
        if(index == wxNOT_FOUND) {

            if(IsDuplicate(*li_iter, updated_bps)) continue;

            // This will happen e.g. if a bp was auto-set on Main()
            // If so, its internal_id will be invalid
            BreakpointInfo bp = *li_iter;
            bp.internal_id = GetNextID();
            updated_bps.push_back(bp);

        } else {
            // We've match the debugger_id from -break-list with a bp
            // Update the ignore-count, then store it in a new vector
            BreakpointInfo bp = m_bps.at(index);
            bp.ignore_number = li_iter->ignore_number;
            bp.what = li_iter->what;
            bp.at = li_iter->at;

            // Remove it from the m_bps list
            m_bps.erase(m_bps.begin() + index);

            SetBestBPType(bp); // as this might have just changed
            updated_bps.push_back(bp);
        }
    }
    // All the still-existing bps have been added to updated_bps
    // So throw away m_bps (which will contain stale bps) and replace with the new vector
    // First though, delete all markers. Otherwise, if the last in a file has been deleted...
    DeleteAllBreakpointMarkers();

    // All the stale breakpoints should be assigned to the 'm_pendingBreakpointList'
    m_pendingBreakpointsList = m_bps;

    m_bps.clear();
    SetBreakpoints(updated_bps);

    RefreshBreakpointMarkers();
    // update the Breakpoints pane too
    clMainFrame::Get()->GetDebuggerPane()->GetBreakpointView()->Initialize();
}

// When a a breakpoint is hit, see if it's got a command-list that needs faking
void BreakptMgr::BreakpointHit(double id)
{
    int index = FindBreakpointById(id, m_bps);
    if((index == wxNOT_FOUND) || (index >= FIRST_INTERNAL_ID)) {
        return;
    }

    BreakpointInfo bp = m_bps.at(index);
    if(!bp.commandlist.IsEmpty()) {
        IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
        if(dbgr && dbgr->IsRunning()) {
            // A likely command, presumably at the end of the command-list, is 'continue' or 'cont'
            // Filter this out and do it separately, otherwise Manager::UpdateLostControl isn't called to blank the
            // indicator
            static wxRegEx reContinue(wxT("(([[:space:]]|(^))((cont$)|(continue)))"));
            bool needsCont = false;
            wxString commands = bp.commandlist;
            if(reContinue.IsValid() && reContinue.Matches(commands)) {
                size_t start, len;
                if(reContinue.GetMatch(&start, &len)) {
                    commands = commands.Left(start);
                    needsCont = true;
                }
            }
            if(!commands.IsEmpty()) { // Just in case someone's _only_ command is 'continue' !
                dbgr->ExecuteCmd(commands);
            }
            if(needsCont) {
                dbgr->Continue();
            }
        }
    }

    if(bp.bp_type == BP_type_tempbreak) {
        // If this is a temporary bp, remove it from m_bps now it's been hit
        // Otherwise it will be treated as a 'Pending' bp, the button will be displayed
        // and, if clicked, the bp will be resurrected.
        int index = FindBreakpointById(id, m_bps);
        if(index != wxNOT_FOUND) {
            m_bps.erase(m_bps.begin() + index);
        }
    }
}

/*------------------------------- Implementation -------------------------------*/

// Construct set of files containing bps
std::set<wxString> BreakptMgr::GetFilesWithBreakpointMarkers()
{
    // Make a set of all filenames containing a file-relevant variety of breakpoint
    std::set<wxString> filenames;
    std::vector<BreakpointInfo>::iterator iter = m_bps.begin();
    for(; iter != m_bps.end(); ++iter) {
        // If this bp is a lineno or function type, add its file to the set
        wxString fileName = iter->file;
        if((!fileName.IsEmpty()) && (iter->memory_address.IsEmpty())) {
            filenames.insert(fileName);
        }
    }

    return filenames;
}

int BreakptMgr::FindBreakpointById(double id, const std::vector<BreakpointInfo>& li)
{
    std::vector<BreakpointInfo>::const_iterator iter = li.begin();
    for(; iter != li.end(); ++iter) {
        BreakpointInfo b = *iter;
        // If we were passed an id > 10000, it must be internal
        double this_id = (id > FIRST_INTERNAL_ID ? b.internal_id : b.debugger_id);
        if(id == this_id) {
            return (int)(iter - li.begin());
        }
    }

    return wxNOT_FOUND;
}

bool BreakptMgr::CanThisBreakpointBeUpdated(const BreakpointInfo& a, const BreakpointInfo& b) const
{
    // Since, afaik, the only things that *can* be updated are: conditions/commands/ignores/enables,
    // return true if all but these are == (except for bp_type, which will have changed as a consequence of those)
    BreakpointInfo temp = a;
    temp.ignore_number = b.ignore_number;
    temp.is_enabled = b.is_enabled;
    temp.conditions = b.conditions;
    temp.commandlist = b.commandlist;
    temp.bp_type = b.bp_type;
    return (temp == b);
}

bool BreakptMgr::SetBPIgnoreCount(double bid, const int ignorecount)
{
    IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
    if(dbgr && dbgr->IsRunning()) {
        // If the debugger is already running, tell it about the new ignore level
        // If not, it'll happen automatically when the debugger does start
        bool contIsNeeded = PauseDebuggerIfNeeded();
        bool result = dbgr->SetIgnoreLevel(bid, ignorecount);
        if(contIsNeeded) {
            dbgr->Continue();
        }
        return result;
    }
    return true;
}

bool BreakptMgr::SetBPCommands(const BreakpointInfo& bp)
{
    IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
    if(dbgr && dbgr->IsRunning()) {
        // If the debugger is already running, tell it about the commands
        // If not, it'll happen automatically when the debugger does start
        bool contIsNeeded = PauseDebuggerIfNeeded();
        bool result = dbgr->SetCommands(bp);
        if(contIsNeeded) {
            dbgr->Continue();
        }
        return result;
    }
    return false;
}

bool BreakptMgr::SetBPConditon(const BreakpointInfo& bp)
{
    IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
    if(dbgr && dbgr->IsRunning()) {
        // If the debugger is already running, tell it about the condition
        // If not, it'll happen automatically when the debugger does start
        bool contIsNeeded = PauseDebuggerIfNeeded();
        bool result = dbgr->SetCondition(bp);
        if(contIsNeeded) {
            dbgr->Continue();
        }
        return result;
    }
    return false;
}

bool BreakptMgr::SetBPEnabledState(double bid, const bool enable)
{
    IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
    if(dbgr && dbgr->IsRunning()) {
        // If the debugger is already running, tell it about the new 'enable' level
        // If not, it'll happen automatically when the debugger does start
        bool contIsNeeded = PauseDebuggerIfNeeded();
        bool result = dbgr->SetEnabledState(bid, enable);
        if(contIsNeeded) {
            dbgr->Continue();
        }
        return result;
    }
    return true;
}

void BreakptMgr::SetBestBPType(BreakpointInfo& bp)
{
    if(bp.bp_type == BP_type_watchpt) {
        return;
    }

    if(bp.ignore_number > 0) {
        bp.bp_type = BP_type_ignoredbreak;
        return;
    }

    if(bp.IsConditional()) {
        bp.bp_type = BP_type_condbreak;
        return;
    }

    if(!bp.commandlist.IsEmpty()) {
        bp.bp_type = BP_type_cmdlistbreak;
        return;
    }

    if(bp.is_temp) {
        bp.bp_type = BP_type_tempbreak;
        return;
    }

    bp.bp_type = BP_type_break; // Default option
}

// If the debugger is running but can't interact, pause it and return true (to flag needs restart)
bool BreakptMgr::PauseDebuggerIfNeeded()
{
    IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
    if(dbgr && dbgr->IsRunning() && !ManagerST::Get()->DbgCanInteract()) {
        SetExpectingControl(true);
        dbgr->Interrupt();
        return true;
    }
    return false;
}

void BreakptMgr::DeleteAllBreakpointsByFileName(const wxString& fileName)
{
    std::vector<BreakpointInfo>::iterator iter = m_bps.begin();
    while(iter != m_bps.end()) {
        if((fileName == iter->file) && (iter->lineno != -1)) {
            iter = m_bps.erase(iter);
        } else {
            ++iter;
        }
    }
}

void BreakptMgr::SetBreakpoints(const std::vector<BreakpointInfo>& bps)
{
    // append the breakpoint list
    m_bps.insert(m_bps.end(), bps.begin(), bps.end());
}

bool BreakptMgr::AreThereEnabledBreakpoints(bool enabled /*= true*/)
{
    for(size_t i = 0; i < m_bps.size(); ++i) {
        BreakpointInfo& bp = m_bps.at(i);
        if(bp.is_enabled == enabled) {
            // There's at least one bp that can be altered
            return true;
        }
    }

    return false;
}

void BreakptMgr::SaveSession(SessionEntry& session) { session.SetBreakpoints(m_bps); }

void BreakptMgr::LoadSession(const SessionEntry& session)
{
    const std::vector<BreakpointInfo>& breakpoints = session.GetBreakpoints();
    for(std::vector<BreakpointInfo>::const_iterator itr = breakpoints.begin(); itr != breakpoints.end(); ++itr) {
        BreakpointInfo bp = *itr;
        bp.internal_id = GetNextID();
        bp.origin = BO_Editor;
        AddBreakpoint(bp);
    }
    RefreshBreakpointMarkers();
}

void BreakptMgr::DragBreakpoint(LEditor* editor, int line, wxBitmap bitmap)
{
    // See if there's a bp marker under the cursor. If so, let the user drag it
    BreakpointInfo& bp = GetBreakpoint(editor->GetFileName().GetFullPath(), line + 1);
    if(bp.IsNull()) {
        return;
    }

    m_dragImage = new myDragImage(editor, bitmap, bp);
    m_dragImage->StartDrag();
}

void BreakptMgr::DropBreakpoint(const BreakpointInfo& bp, int newline)
{
    if(DelBreakpoint(bp.GetId())) {
        BreakpointInfo new_bp = bp;
        new_bp.lineno = newline;
        AddBreakpoint(new_bp);
    }
}

//---------------------------------------------------------

myDragImage::myDragImage(LEditor* ed, const wxBitmap& bitmap, const BreakpointInfo& bp)
    : wxDragImage(bitmap, wxCURSOR_POINT_LEFT)
    , editor(ed)
    , m_bp(bp)
{
    // In theory, we could pass a blank cursor to wxDragImage::BeginDrag
    // In practice, that doesn't seem to work, so do it here, and undo it in OnEndDrag()
    oldcursor = editor->GetCursor();
    editor->SetCursor(wxCursor(wxCURSOR_BLANK));
}

bool myDragImage::StartDrag()
{
    BeginDrag(wxPoint(0, 0), editor, false);
    wxPoint pt = editor->ScreenToClient(wxGetMousePosition());
    // Store the initial x position, as we know it must be in the bp margin
    m_startx = pt.x;
    Move(pt);
    Show();

    return false;
}

void myDragImage::OnMotion(wxMouseEvent& event)
{
    Move(event.GetPosition());
    event.Skip();
}

void myDragImage::OnEndDrag(wxMouseEvent& event)
{
    Hide();
    EndDrag();
    editor->SetCursor(oldcursor);
    editor->Disconnect(wxEVT_MOTION, wxMouseEventHandler(myDragImage::OnMotion), NULL, this);
    editor->Disconnect(wxEVT_LEFT_UP, wxMouseEventHandler(myDragImage::OnEndDrag), NULL, this);

    // If the cursor is within spitting distance of the bp margin, assume it's a genuine drop
    wxPoint pt = event.GetPosition();
    if((pt.x < 0) || ((pt.x - m_startx) > 10)) {
        return;
    }
    // Find the desired new line, and check it's different from the previous
    long pos = editor->PositionFromPoint(pt);
    int newline = editor->LineFromPosition(pos);
    if((newline + 1) != m_bp.lineno) {
        ManagerST::Get()->GetBreakpointsMgr()->DropBreakpoint(m_bp, newline);
    }
}

void BreakptMgr::RefreshBreakpointsForEditor(LEditor* editor) { DoRefreshFileBreakpoints(editor); }

bool BreakptMgr::IsDuplicate(const BreakpointInfo& bp, const std::vector<BreakpointInfo>& bpList)
{
    if(bp.debugger_id != wxNOT_FOUND) {
        return false; // A real breakpoint
    }

    wxString bpFile = bp.file;
    if(bpFile.IsEmpty() == false) {
        wxFileName bpFileName(bp.file);
        bpFileName.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_LONG);
        bpFile = bpFileName.GetFullPath();
    }
    for(size_t i = 0; i < bpList.size(); i++) {
        if(bpList.at(i).file.IsEmpty() == false) {
            wxFileName fn(bpList.at(i).file);
            fn.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_LONG);

            if(fn.GetFullPath() == bpFile && bp.lineno == bpList.at(i).lineno) return true;
        } else {
            if(bpList.at(i).file == bpFile && bp.lineno == bpList.at(i).lineno) return true;
        }
    }
    return false;
}

void BreakptMgr::DoRemoveDuplicateBreakpoints()
{
    std::vector<BreakpointInfo> bps;
    std::map<wxString, BreakpointInfo> uniqueNormalBreakpoints;
    for(size_t i = 0; i < m_bps.size(); ++i) {
        const BreakpointInfo& bi = m_bps.at(i);
        
        if(bi.bp_type != BP_type_break) {
            bps.push_back(bi);

        } else {
            
            if(bi.debugger_id != wxNOT_FOUND) {
                // an actual breakpoint, so it must be unique
                bps.push_back(bi);
                continue;
            }
            
            wxString key;

            /// construct a unique identifier for the breakpoint
            if(!bi.memory_address.IsEmpty()) {
                key << bi.memory_address;

            } else if(!bi.function_name.IsEmpty()) {
                key << bi.function_name;

            } else {
                key << bi.file << bi.lineno;
            }

            if(uniqueNormalBreakpoints.count(key)) {
                continue;
            } else {
                uniqueNormalBreakpoints.insert(std::make_pair(key, bi));
            }
        }
    }
    std::map<wxString, BreakpointInfo>::iterator iter = uniqueNormalBreakpoints.begin();
    for(; iter != uniqueNormalBreakpoints.end(); ++iter) {
        bps.push_back(iter->second);
    }
    m_bps.swap(bps);
}

int BreakptMgr::DelBreakpointByAddress(const wxString& address)
{
    std::vector<BreakpointInfo> allBps; // Start by finding all on the line
    GetBreakpoints(allBps);

    int breakpointsRemoved = 0;
    for(size_t i = 0; i < allBps.size(); i++) {
        BreakpointInfo& bp = allBps.at(i);
        if(bp.memory_address == address) {
            int bpId = (bp.debugger_id == -1 ? bp.internal_id : bp.debugger_id);

            if(bpId == wxID_CANCEL || bpId == BP_type_none) continue;

            if(DelBreakpoint(bpId)) {
                breakpointsRemoved++;
            }
        }
    }
    return breakpointsRemoved;
}

void BreakptMgr::GetAllMemoryBreakpoints(BreakpointInfoVec_t& memoryBps)
{
    BreakpointInfoVec_t allBps; // Start by finding all on the line
    GetBreakpoints(allBps);

    for(size_t i = 0; i < allBps.size(); i++) {
        BreakpointInfo& bp = allBps.at(i);
        if(!bp.memory_address.IsEmpty()) {
            memoryBps.push_back(bp);
        }
    }
}