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>
13 #include <qfileinfo.h>
15 #include <qpopupmenu.h>
16 #include <kapplication.h>
17 #include <kiconloader.h>
18 #include <kglobalsettings.h>
19 #include <kmainwindow.h>
24 SourceWindow::SourceWindow(const QString
& fileName
, QWidget
* parent
, const char* name
) :
25 QTextEdit(parent
, name
),
33 m_pcinner
= UserIcon("pcinner");
34 m_pcup
= UserIcon("pcup");
35 m_brkena
= UserIcon("brkena");
36 m_brkdis
= UserIcon("brkdis");
37 m_brktmp
= UserIcon("brktmp");
38 m_brkcond
= UserIcon("brkcond");
39 m_brkorph
= UserIcon("brkorph");
40 setFont(KGlobalSettings::fixedFont());
42 setMargins(m_widthItems
+m_widthPlus
+m_widthLineNo
, 0, 0 ,0);
43 setAutoFormatting(AutoNone
);
44 setTextFormat(Qt::PlainText
);
46 connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
47 this, SLOT(update()));
48 connect(this, SIGNAL(cursorPositionChanged(int,int)), this, SLOT(cursorChanged(int)));
49 viewport()->installEventFilter(this);
51 // add a syntax highlighter
52 if (QRegExp("\\.(c(pp|c|\\+\\+)?|CC?|h(\\+\\+|h)?|HH?)$").search(m_fileName
) >= 0)
54 new HighlightCpp(this);
58 SourceWindow::~SourceWindow()
60 delete syntaxHighlighter();
63 bool SourceWindow::loadFile()
65 // first we load the code into QTextEdit
67 if (!f
.open(IO_ReadOnly
)) {
75 // then we copy it into our own m_sourceCode
77 m_sourceCode
.resize(n
);
78 m_rowToLine
.resize(n
);
79 for (int i
= 0; i
< n
; i
++) {
80 m_sourceCode
[i
].code
= text(i
);
83 m_lineItems
.resize(n
, 0);
85 // set a font for line numbers
86 m_lineNoFont
= currentFont();
87 m_lineNoFont
.setPixelSize(11);
92 void SourceWindow::reloadFile()
95 if (!f
.open(IO_ReadOnly
)) {
96 // open failed; leave alone
100 // read text into m_sourceCode
101 m_sourceCode
.clear(); /* clear old text */
107 m_sourceCode
.resize(paragraphs());
108 for (size_t i
= 0; i
< m_sourceCode
.size(); i
++) {
109 m_sourceCode
[i
].code
= text(i
);
111 // expanded lines are collapsed: move existing line items up
112 for (size_t i
= 0; i
< m_lineItems
.size(); i
++) {
113 if (m_rowToLine
[i
] != i
) {
114 m_lineItems
[m_rowToLine
[i
]] |= m_lineItems
[i
];
118 // allocate line items
119 m_lineItems
.resize(m_sourceCode
.size(), 0);
121 m_rowToLine
.resize(m_sourceCode
.size());
122 for (size_t i
= 0; i
< m_sourceCode
.size(); i
++)
125 // Highlighting was applied above when the text was inserted into widget,
126 // but at that time m_rowToLine was not corrected, yet, so that lines
127 // that previously were assembly were painted incorrectly.
128 if (syntaxHighlighter())
129 syntaxHighlighter()->rehighlight();
130 update(); // line numbers
133 void SourceWindow::scrollTo(int lineNo
, const DbgAddr
& address
)
135 if (lineNo
< 0 || lineNo
>= int(m_sourceCode
.size()))
138 int row
= lineToRow(lineNo
, address
);
142 void SourceWindow::scrollToRow(int row
)
144 setCursorPosition(row
, 0);
145 ensureCursorVisible();
148 void SourceWindow::drawFrame(QPainter
* p
)
150 QTextEdit::drawFrame(p
);
152 // and paragraph at the top is...
153 int top
= paragraphAt(QPoint(0,contentsY()));
154 int bot
= paragraphAt(QPoint(0,contentsY()+visibleHeight()-1));
156 bot
= paragraphs()-1;
160 // set a clip rectangle
161 int fw
= frameWidth();
162 QRect inside
= rect();
163 inside
.addCoords(fw
,fw
,-fw
,-fw
);
164 QRegion clip
= p
->clipRegion();
165 clip
&= QRegion(inside
);
166 p
->setClipRegion(clip
);
168 p
->setFont(m_lineNoFont
);
169 p
->setPen(colorGroup().text());
170 p
->eraseRect(inside
);
172 for (int row
= top
; row
<= bot
; row
++)
174 uchar item
= m_lineItems
[row
];
177 QRect r
= paragraphRect(row
);
178 QPoint pt
= contentsToViewport(r
.topLeft());
180 p
->translate(fw
, pt
.y()+viewport()->y());
183 // enabled breakpoint
184 int y
= (h
- m_brkena
.height())/2;
186 p
->drawPixmap(0,y
,m_brkena
);
188 if (item
& liBPdisabled
) {
189 // disabled breakpoint
190 int y
= (h
- m_brkdis
.height())/2;
192 p
->drawPixmap(0,y
,m_brkdis
);
194 if (item
& liBPtemporary
) {
195 // temporary breakpoint marker
196 int y
= (h
- m_brktmp
.height())/2;
198 p
->drawPixmap(0,y
,m_brktmp
);
200 if (item
& liBPconditional
) {
201 // conditional breakpoint marker
202 int y
= (h
- m_brkcond
.height())/2;
204 p
->drawPixmap(0,y
,m_brkcond
);
206 if (item
& liBPorphan
) {
207 // orphaned breakpoint marker
208 int y
= (h
- m_brkcond
.height())/2;
210 p
->drawPixmap(0,y
,m_brkorph
);
213 // program counter in innermost frame
214 int y
= (h
- m_pcinner
.height())/2;
216 p
->drawPixmap(0,y
,m_pcinner
);
219 // program counter somewhere up the stack
220 int y
= (h
- m_pcup
.height())/2;
222 p
->drawPixmap(0,y
,m_pcup
);
224 p
->translate(m_widthItems
, 0);
225 if (!isRowDisassCode(row
) && m_sourceCode
[rowToLine(row
)].canDisass
) {
229 p
->drawLine(x
-2, y
, x
+2, y
);
230 if (!isRowExpanded(row
)) {
231 p
->drawLine(x
, y
-2, x
, y
+2);
234 p
->translate(m_widthPlus
, 0);
235 if (!isRowDisassCode(row
)) {
236 p
->drawText(0, 0, m_widthLineNo
, h
, Qt::AlignRight
|Qt::AlignVCenter
,
237 QString().setNum(rowToLine(row
)+1));
244 void SourceWindow::updateLineItems(const KDebugger
* dbg
)
246 // clear outdated breakpoints
247 for (int i
= m_lineItems
.size()-1; i
>= 0; i
--) {
248 if (m_lineItems
[i
] & liBPany
) {
249 // check if this breakpoint still exists
250 int line
= rowToLine(i
);
251 TRACE(QString().sprintf("checking for bp at %d", line
));
252 KDebugger::BrkptROIterator bp
= dbg
->breakpointsBegin();
253 for (; bp
!= dbg
->breakpointsEnd(); ++bp
)
255 if (bp
->lineNo
== line
&&
256 fileNameMatches(bp
->fileName
) &&
257 lineToRow(line
, bp
->address
) == i
)
259 // yes it exists; mode is changed below
263 if (bp
== dbg
->breakpointsEnd()) {
264 /* doesn't exist anymore, remove it */
265 m_lineItems
[i
] &= ~liBPany
;
271 // add new breakpoints
272 for (KDebugger::BrkptROIterator bp
= dbg
->breakpointsBegin(); bp
!= dbg
->breakpointsEnd(); ++bp
)
274 if (fileNameMatches(bp
->fileName
)) {
275 TRACE(QString().sprintf("updating %s:%d", bp
->fileName
.data(), bp
->lineNo
));
277 if (i
< 0 || i
>= int(m_sourceCode
.size()))
279 // compute new line item flags for breakpoint
280 uchar flags
= bp
->enabled
? liBP
: liBPdisabled
;
282 flags
|= liBPtemporary
;
283 if (!bp
->condition
.isEmpty() || bp
->ignoreCount
!= 0)
284 flags
|= liBPconditional
;
285 if (bp
->isOrphaned())
288 int row
= lineToRow(i
, bp
->address
);
289 if ((m_lineItems
[row
] & liBPany
) != flags
) {
290 m_lineItems
[row
] &= ~liBPany
;
291 m_lineItems
[row
] |= flags
;
298 void SourceWindow::setPC(bool set
, int lineNo
, const DbgAddr
& address
, int frameNo
)
300 if (lineNo
< 0 || lineNo
>= int(m_sourceCode
.size())) {
304 int row
= lineToRow(lineNo
, address
);
306 uchar flag
= frameNo
== 0 ? liPC
: liPCup
;
308 // set only if not already set
309 if ((m_lineItems
[row
] & flag
) == 0) {
310 m_lineItems
[row
] |= flag
;
314 // clear only if not set
315 if ((m_lineItems
[row
] & flag
) != 0) {
316 m_lineItems
[row
] &= ~flag
;
322 void SourceWindow::find(const QString
& text
, bool caseSensitive
, FindDirection dir
)
324 ASSERT(dir
== 1 || dir
== -1);
325 if (QTextEdit::find(text
, caseSensitive
, false, dir
> 0))
327 // not found; wrap around
328 int para
= dir
> 0 ? 0 : paragraphs(), index
= 0;
329 QTextEdit::find(text
, caseSensitive
, false, dir
> 0, ¶
, &index
);
332 void SourceWindow::mousePressEvent(QMouseEvent
* ev
)
334 // we handle left and middle button
335 if (ev
->button() != Qt::LeftButton
&& ev
->button() != Qt::MidButton
)
337 QTextEdit::mousePressEvent(ev
);
342 QPoint p
= viewportToContents(QPoint(0, ev
->y() - viewport()->y()));
343 int row
= paragraphAt(p
);
347 if (ev
->x() > m_widthItems
+frameWidth())
349 if (isRowExpanded(row
)) {
350 actionCollapseRow(row
);
352 actionExpandRow(row
);
358 int line
= rowToLine(row
, &sourceRow
);
360 // find address if row is disassembled code
362 if (row
> sourceRow
) {
363 // get offset from source code line
364 int off
= row
- sourceRow
;
365 address
= m_sourceCode
[line
].disassAddr
[off
-1];
368 switch (ev
->button()) {
370 TRACE(QString().sprintf("left-clicked line %d", line
));
371 emit
clickedLeft(m_fileName
, line
, address
,
372 (ev
->state() & Qt::ShiftButton
) != 0);
375 TRACE(QString().sprintf("mid-clicked row %d", line
));
376 emit
clickedMid(m_fileName
, line
, address
);
382 void SourceWindow::keyPressEvent(QKeyEvent
* ev
)
388 actionExpandRow(m_curRow
);
391 actionCollapseRow(m_curRow
);
395 setCursorPosition(m_curRow
-1, 0);
399 if (m_curRow
< paragraphs()-1) {
400 setCursorPosition(m_curRow
+1, 0);
404 setCursorPosition(0, 0);
407 setCursorPosition(paragraphs()-1, 0);
411 top
= viewportToContents(QPoint(0,0));
412 top1
= paragraphAt(top
);
415 QTextEdit::keyPressEvent(ev
);
420 top
= viewportToContents(QPoint(0,0));
421 top2
= paragraphAt(top
);
422 setCursorPosition(m_curRow
+(top2
-top1
), 0);
426 static inline bool isident(QChar c
)
428 return c
.isLetterOrNumber() || c
.latin1() == '_';
431 bool SourceWindow::wordAtPoint(const QPoint
& p
, QString
& word
, QRect
& r
)
433 QPoint pv
= viewportToContents(p
- viewport()->pos());
434 int row
, col
= charAt(pv
, &row
);
435 if (row
< 0 || col
< 0)
438 // isolate the word at row, col
439 QString line
= text(row
);
440 if (!isident(line
[col
]))
444 while (begin
> 0 && isident(line
[begin
-1]))
448 while (col
< int(line
.length()) && isident(line
[col
]));
451 r
.addCoords(-5,-5,5,5);
452 word
= line
.mid(begin
, col
-begin
);
456 void SourceWindow::paletteChange(const QPalette
& oldPal
)
458 setFont(KGlobalSettings::fixedFont());
459 QTextEdit::paletteChange(oldPal
);
463 * Two file names (possibly full paths) match if the last parts - the file
466 bool SourceWindow::fileNameMatches(const QString
& other
)
468 return QFileInfo(other
).fileName() == QFileInfo(m_fileName
).fileName();
471 void SourceWindow::disassembled(int lineNo
, const std::list
<DisassembledCode
>& disass
)
473 TRACE("disassembled line " + QString().setNum(lineNo
));
474 if (lineNo
< 0 || lineNo
>= int(m_sourceCode
.size()))
477 SourceLine
& sl
= m_sourceCode
[lineNo
];
479 // copy disassembled code and its addresses
480 sl
.disass
.resize(disass
.size());
481 sl
.disassAddr
.resize(disass
.size());
482 sl
.canDisass
= !disass
.empty();
484 for (std::list
<DisassembledCode
>::const_iterator c
= disass
.begin(); c
!= disass
.end(); ++c
, ++i
)
486 QString code
= c
->code
;
487 while (code
.endsWith("\n"))
488 code
.truncate(code
.length()-1);
489 sl
.disass
[i
] = c
->address
.asString() + ' ' + code
;
490 sl
.disassAddr
[i
] = c
->address
;
493 int row
= lineToRow(lineNo
);
497 // clear expansion marker
502 int SourceWindow::rowToLine(int row
, int* sourceRow
)
504 int line
= row
>= 0 ? m_rowToLine
[row
] : -1;
505 if (sourceRow
!= 0) {
506 // search back until we hit the first entry with the current line number
507 while (row
> 0 && m_rowToLine
[row
-1] == line
)
515 * Rows showing diassembled code have the same line number as the
516 * corresponding source code line number. Therefore, the line numbers in
517 * m_rowToLine are monotonically increasing with blocks of equal line
518 * numbers for a source line and its disassembled code that follows it.
520 * Hence, m_rowToLine always obeys the following condition:
522 * m_rowToLine[i] <= i
525 int SourceWindow::lineToRow(int line
)
527 // line is zero-based!
529 assert(line
< int(m_rowToLine
.size()));
531 // quick test for common case
532 if (line
< 0 || m_rowToLine
[line
] == line
)
535 assert(m_rowToLine
[line
] < line
);
538 * Binary search between row == line and end of list. In the loop below
539 * we use the fact that the line numbers m_rowToLine do not contain
543 int h
= m_rowToLine
.size();
544 while (l
< h
&& m_rowToLine
[l
] != line
)
546 assert(h
== int(m_rowToLine
.size()) || m_rowToLine
[l
] < m_rowToLine
[h
]);
549 * We want to round down the midpoint so that we find the
550 * lowest row that belongs to the line we seek.
553 if (m_rowToLine
[mid
] <= line
)
558 // Found! Result is in l:
559 assert(m_rowToLine
[l
] == line
);
562 * We might not have hit the lowest index for the line.
564 while (l
> 0 && m_rowToLine
[l
-1] == line
)
570 int SourceWindow::lineToRow(int line
, const DbgAddr
& address
)
572 int row
= lineToRow(line
);
573 if (isRowExpanded(row
)) {
574 row
+= m_sourceCode
[line
].findAddressRowOffset(address
);
579 bool SourceWindow::isRowExpanded(int row
)
582 return row
< int(m_rowToLine
.size())-1 &&
583 m_rowToLine
[row
] == m_rowToLine
[row
+1];
586 bool SourceWindow::isRowDisassCode(int row
)
588 return row
> 0 && row
< int(m_rowToLine
.size()) &&
589 m_rowToLine
[row
] == m_rowToLine
[row
-1];
592 void SourceWindow::expandRow(int row
)
594 TRACE("expanding row " + QString().setNum(row
));
595 // get disassembled code
596 int line
= rowToLine(row
);
597 const std::vector
<QString
>& disass
= m_sourceCode
[line
].disass
;
599 // remove PC (must be set again in slot of signal expanded())
600 m_lineItems
[row
] &= ~(liPC
|liPCup
);
602 // adjust current row
603 if (m_curRow
> row
) {
604 m_curRow
+= disass
.size();
605 // highlight is moved automatically
609 setUpdatesEnabled(false);
611 for (size_t i
= 0; i
< disass
.size(); i
++) {
612 m_rowToLine
.insert(m_rowToLine
.begin()+row
, line
);
613 m_lineItems
.insert(m_lineItems
.begin()+row
, 0);
614 insertParagraph(disass
[i
], row
++);
616 setUpdatesEnabled(true);
617 viewport()->update();
618 update(); // line items
620 emit
expanded(line
); /* must set PC */
623 void SourceWindow::collapseRow(int row
)
625 TRACE("collapsing row " + QString().setNum(row
));
626 int line
= rowToLine(row
);
628 // find end of this block
630 while (end
< int(m_rowToLine
.size()) && m_rowToLine
[end
] == m_rowToLine
[row
]) {
634 // adjust current row
635 if (m_curRow
>= row
) {
637 if (m_curRow
< row
) // was m_curRow in disassembled code?
640 setUpdatesEnabled(false);
641 while (--end
>= row
) {
642 m_rowToLine
.erase(m_rowToLine
.begin()+end
);
643 m_lineItems
.erase(m_lineItems
.begin()+end
);
644 removeParagraph(end
);
646 setUpdatesEnabled(true);
647 viewport()->update();
648 update(); // line items
650 emit
collapsed(line
);
653 void SourceWindow::activeLine(int& line
, DbgAddr
& address
)
658 line
= rowToLine(row
, &sourceRow
);
659 if (row
> sourceRow
) {
660 int off
= row
- sourceRow
; /* offset from source line */
661 address
= m_sourceCode
[line
].disassAddr
[off
-1];
666 * Returns the offset from the line displaying the source code to
667 * the line containing the specified address. If the address is not
668 * found, 0 is returned.
670 int SourceWindow::SourceLine::findAddressRowOffset(const DbgAddr
& address
) const
672 if (address
.isEmpty())
675 for (size_t i
= 0; i
< disassAddr
.size(); i
++) {
676 if (disassAddr
[i
] == address
) {
677 // found exact address
680 if (disassAddr
[i
] > address
) {
682 * We have already advanced too far; the address is before this
683 * index, but obviously we haven't found an exact match
684 * earlier. address is somewhere between the displayed
685 * addresses. We return the previous line.
694 void SourceWindow::actionExpandRow(int row
)
696 if (row
< 0 || isRowExpanded(row
) || isRowDisassCode(row
))
700 int line
= rowToLine(row
);
701 const SourceLine
& sl
= m_sourceCode
[line
];
704 if (sl
.disass
.size() == 0) {
705 emit
disassemble(m_fileName
, line
);
711 void SourceWindow::actionCollapseRow(int row
)
713 if (row
< 0 || !isRowExpanded(row
) || isRowDisassCode(row
))
719 void SourceWindow::setTabWidth(int numChars
)
723 QFontMetrics
fm(currentFont());
725 int w
= fm
.width(s
.fill('x', numChars
));
729 void SourceWindow::cursorChanged(int row
)
734 if (m_curRow
>= 0 && m_curRow
< paragraphs())
735 clearParagraphBackground(m_curRow
);
737 setParagraphBackgroundColor(row
, colorGroup().background());
741 * We must override the context menu handling because QTextEdit's handling
742 * requires that it receives ownership of the popup menu; but the popup menu
743 * returned from the GUI factory is owned by the factory.
746 void SourceWindow::contextMenuEvent(QContextMenuEvent
* e
)
748 // get the context menu from the GUI factory
751 top
= top
->parentWidget();
752 while (!top
->isTopLevel());
753 KMainWindow
* mw
= static_cast<KMainWindow
*>(top
);
755 static_cast<QPopupMenu
*>(mw
->factory()->container("popup_files", mw
));
756 m
->exec(e
->globalPos());
759 bool SourceWindow::eventFilter(QObject
* watched
, QEvent
* e
)
761 if (e
->type() == QEvent::ContextMenu
&& watched
== viewport())
763 contextMenuEvent(static_cast<QContextMenuEvent
*>(e
));
766 return QTextEdit::eventFilter(watched
, e
);
769 HighlightCpp::HighlightCpp(SourceWindow
* srcWnd
) :
770 QSyntaxHighlighter(srcWnd
),
782 static const QString ckw
[] =
860 int HighlightCpp::highlightParagraph(const QString
& text
, int state
)
862 int row
= currentParagraph();
863 // highlight assembly lines
864 if (m_srcWnd
->isRowDisassCode(row
))
866 setFormat(0, text
.length(), Qt::blue
);
870 if (state
== -2) // initial state
873 // check for preprocessor line
874 if (state
== 0 && text
.stripWhiteSpace().startsWith("#"))
876 setFormat(0, text
.length(), QColor("dark green"));
880 // a font for keywords
881 QFont identFont
= textEdit()->currentFont();
882 identFont
.setBold(!identFont
.bold());
885 while (start
< text
.length())
892 setFormat(start
, end
-start
, QColor("gray50"));
895 end
= text
.find("*/", start
);
900 setFormat(start
, end
-start
, QColor("gray50"));
903 for (end
= start
+1; end
< int(text
.length()); end
++) {
904 if (text
[end
] == '\\') {
905 if (end
< int(text
.length()))
907 } else if (text
[end
] == text
[start
]) {
913 setFormat(start
, end
-start
, QColor("dark red"));
916 for (end
= start
+1; end
< int(text
.length()); end
++) {
917 if (!text
[end
].isLetterOrNumber() && text
[end
] != '_')
921 if (std::binary_search(ckw
, ckw
+ sizeof(ckw
)/sizeof(ckw
[0]),
922 text
.mid(start
, end
-start
)))
924 setFormat(start
, end
-start
, identFont
);
926 setFormat(start
, end
-start
, m_srcWnd
->colorGroup().text());
930 for (end
= start
; end
< int(text
.length()); end
++)
932 if (text
[end
] == '/')
934 if (end
+1 < int(text
.length())) {
935 if (text
[end
+1] == '/') {
936 state
= hlCommentLine
;
938 } else if (text
[end
+1] == '*') {
939 state
= hlCommentBlock
;
944 else if (text
[end
] == '"' || text
[end
] == '\'')
949 else if (text
[end
] >= 'A' && text
[end
] <= 'Z' ||
950 text
[end
] >= 'a' && text
[end
] <= 'z' ||
957 setFormat(start
, end
-start
, m_srcWnd
->colorGroup().text());
964 #include "sourcewnd.moc"