2 * Copyright Johannes Sixt
3 * This file is licensed under the GNU General Public License Version 2.
4 * See the file COPYING in the toplevel directory of the source directory.
9 #include <qtextstream.h>
14 #include <qpopupmenu.h>
16 #include <kiconloader.h>
17 #include <kglobalsettings.h>
18 #include <kmainwindow.h>
26 SourceWindow::SourceWindow(const char* fileName
, QWidget
* parent
, const char* name
) :
27 QTextEdit(parent
, name
),
34 m_pcinner
= UserIcon("pcinner");
35 m_pcup
= UserIcon("pcup");
36 m_brkena
= UserIcon("brkena");
37 m_brkdis
= UserIcon("brkdis");
38 m_brktmp
= UserIcon("brktmp");
39 m_brkcond
= UserIcon("brkcond");
40 m_brkorph
= UserIcon("brkorph");
41 setFont(KGlobalSettings::fixedFont());
43 setMargins(m_widthItems
+m_widthPlus
, 0, 0 ,0);
44 setAutoFormatting(AutoNone
);
45 setTextFormat(PlainText
);
47 connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
48 this, SLOT(update()));
49 connect(this, SIGNAL(cursorPositionChanged(int,int)), this, SLOT(cursorChanged(int)));
50 viewport()->installEventFilter(this);
52 // add a syntax highlighter
53 if (QRegExp("\\.(c(pp|c|\\+\\+)?|CC?|h(\\+\\+|h)?|HH?)$").search(m_fileName
))
55 new HighlightCpp(this);
59 SourceWindow::~SourceWindow()
61 delete syntaxHighlighter();
64 bool SourceWindow::loadFile()
66 // first we load the code into QTextEdit
68 if (!f
.open(IO_ReadOnly
)) {
76 // then we copy it into our own m_sourceCode
78 m_sourceCode
.resize(n
);
79 m_rowToLine
.resize(n
);
80 for (int i
= 0; i
< n
; i
++) {
81 m_sourceCode
[i
].code
= text(i
);
84 m_lineItems
.resize(n
, 0);
89 void SourceWindow::reloadFile()
92 if (!f
.open(IO_ReadOnly
)) {
93 // open failed; leave alone
97 // read text into m_sourceCode
98 m_sourceCode
.clear(); /* clear old text */
104 m_sourceCode
.resize(paragraphs());
105 for (size_t i
= 0; i
< m_sourceCode
.size(); i
++) {
106 m_sourceCode
[i
].code
= text(i
);
108 // allocate line items
109 m_lineItems
.resize(m_sourceCode
.size(), 0);
111 m_rowToLine
.resize(m_sourceCode
.size());
112 for (size_t i
= 0; i
< m_sourceCode
.size(); i
++)
116 void SourceWindow::scrollTo(int lineNo
, const DbgAddr
& address
)
118 if (lineNo
< 0 || lineNo
>= int(m_sourceCode
.size()))
121 int row
= lineToRow(lineNo
, address
);
125 void SourceWindow::scrollToRow(int row
)
127 setCursorPosition(row
, 0);
128 ensureCursorVisible();
131 void SourceWindow::drawFrame(QPainter
* p
)
133 QTextEdit::drawFrame(p
);
135 // and paragraph at the top is...
136 int top
= paragraphAt(QPoint(0,contentsY()));
137 int bot
= paragraphAt(QPoint(0,contentsY()+visibleHeight()-1));
139 bot
= paragraphs()-1;
143 // set a clip rectangle
144 int fw
= frameWidth();
145 QRect inside
= rect();
146 inside
.addCoords(fw
,fw
,-fw
,-fw
);
147 QRegion clip
= p
->clipRegion();
148 clip
&= QRegion(inside
);
149 p
->setClipRegion(clip
);
151 p
->setPen(colorGroup().text());
152 p
->eraseRect(inside
);
154 for (int row
= top
; row
<= bot
; row
++)
156 uchar item
= m_lineItems
[row
];
159 QRect r
= paragraphRect(row
);
160 QPoint pt
= contentsToViewport(r
.topLeft());
162 p
->translate(fw
, pt
.y()+viewport()->y());
165 // enabled breakpoint
166 int y
= (h
- m_brkena
.height())/2;
168 p
->drawPixmap(0,y
,m_brkena
);
170 if (item
& liBPdisabled
) {
171 // disabled breakpoint
172 int y
= (h
- m_brkdis
.height())/2;
174 p
->drawPixmap(0,y
,m_brkdis
);
176 if (item
& liBPtemporary
) {
177 // temporary breakpoint marker
178 int y
= (h
- m_brktmp
.height())/2;
180 p
->drawPixmap(0,y
,m_brktmp
);
182 if (item
& liBPconditional
) {
183 // conditional breakpoint marker
184 int y
= (h
- m_brkcond
.height())/2;
186 p
->drawPixmap(0,y
,m_brkcond
);
188 if (item
& liBPorphan
) {
189 // orphaned breakpoint marker
190 int y
= (h
- m_brkcond
.height())/2;
192 p
->drawPixmap(0,y
,m_brkorph
);
195 // program counter in innermost frame
196 int y
= (h
- m_pcinner
.height())/2;
198 p
->drawPixmap(0,y
,m_pcinner
);
201 // program counter somewhere up the stack
202 int y
= (h
- m_pcup
.height())/2;
204 p
->drawPixmap(0,y
,m_pcup
);
206 if (!isRowDisassCode(row
) && m_sourceCode
[rowToLine(row
)].canDisass
) {
208 p
->translate(m_widthItems
, 0);
211 p
->drawLine(x
-2, y
, x
+2, y
);
212 if (!isRowExpanded(row
)) {
213 p
->drawLine(x
, y
-2, x
, y
+2);
221 void SourceWindow::updateLineItems(const KDebugger
* dbg
)
223 // clear outdated breakpoints
224 for (int i
= m_lineItems
.size()-1; i
>= 0; i
--) {
225 if (m_lineItems
[i
] & liBPany
) {
226 // check if this breakpoint still exists
227 int line
= rowToLine(i
);
228 TRACE(QString().sprintf("checking for bp at %d", line
));
230 for (j
= dbg
->numBreakpoints()-1; j
>= 0; j
--) {
231 const Breakpoint
* bp
= dbg
->breakpoint(j
);
232 if (bp
->lineNo
== line
&&
233 fileNameMatches(bp
->fileName
) &&
234 lineToRow(line
, bp
->address
) == i
)
236 // yes it exists; mode is changed below
241 /* doesn't exist anymore, remove it */
242 m_lineItems
[i
] &= ~liBPany
;
248 // add new breakpoints
249 for (int j
= dbg
->numBreakpoints()-1; j
>= 0; j
--) {
250 const Breakpoint
* bp
= dbg
->breakpoint(j
);
251 if (fileNameMatches(bp
->fileName
)) {
252 TRACE(QString().sprintf("updating %s:%d", bp
->fileName
.data(), bp
->lineNo
));
254 if (i
< 0 || i
>= int(m_sourceCode
.size()))
256 // compute new line item flags for breakpoint
257 uchar flags
= bp
->enabled
? liBP
: liBPdisabled
;
259 flags
|= liBPtemporary
;
260 if (!bp
->condition
.isEmpty() || bp
->ignoreCount
!= 0)
261 flags
|= liBPconditional
;
262 if (bp
->isOrphaned())
265 int row
= lineToRow(i
, bp
->address
);
266 if ((m_lineItems
[row
] & liBPany
) != flags
) {
267 m_lineItems
[row
] &= ~liBPany
;
268 m_lineItems
[row
] |= flags
;
275 void SourceWindow::setPC(bool set
, int lineNo
, const DbgAddr
& address
, int frameNo
)
277 if (lineNo
< 0 || lineNo
>= int(m_sourceCode
.size())) {
281 int row
= lineToRow(lineNo
, address
);
283 uchar flag
= frameNo
== 0 ? liPC
: liPCup
;
285 // set only if not already set
286 if ((m_lineItems
[row
] & flag
) == 0) {
287 m_lineItems
[row
] |= flag
;
291 // clear only if not set
292 if ((m_lineItems
[row
] & flag
) != 0) {
293 m_lineItems
[row
] &= ~flag
;
299 void SourceWindow::find(const QString
& text
, bool caseSensitive
, FindDirection dir
)
301 ASSERT(dir
== 1 || dir
== -1);
302 if (QTextEdit::find(text
, caseSensitive
, false, dir
> 0))
304 // not found; wrap around
305 int para
= dir
> 0 ? 0 : paragraphs(), index
= 0;
306 QTextEdit::find(text
, caseSensitive
, false, dir
> 0, ¶
, &index
);
309 void SourceWindow::mousePressEvent(QMouseEvent
* ev
)
311 // we handle left and middle button
312 if (ev
->button() != LeftButton
&& ev
->button() != MidButton
)
314 QTextEdit::mousePressEvent(ev
);
319 QPoint p
= viewportToContents(QPoint(0, ev
->y() - viewport()->y()));
320 int row
= paragraphAt(p
);
324 if (ev
->x() > m_widthItems
+frameWidth())
326 if (isRowExpanded(row
)) {
327 actionCollapseRow(row
);
329 actionExpandRow(row
);
335 int line
= rowToLine(row
, &sourceRow
);
337 // find address if row is disassembled code
339 if (row
> sourceRow
) {
340 // get offset from source code line
341 int off
= row
- sourceRow
;
342 address
= m_sourceCode
[line
].disassAddr
[off
-1];
345 switch (ev
->button()) {
347 TRACE(QString().sprintf("left-clicked line %d", line
));
348 emit
clickedLeft(m_fileName
, line
, address
,
349 (ev
->state() & ShiftButton
) != 0);
352 TRACE(QString().sprintf("mid-clicked row %d", line
));
353 emit
clickedMid(m_fileName
, line
, address
);
359 void SourceWindow::keyPressEvent(QKeyEvent
* ev
)
365 actionExpandRow(m_curRow
);
368 actionCollapseRow(m_curRow
);
372 setCursorPosition(m_curRow
-1, 0);
376 if (m_curRow
< paragraphs()-1) {
377 setCursorPosition(m_curRow
+1, 0);
381 setCursorPosition(0, 0);
384 setCursorPosition(paragraphs()-1, 0);
388 top
= viewportToContents(QPoint(0,0));
389 top1
= paragraphAt(top
);
392 QTextEdit::keyPressEvent(ev
);
397 top
= viewportToContents(QPoint(0,0));
398 top2
= paragraphAt(top
);
399 setCursorPosition(m_curRow
+(top2
-top1
), 0);
403 static inline bool isident(QChar c
)
405 return c
.isLetterOrNumber() || c
.latin1() == '_';
408 bool SourceWindow::wordAtPoint(const QPoint
& p
, QString
& word
, QRect
& r
)
410 QPoint pv
= viewportToContents(p
- viewport()->pos());
411 int row
, col
= charAt(pv
, &row
);
412 if (row
< 0 || col
< 0)
415 // isolate the word at row, col
416 QString line
= text(row
);
417 if (!isident(line
[col
]))
421 while (begin
> 0 && isident(line
[begin
-1]))
425 while (col
< int(line
.length()) && isident(line
[col
]));
428 r
.addCoords(-5,-5,5,5);
429 word
= line
.mid(begin
, col
-begin
);
433 void SourceWindow::paletteChange(const QPalette
& oldPal
)
435 setFont(KGlobalSettings::fixedFont());
436 QTextEdit::paletteChange(oldPal
);
440 * Two file names (possibly full paths) match if the last parts - the file
443 bool SourceWindow::fileNameMatches(const QString
& other
)
445 const QString
& me
= fileName();
447 // check for null file names first
448 if (me
.isNull() || other
.isNull()) {
449 return me
.isNull() && other
.isNull();
453 * Get file names. Note: Either there is a slash, then skip it, or
454 * there is no slash, then -1 + 1 = 0!
456 int sme
= me
.findRev('/') + 1;
457 int sother
= other
.findRev('/') + 1;
458 return strcmp(me
.data() + sme
, other
.data() + sother
) == 0;
461 void SourceWindow::disassembled(int lineNo
, const QList
<DisassembledCode
>& disass
)
463 TRACE("disassembled line " + QString().setNum(lineNo
));
464 if (lineNo
< 0 || lineNo
>= int(m_sourceCode
.size()))
467 SourceLine
& sl
= m_sourceCode
[lineNo
];
469 // copy disassembled code and its addresses
470 sl
.disass
.resize(disass
.count());
471 sl
.disassAddr
.resize(disass
.count());
472 sl
.canDisass
= disass
.count() > 0;
473 for (uint i
= 0; i
< disass
.count(); i
++) {
474 const DisassembledCode
* c
=
475 const_cast<QList
<DisassembledCode
>&>(disass
).at(i
);
476 QString code
= c
->code
;
477 while (code
.endsWith("\n"))
478 code
.truncate(code
.length()-1);
479 sl
.disass
[i
] = c
->address
.asString() + ' ' + code
;
480 sl
.disassAddr
[i
] = c
->address
;
483 int row
= lineToRow(lineNo
);
487 // clear expansion marker
492 int SourceWindow::rowToLine(int row
, int* sourceRow
)
494 int line
= row
>= 0 ? m_rowToLine
[row
] : -1;
495 if (sourceRow
!= 0) {
496 // search back until we hit the first entry with the current line number
497 while (row
> 0 && m_rowToLine
[row
-1] == line
)
505 * Rows showing diassembled code have the same line number as the
506 * corresponding source code line number. Therefore, the line numbers in
507 * m_rowToLine are monotonically increasing with blocks of equal line
508 * numbers for a source line and its disassembled code that follows it.
510 * Hence, m_rowToLine always obeys the following condition:
512 * m_rowToLine[i] <= i
515 int SourceWindow::lineToRow(int line
)
517 // line is zero-based!
519 assert(line
< int(m_rowToLine
.size()));
521 // quick test for common case
522 if (line
< 0 || m_rowToLine
[line
] == line
)
525 assert(m_rowToLine
[line
] < line
);
528 * Binary search between row == line and end of list. In the loop below
529 * we use the fact that the line numbers m_rowToLine do not contain
533 int h
= m_rowToLine
.size();
534 while (l
< h
&& m_rowToLine
[l
] != line
)
536 assert(h
== int(m_rowToLine
.size()) || m_rowToLine
[l
] < m_rowToLine
[h
]);
539 * We want to round down the midpoint so that we find the
540 * lowest row that belongs to the line we seek.
543 if (m_rowToLine
[mid
] <= line
)
548 // Found! Result is in l:
549 assert(m_rowToLine
[l
] == line
);
552 * We might not have hit the lowest index for the line.
554 while (l
> 0 && m_rowToLine
[l
-1] == line
)
560 int SourceWindow::lineToRow(int line
, const DbgAddr
& address
)
562 int row
= lineToRow(line
);
563 if (isRowExpanded(row
)) {
564 row
+= m_sourceCode
[line
].findAddressRowOffset(address
);
569 bool SourceWindow::isRowExpanded(int row
)
572 return row
< int(m_rowToLine
.size())-1 &&
573 m_rowToLine
[row
] == m_rowToLine
[row
+1];
576 bool SourceWindow::isRowDisassCode(int row
)
578 return row
> 0 && row
< int(m_rowToLine
.size()) &&
579 m_rowToLine
[row
] == m_rowToLine
[row
-1];
582 void SourceWindow::expandRow(int row
)
584 TRACE("expanding row " + QString().setNum(row
));
585 // get disassembled code
586 int line
= rowToLine(row
);
587 const std::vector
<QString
>& disass
= m_sourceCode
[line
].disass
;
589 // remove PC (must be set again in slot of signal expanded())
590 m_lineItems
[row
] &= ~(liPC
|liPCup
);
592 // adjust current row
593 if (m_curRow
> row
) {
594 m_curRow
+= disass
.size();
595 // highlight is moved automatically
599 setUpdatesEnabled(false);
601 for (size_t i
= 0; i
< disass
.size(); i
++) {
602 m_rowToLine
.insert(m_rowToLine
.begin()+row
, line
);
603 m_lineItems
.insert(m_lineItems
.begin()+row
, 0);
604 insertParagraph(disass
[i
], row
++);
606 setUpdatesEnabled(true);
607 viewport()->update();
608 update(); // line items
610 emit
expanded(line
); /* must set PC */
613 void SourceWindow::collapseRow(int row
)
615 TRACE("collapsing row " + QString().setNum(row
));
616 int line
= rowToLine(row
);
618 // find end of this block
620 while (end
< int(m_rowToLine
.size()) && m_rowToLine
[end
] == m_rowToLine
[row
]) {
624 // adjust current row
625 if (m_curRow
>= row
) {
627 if (m_curRow
< row
) // was m_curRow in disassembled code?
630 setUpdatesEnabled(false);
631 while (--end
>= row
) {
632 m_rowToLine
.erase(m_rowToLine
.begin()+end
);
633 m_lineItems
.erase(m_lineItems
.begin()+end
);
634 removeParagraph(end
);
636 setUpdatesEnabled(true);
637 viewport()->update();
638 update(); // line items
640 emit
collapsed(line
);
643 void SourceWindow::activeLine(int& line
, DbgAddr
& address
)
648 line
= rowToLine(row
, &sourceRow
);
649 if (row
> sourceRow
) {
650 int off
= row
- sourceRow
; /* offset from source line */
651 address
= m_sourceCode
[line
].disassAddr
[off
-1];
656 * Returns the offset from the line displaying the source code to
657 * the line containing the specified address. If the address is not
658 * found, 0 is returned.
660 int SourceWindow::SourceLine::findAddressRowOffset(const DbgAddr
& address
) const
662 if (address
.isEmpty())
665 for (size_t i
= 0; i
< disassAddr
.size(); i
++) {
666 if (disassAddr
[i
] == address
) {
667 // found exact address
670 if (disassAddr
[i
] > address
) {
672 * We have already advanced too far; the address is before this
673 * index, but obviously we haven't found an exact match
674 * earlier. address is somewhere between the displayed
675 * addresses. We return the previous line.
684 void SourceWindow::actionExpandRow(int row
)
686 if (row
< 0 || isRowExpanded(row
) || isRowDisassCode(row
))
690 int line
= rowToLine(row
);
691 const SourceLine
& sl
= m_sourceCode
[line
];
694 if (sl
.disass
.size() == 0) {
695 emit
disassemble(m_fileName
, line
);
701 void SourceWindow::actionCollapseRow(int row
)
703 if (row
< 0 || !isRowExpanded(row
) || isRowDisassCode(row
))
709 void SourceWindow::setTabWidth(int numChars
)
713 QFontMetrics
fm(currentFont());
715 int w
= fm
.width(s
.fill('x', numChars
));
719 void SourceWindow::cursorChanged(int row
)
724 if (m_curRow
>= 0 && m_curRow
< paragraphs())
725 clearParagraphBackground(m_curRow
);
727 setParagraphBackgroundColor(row
, colorGroup().background());
733 * We must override the context menu handling because QTextEdit's handling
734 * requires that it receives ownership of the popup menu; but the popup menu
735 * returned from the GUI factory is owned by the factory.
738 void SourceWindow::contextMenuEvent(QContextMenuEvent
* e
)
740 // get the context menu from the GUI factory
743 top
= top
->parentWidget();
744 while (!top
->isTopLevel());
745 KMainWindow
* mw
= static_cast<KMainWindow
*>(top
);
747 static_cast<QPopupMenu
*>(mw
->factory()->container("popup_files", mw
));
748 m
->exec(e
->globalPos());
751 bool SourceWindow::eventFilter(QObject
* watched
, QEvent
* e
)
753 if (e
->type() == QEvent::ContextMenu
&& watched
== viewport())
755 contextMenuEvent(static_cast<QContextMenuEvent
*>(e
));
758 return QTextEdit::eventFilter(watched
, e
);
761 HighlightCpp::HighlightCpp(SourceWindow
* srcWnd
) :
762 QSyntaxHighlighter(srcWnd
),
774 static const QString ckw
[] =
852 int HighlightCpp::highlightParagraph(const QString
& text
, int state
)
854 int row
= currentParagraph();
855 // highlight assembly lines
856 if (m_srcWnd
->isRowDisassCode(row
))
858 setFormat(0, text
.length(), blue
);
862 if (state
== -2) // initial state
865 // check for preprocessor line
866 if (state
== 0 && text
.stripWhiteSpace().startsWith("#"))
868 setFormat(0, text
.length(), QColor("dark green"));
872 // a font for keywords
873 QFont identFont
= textEdit()->currentFont();
874 identFont
.setBold(!identFont
.bold());
877 while (start
< text
.length())
884 setFormat(start
, end
-start
, QColor("gray50"));
887 end
= text
.find("*/", start
);
892 setFormat(start
, end
-start
, QColor("gray50"));
895 for (end
= start
+1; end
< int(text
.length()); end
++) {
896 if (text
[end
] == '\\') {
897 if (end
< int(text
.length()))
899 } else if (text
[end
] == text
[start
]) {
905 setFormat(start
, end
-start
, QColor("dark red"));
908 for (end
= start
+1; end
< int(text
.length()); end
++) {
909 if (!text
[end
].isLetterOrNumber() && text
[end
] != '_')
913 if (std::binary_search(ckw
, ckw
+ sizeof(ckw
)/sizeof(ckw
[0]),
914 text
.mid(start
, end
-start
)))
916 setFormat(start
, end
-start
, identFont
);
918 setFormat(start
, end
-start
, m_srcWnd
->colorGroup().text());
922 for (end
= start
; end
< int(text
.length()); end
++)
924 if (text
[end
] == '/')
926 if (end
+1 < int(text
.length())) {
927 if (text
[end
+1] == '/') {
928 state
= hlCommentLine
;
930 } else if (text
[end
+1] == '*') {
931 state
= hlCommentBlock
;
936 else if (text
[end
] == '"' || text
[end
] == '\'')
941 else if (text
[end
] >= 'A' && text
[end
] <= 'Z' ||
942 text
[end
] >= 'a' && text
[end
] <= 'z' ||
949 setFormat(start
, end
-start
, m_srcWnd
->colorGroup().text());
956 #include "sourcewnd.moc"