Fix small memory leak by switch from QStack to QValueStack.
[kdbg.git] / kdbg / exprwnd.cpp
blob1f6ad0cf23052589e29a661558150508bdffaca9
1 // $Id$
3 // Copyright by Johannes Sixt
4 // This file is under GPL, the GNU General Public Licence
6 #include "exprwnd.h"
7 #include "exprwnd.moc"
8 #include "typetable.h"
9 #include <qstrlist.h>
10 #include <qpainter.h>
11 #include <qscrollbar.h>
12 #include <kapp.h>
13 #include <kiconloader.h> /* icons */
14 #ifdef HAVE_CONFIG_H
15 #include "config.h"
16 #endif
17 #include "mydebug.h"
19 VarTree::VarTree(const QString& name, NameKind aKind) :
20 KTreeViewItem(name),
21 m_varKind(VKsimple),
22 m_nameKind(aKind),
23 m_valueChanged(false),
24 m_type(0),
25 m_exprIndex(0),
26 m_exprIndexUseGuard(false)
30 VarTree::~VarTree()
34 void VarTree::paintValue(QPainter* p)
36 p->save();
37 int cellHeight = height(p->fontMetrics());
38 int textX = 2;
39 int textY = (cellHeight - p->fontMetrics().height()) / 2 +
40 p->fontMetrics().ascent();
42 if (m_valueChanged) {
43 p->setPen(red);
45 // p->setBackgroundColor(cg.base());
46 p->drawText(textX, textY, m_value, m_value.length());
47 p->restore();
50 int VarTree::valueWidth()
52 assert(owner != 0);
53 return owner->fontMetrics().width(m_value) + 4;
56 QString VarTree::computeExpr() const
58 assert(getParent() != 0);
59 // just to be sure
60 if (getParent() == 0)
61 return QString();
63 // top-level items are special
64 if (getParent()->getParent() == 0)
65 return getText();
67 // get parent expr
68 VarTree* par = static_cast<VarTree*>(getParent());
69 QString parentExpr = par->computeExpr();
71 /* don't add this item's name if this is a base class sub-item */
72 if (m_nameKind == NKtype) {
73 return parentExpr;
75 /* augment by this item's text */
76 QString result;
77 /* if this is an address, dereference it */
78 if (m_nameKind == NKaddress) {
79 ASSERT(par->m_varKind == VKpointer);
80 result = "*" + parentExpr;
81 return result;
83 switch (par->m_varKind) {
84 case VKarray:
86 QString index = getText();
87 int i = 1;
88 // skip past the index
89 while (index[i].isDigit())
90 i++;
92 * Some array indices are actually ranges due to repeated array
93 * values. We use the first index in these cases.
95 if (index[i] != ']') {
96 // remove second index
97 index.remove(i, index.length()-i-1);
99 result = "(" + parentExpr + ")" + index;
101 break;
102 case VKstruct:
103 result = "(" + parentExpr + ")." + getText();
104 break;
105 case VKsimple: /* parent can't be simple */
106 case VKpointer: /* handled in NKaddress */
107 case VKdummy: /* can't occur at all */
108 ASSERT(false);
109 result = parentExpr; /* paranoia */
110 break;
112 return result;
115 bool VarTree::isToplevelExpr() const
117 return getParent() != 0 && getParent()->getParent() == 0;
120 bool VarTree::isAncestorEq(const VarTree* child) const
122 const KTreeViewItem* c = child;
123 while (c != 0 && c != this) {
124 c = c->getParent();
126 return c != 0;
129 bool VarTree::updateValue(const QString& newValue)
131 // check whether the value changed
132 bool prevValueChanged = m_valueChanged;
133 m_valueChanged = false;
134 if (m_value != newValue) {
135 m_value = newValue;
136 m_valueChanged = true;
139 * We must repaint the cell if the value changed. If it did not change,
140 * we still must repaint the cell if the value changed previously,
141 * because the color of the display must be changed (from red to
142 * black).
144 return m_valueChanged || prevValueChanged;
147 void VarTree::inferTypesOfChildren(ProgramTypeTable& typeTable)
150 * Type inference works like this: We use type information of those
151 * children that have a type name in their name (base classes) or in
152 * their value (pointers)
155 // first recurse children
156 VarTree* child = static_cast<VarTree*>(getChild());
157 while (child != 0) {
158 child->inferTypesOfChildren(typeTable);
159 child = static_cast<VarTree*>(child->getSibling());
162 // if this is a pointer, get the type from the value (less the pointer)
163 if (m_varKind == VKpointer) {
164 #ifndef I_know_a_way_to_do_this_cleanly
165 return;
166 #else
167 const char* p = m_value.data();
168 const char* start = p;
169 // the type of the pointer shows up in the value (sometimes)
170 if (p == 0 || *p != '(')
171 return;
172 skipNested(p, '(', ')');
174 * We only recognize pointers to data "(int *)" but not pointers
175 * to functions "(void (*)())".
177 if (p-start < 3 && /* at least 3 chars necessary: (*) */
178 p[-2] != '*') /* skip back before the closing paren */
180 return;
182 const QString& typeName =
183 FROM_LATIN1(start+1, p-start-3) // minus 3 chars
184 .stripWhiteSpace();
185 m_type = typeTable.lookup(typeName);
186 if (m_type == 0) {
187 m_type = TypeInfo::unknownType();
189 #endif
190 } else if (m_varKind == VKstruct) {
191 // check if this is a base class part
192 if (m_nameKind == NKtype) {
193 const QString& typeName =
194 text.mid(1, text.length()-2); // strip < and >
195 m_type = typeTable.lookup(typeName);
197 /* if we don't have a type yet, get it from the base class */
198 if (m_type == 0) {
199 m_type = inferTypeFromBaseClass();
201 * If there is a known type now, it is the one from the
202 * first base class whose type we know.
207 * If we still don't have a type, the type is really unknown.
209 if (m_type == 0) {
210 m_type = TypeInfo::unknownType();
212 } // else
214 * This is not a base class part. We don't assign a type so
215 * that later we can ask gdb.
221 * Get the type of the first base class whose type we know.
223 TypeInfo* VarTree::inferTypeFromBaseClass()
225 if (m_varKind == VKstruct) {
226 VarTree* child = static_cast<VarTree*>(getChild());
227 while (child != 0 &&
228 // only check base class parts (i.e. type names)
229 child->m_nameKind == NKtype)
231 if (child->m_type != 0 &&
232 child->m_type != TypeInfo::unknownType())
234 // got a type!
235 return child->m_type;
237 child = static_cast<VarTree*>(child->getSibling());
240 return 0;
244 ExprWnd::ExprWnd(QWidget* parent, const char* name) :
245 KTreeView(parent, name),
246 maxValueWidth(0),
247 m_edit(this)
249 setNumCols(2);
251 connect(this, SIGNAL(expanded(int)), SLOT(slotExpandOrCollapse(int)));
252 connect(this, SIGNAL(collapsed(int)), SLOT(slotExpandOrCollapse(int)));
254 m_pixPointer = UserIcon("pointer.xpm");
255 if (m_pixPointer.isNull())
256 TRACE("Can't load pointer.xpm");
259 ExprWnd::~ExprWnd()
263 void ExprWnd::exprList(QStrList& exprs)
265 // ASSERT(exprs does deep-copies)
266 KTreeViewItem* item;
267 for (item = itemAt(0); item != 0; item = item->getSibling()) {
268 exprs.append(item->getText());
272 void ExprWnd::insertExpr(VarTree* expr)
274 // append the expression
275 insertItem(expr);
277 collectUnknownTypes(expr);
279 updateValuesWidth();
282 void ExprWnd::updateExpr(VarTree* expr)
284 // search the root variable
285 KPath path;
286 path.push(expr->getText());
287 KTreeViewItem* item = itemAt(path);
288 if (item == 0) {
289 return;
291 // now update it
292 if (updateExprRec(static_cast<VarTree*>(item), expr)) {
293 updateVisibleItems();
294 updateValuesWidth();
295 repaint();
297 collectUnknownTypes(static_cast<VarTree*>(item));
300 void ExprWnd::updateExpr(VarTree* display, VarTree* newValues)
302 if (updateExprRec(display, newValues) && display->isVisible()) {
303 updateVisibleItems();
304 updateValuesWidth();
305 repaint();
307 collectUnknownTypes(display);
311 * returns true if there's a visible change
313 bool ExprWnd::updateExprRec(VarTree* display, VarTree* newValues)
315 bool isExpanded = display->isExpanded();
318 * If we are updating a pointer without children by a dummy, we don't
319 * collapse it, but simply insert the new children. This happens when a
320 * pointer has just been expanded by the user.
322 if (display->m_varKind == VarTree::VKpointer &&
323 display->childCount() == 0 &&
324 newValues->m_varKind == VarTree::VKdummy)
326 replaceChildren(display, newValues);
327 return isExpanded; /* no visible change if not expanded */
331 * If the display and newValues have different kind or if their number
332 * of children is different, replace the whole sub-tree.
334 if (// the next two lines mean: not(m_varKind remains unchanged)
335 !(newValues->m_varKind == VarTree::VKdummy ||
336 display->m_varKind == newValues->m_varKind)
338 (display->childCount() != newValues->childCount() &&
340 * If this is a pointer and newValues doesn't have children, we
341 * don't replace the sub-tree; instead, below we mark this
342 * sub-tree for requiring an update.
344 (display->m_varKind != VarTree::VKpointer ||
345 newValues->childCount() != 0)))
347 if (isExpanded) {
348 collapseSubTree(display, false);
351 // since children changed, it is likely that the type has also changed
352 display->m_type = 0; /* will re-evaluate the type */
354 // display the new value
355 updateSingleExpr(display, newValues);
356 replaceChildren(display, newValues);
358 // update the m_varKind
359 if (newValues->m_varKind != VarTree::VKdummy) {
360 display->m_varKind = newValues->m_varKind;
361 display->setDelayedExpanding(newValues->m_varKind == VarTree::VKpointer);
364 // (note that the new value might not have a sub-tree at all)
365 return display->m_valueChanged || isExpanded; /* no visible change if not expanded */
368 // display the new value
369 updateSingleExpr(display, newValues);
372 * If this is an expanded pointer, record it for being updated.
374 if (display->m_varKind == VarTree::VKpointer) {
375 if (isExpanded &&
376 // if newValues is a dummy, we have already updated this pointer
377 newValues->m_varKind != VarTree::VKdummy)
379 m_updatePtrs.append(display);
382 * If the visible sub-tree has children, but newValues doesn't, we
383 * can stop here.
385 if (newValues->childCount() == 0) {
386 return display->m_valueChanged;
390 ASSERT(display->childCount() == newValues->childCount());
392 // go for children
393 bool childChanged = false;
395 VarTree* vDisplay = static_cast<VarTree*>(display->getChild());
396 VarTree* vNew = static_cast<VarTree*>(newValues->getChild());
397 while (vDisplay != 0) {
398 // check whether the names are the same
399 if (strcmp(vDisplay->getText(), vNew->getText()) != 0) {
400 // set new name
401 vDisplay->setText(vNew->getText());
402 int i = itemRow(vDisplay);
403 if (i >= 0) {
404 updateCell(i, 0, true);
405 childChanged = true;
408 // recurse
409 if (updateExprRec(vDisplay, vNew)) {
410 childChanged = true;
412 vDisplay = static_cast<VarTree*>(vDisplay->getSibling());
413 vNew = static_cast<VarTree*>(vNew->getSibling());
416 // update of children propagates only if this node is expanded
417 return display->m_valueChanged || (display->isExpanded() && childChanged);
420 void ExprWnd::updateSingleExpr(VarTree* display, VarTree* newValue)
423 * If newValues is a VKdummy, we are only interested in its children.
424 * No need to update anything here.
426 if (newValue->m_varKind == VarTree::VKdummy) {
427 return;
431 * If this node is a struct and we know its type then don't update its
432 * value now. This is a node for which we know how to find a nested
433 * value. So register the node for an update.
435 if (display->m_varKind == VarTree::VKstruct &&
436 display->m_type != 0 &&
437 display->m_type != TypeInfo::unknownType())
439 ASSERT(newValue->m_varKind == VarTree::VKstruct);
440 display->m_partialValue = display->m_type->m_displayString[0];
441 m_updateStruct.append(display);
443 else
445 if (display->updateValue(newValue->m_value)) {
446 int i = itemRow(display);
447 if (i >= 0) {
448 updateCell(i, 1, true);
454 void ExprWnd::updateStructValue(VarTree* display)
456 ASSERT(display->m_varKind == VarTree::VKstruct);
458 if (display->updateValue(display->m_partialValue)) {
459 int i = itemRow(display);
460 if (i >= 0) {
461 updateValuesWidth();
462 updateCell(i, 1, true);
465 // reset the value
466 display->m_partialValue = "";
467 display->m_exprIndex = -1;
470 void ExprWnd::replaceChildren(VarTree* display, VarTree* newValues)
472 ASSERT(display->childCount() == 0 || display->m_varKind != VarTree::VKsimple);
474 // delete all children of display
475 KTreeViewItem* c;
476 while ((c = display->getChild()) != 0) {
477 display->removeChild(c);
479 // insert copies of the newValues
480 for (c = newValues->getChild(); c != 0; c = c->getSibling()) {
481 VarTree* v = static_cast<VarTree*>(c);
482 VarTree* vNew = new VarTree(v->getText(), v->m_nameKind);
483 vNew->m_varKind = v->m_varKind;
484 vNew->m_value = v->m_value;
485 vNew->m_type = v->m_type;
486 vNew->setDelayedExpanding(vNew->m_varKind == VarTree::VKpointer);
487 vNew->setExpanded(v->isExpanded());
488 display->appendChild(vNew);
489 // recurse
490 replaceChildren(vNew, v);
494 void ExprWnd::collectUnknownTypes(VarTree* var)
497 * forEveryItem does not scan the root item itself. So we must do it
498 * ourselves.
500 ASSERT(var->m_varKind != VarTree::VKpointer || var->m_nameKind != VarTree::NKtype);
501 if (var->m_type == 0 &&
502 var->m_varKind == VarTree::VKstruct &&
503 var->m_nameKind != VarTree::NKtype)
505 /* this struct node doesn't have a type yet: register it */
506 m_updateType.append(var);
509 // add pointer pixmap to pointers
510 if (var->m_varKind == VarTree::VKpointer) {
511 var->setPixmap(m_pixPointer);
514 forEveryItem(collectUnknownTypes, this, var);
517 bool ExprWnd::collectUnknownTypes(KTreeViewItem* item, void* user)
519 VarTree* var = static_cast<VarTree*>(item);
520 ExprWnd* tree = static_cast<ExprWnd*>(user);
521 ASSERT(var->m_varKind != VarTree::VKpointer || var->m_nameKind != VarTree::NKtype);
522 if (var->m_type == 0 &&
523 var->m_varKind == VarTree::VKstruct &&
524 var->m_nameKind != VarTree::NKtype)
526 /* this struct node doesn't have a type yet: register it */
527 tree->m_updateType.append(var);
529 // add pointer pixmap to pointers
530 if (var->m_varKind == VarTree::VKpointer) {
531 var->setPixmap(tree->m_pixPointer);
533 return false;
537 VarTree* ExprWnd::topLevelExprByName(const char* name)
539 KPath path;
540 path.push(name);
541 KTreeViewItem* item = itemAt(path);
543 return static_cast<VarTree*>(item);
546 void ExprWnd::removeExpr(VarTree* item)
548 // must remove any pointers scheduled for update from the list
549 sweepList(m_updatePtrs, item);
550 sweepList(m_updateType, item);
551 sweepList(m_updateStruct, item);
553 takeItem(item);
554 delete item;
556 updateValuesWidth();
559 void ExprWnd::sweepList(QList<VarTree>& list, VarTree* subTree)
561 if (subTree == 0)
562 return;
564 VarTree* checkItem = list.first();
565 while (checkItem != 0) {
566 if (!subTree->isAncestorEq(checkItem)) {
567 // checkItem is not an item from subTree
568 // advance
569 checkItem = list.next();
570 } else {
571 // checkItem is an item from subTree
573 * If checkItem is the last item in the list, we need a special
574 * treatment, because remove()ing it steps the current item of
575 * the list in the "wrong" direction.
577 if (checkItem == list.getLast()) { // does not set current item
578 list.remove();
579 /* we deleted the last element, so we've finished */
580 checkItem = 0;
581 } else {
582 list.remove();
583 /* remove() advanced already */
584 checkItem = list.current();
590 QString ExprWnd::exprStringAt(int index)
592 KTreeViewItem* item = itemAt(index);
593 if (item == 0) return QString(); /* paranoia */
594 VarTree* expr = static_cast<VarTree*>(item);
595 return expr->computeExpr();
598 void ExprWnd::clearPendingUpdates()
600 m_updatePtrs.clear();
601 m_updateType.clear();
602 m_updateStruct.clear();
605 VarTree* ExprWnd::nextUpdatePtr()
607 VarTree* ptr = m_updatePtrs.first();
608 if (ptr != 0) {
609 m_updatePtrs.remove();
611 return ptr;
614 VarTree* ExprWnd::nextUpdateType()
616 VarTree* ptr = m_updateType.first();
617 if (ptr != 0) {
618 m_updateType.remove();
620 return ptr;
623 VarTree* ExprWnd::nextUpdateStruct()
625 VarTree* ptr = m_updateStruct.first();
626 if (ptr != 0) {
627 m_updateStruct.remove();
629 return ptr;
632 void ExprWnd::paintCell(QPainter* painter, int row, int col)
634 if (col == 0) {
635 KTreeView::paintCell(painter, row, col);
636 } else {
637 VarTree* item = static_cast<VarTree*>(itemAt(row));
638 if (item != 0) {
639 item->paintValue(painter);
644 int ExprWnd::cellWidth(int col) const
646 if (col == 0) {
647 return KTreeView::cellWidth(col);
648 } else {
649 return maxValueWidth;
653 void ExprWnd::updateValuesWidth()
655 int maxW = 0;
656 forEveryVisibleItem(static_cast<KForEveryFunc>(&getMaxValueWidth), &maxW);
657 maxValueWidth = maxW;
658 updateTableSize();
661 // called by updateValuesWidth() for each item in the visible list
662 bool ExprWnd::getMaxValueWidth(KTreeViewItem* item, void* user)
664 int *maxW = (int *)user;
665 VarTree* v = static_cast<VarTree*>(item);
666 int w = v->valueWidth();
667 if(w > *maxW)
668 *maxW = w;
669 return false;
672 void ExprWnd::slotExpandOrCollapse(int)
674 updateValuesWidth();
677 void ExprWnd::editValue(int row, const QString& text)
679 int x;
680 colXPos(1, &x);
681 int y;
682 rowYPos(row, &y);
683 int w = cellWidth(1);
684 int h = cellHeight(row);
685 QScrollBar* sbV = static_cast<QScrollBar*>(child("table_sbV"));
688 * Make the edit widget at least 5 characters wide (but not wider than
689 * this widget). If less than half of this widget is used to display
690 * the text, scroll this widget so that half of it shows the text (or
691 * less than half of it if the text is shorter).
693 QFontMetrics metr = m_edit.font();
694 int wMin = metr.width("88888");
695 if (w < wMin)
696 w = wMin;
697 int wThis = width();
698 if (sbV->isVisible()) // subtract width of scrollbar
699 wThis -= sbV->width();
700 if (x >= wThis/2 && // less than half the width displays text
701 x+w > wThis) // not all text is visible
703 // scroll so that more text is visible
704 int wScroll = QMIN(x-wThis/2, x+w-wThis);
705 sbHor(xOffset()+wScroll);
706 colXPos(1, &x);
708 else if (x < 0)
710 // don't let the edit move out at the left
711 x = 0;
714 // make the edit box as wide as the visible column
715 QRect rect(x,y, wThis-x,h);
716 m_edit.setText(text);
717 m_edit.selectAll();
719 m_edit.setGeometry(rect);
720 m_edit.m_finished = false;
721 m_edit.m_row = row;
722 m_edit.show();
723 m_edit.setFocus();
726 bool ExprWnd::isEditing() const
728 return m_edit.isVisible();
732 ValueEdit::ValueEdit(ExprWnd* parent) :
733 QLineEdit(parent, "valueedit")
735 setFrame(false);
736 hide();
737 lower(); // lower the window below scrollbars
738 connect(parent, SIGNAL(selected(int)), SLOT(slotSelectionChanged()));
739 connect(parent, SIGNAL(collapsed(int)), SLOT(slotSelectionChanged()));
740 connect(parent, SIGNAL(expanded(int)), SLOT(slotSelectionChanged()));
741 connect(this, SIGNAL(done(int, const QString&)),
742 parent, SIGNAL(editValueCommitted(int, const QString&)));
745 ValueEdit::~ValueEdit()
749 void ValueEdit::terminate(bool commit)
751 TRACE(commit?"ValueEdit::terminate(true)":"ValueEdit::terminate(false)");
752 if (!m_finished)
754 m_finished = true;
755 hide(); // will call focusOutEvent, that's why we need m_finished
756 if (commit) {
757 emit done(m_row, text());
762 void ValueEdit::keyPressEvent(QKeyEvent *e)
764 if(e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter)
765 terminate(true);
766 else if(e->key() == Qt::Key_Escape)
767 terminate(false);
768 else
769 QLineEdit::keyPressEvent(e);
772 void ValueEdit::paintEvent(QPaintEvent* e)
774 QLineEdit::paintEvent(e);
776 QPainter p(this);
777 p.drawRect(rect());
780 void ValueEdit::focusOutEvent(QFocusEvent* ev)
782 TRACE("ValueEdit::focusOutEvent");
783 QFocusEvent* focusEv = static_cast<QFocusEvent*>(ev);
784 // Don't let a RMB close the editor
785 if (focusEv->reason() != QFocusEvent::Popup &&
786 focusEv->reason() != QFocusEvent::ActiveWindow)
788 terminate(true);
792 void ValueEdit::slotSelectionChanged()
794 TRACE("ValueEdit::slotSelectionChanged");
795 terminate(false);