Convert child item iterations to firstChild() and nextSibling().
[kdbg.git] / kdbg / exprwnd.cpp
blob6f55bb389479deb98a63fcfa8f1c5b2cdc5204f6
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 = firstChild();
157 while (child != 0) {
158 child->inferTypesOfChildren(typeTable);
159 child = child->nextSibling();
162 // if this is a pointer, get the type from the value (less the pointer)
163 if (m_varKind == VKpointer) {
164 if (isWcharT())
167 * wchart_t pointers must be treated as struct, because the array
168 * of characters is printed similar to how QStrings are decoded.
170 m_varKind = VKstruct;
171 setDelayedExpanding(false);
172 return;
174 #ifndef I_know_a_way_to_do_this_cleanly
175 return;
176 #else
177 const char* p = m_value.data();
178 const char* start = p;
179 // the type of the pointer shows up in the value (sometimes)
180 if (p == 0 || *p != '(')
181 return;
182 skipNested(p, '(', ')');
184 * We only recognize pointers to data "(int *)" but not pointers
185 * to functions "(void (*)())".
187 if (p-start < 3 && /* at least 3 chars necessary: (*) */
188 p[-2] != '*') /* skip back before the closing paren */
190 return;
192 const QString& typeName =
193 QString::fromLatin1(start+1, p-start-3) // minus 3 chars
194 .stripWhiteSpace();
195 m_type = typeTable.lookup(typeName);
196 if (m_type == 0) {
197 m_type = TypeInfo::unknownType();
199 #endif
200 } else if (m_varKind == VKstruct) {
201 // check if this is a base class part
202 if (m_nameKind == NKtype) {
203 const QString& typeName =
204 text.mid(1, text.length()-2); // strip < and >
205 m_type = typeTable.lookup(typeName);
207 /* if we don't have a type yet, get it from the base class */
208 if (m_type == 0) {
209 m_type = inferTypeFromBaseClass();
211 * If there is a known type now, it is the one from the
212 * first base class whose type we know.
217 * If we still don't have a type, the type is really unknown.
219 if (m_type == 0) {
220 m_type = TypeInfo::unknownType();
222 } // else
224 * This is not a base class part. We don't assign a type so
225 * that later we can ask gdb.
230 // the value contains the pointer type in parenthesis
231 bool VarTree::isWcharT() const
233 return m_value.startsWith("(const wchar_t *)") ||
234 m_value.startsWith("(wchar_t *)");
238 * Get the type of the first base class whose type we know.
240 TypeInfo* VarTree::inferTypeFromBaseClass()
242 if (m_varKind == VKstruct) {
243 VarTree* child = firstChild();
244 while (child != 0 &&
245 // only check base class parts (i.e. type names)
246 child->m_nameKind == NKtype)
248 if (child->m_type != 0 &&
249 child->m_type != TypeInfo::unknownType())
251 // got a type!
252 return child->m_type;
254 child = child->nextSibling();
257 return 0;
261 ExprWnd::ExprWnd(QWidget* parent, const char* name) :
262 KTreeView(parent, name),
263 maxValueWidth(0),
264 m_edit(this)
266 setNumCols(2);
268 connect(this, SIGNAL(expanded(int)), SLOT(slotExpandOrCollapse(int)));
269 connect(this, SIGNAL(collapsed(int)), SLOT(slotExpandOrCollapse(int)));
271 m_pixPointer = UserIcon("pointer.xpm");
272 if (m_pixPointer.isNull())
273 TRACE("Can't load pointer.xpm");
276 ExprWnd::~ExprWnd()
280 void ExprWnd::exprList(QStrList& exprs)
282 // ASSERT(exprs does deep-copies)
283 VarTree* item;
284 for (item = firstChild(); item != 0; item = item->nextSibling()) {
285 exprs.append(item->getText());
289 VarTree* ExprWnd::insertExpr(VarTree* expr, ProgramTypeTable& typeTable)
291 // append a new dummy expression
292 VarTree* display = new VarTree(expr->getText(), VarTree::NKplain);
293 insertItem(display);
295 // replace it right away
296 updateExpr(display, expr, typeTable);
297 return display;
300 void ExprWnd::updateExpr(VarTree* expr, ProgramTypeTable& typeTable)
302 // search the root variable
303 VarTree* item = firstChild();
304 while (item != 0 && item->getText() != expr->getText())
305 item = item->nextSibling();
306 if (item == 0) {
307 return;
309 // now update it
310 if (updateExprRec(item, expr, typeTable)) {
311 updateVisibleItems();
312 updateValuesWidth();
313 repaint();
315 collectUnknownTypes(item);
318 void ExprWnd::updateExpr(VarTree* display, VarTree* newValues, ProgramTypeTable& typeTable)
320 if (updateExprRec(display, newValues, typeTable) &&
321 display->isVisible())
323 updateVisibleItems();
324 updateValuesWidth();
325 repaint();
327 collectUnknownTypes(display);
331 * returns true if there's a visible change
333 bool ExprWnd::updateExprRec(VarTree* display, VarTree* newValues, ProgramTypeTable& typeTable)
335 bool isExpanded = display->isExpanded();
338 * If we are updating a pointer without children by a dummy, we don't
339 * collapse it, but simply insert the new children. This happens when a
340 * pointer has just been expanded by the user.
342 if (display->m_varKind == VarTree::VKpointer &&
343 display->childCount() == 0 &&
344 newValues->m_varKind == VarTree::VKdummy)
346 replaceChildren(display, newValues);
347 return isExpanded; /* no visible change if not expanded */
351 * If the display and newValues have different kind or if their number
352 * of children is different, replace the whole sub-tree.
354 if (// the next two lines mean: not(m_varKind remains unchanged)
355 !(newValues->m_varKind == VarTree::VKdummy ||
356 display->m_varKind == newValues->m_varKind)
358 (display->childCount() != newValues->childCount() &&
360 * If this is a pointer and newValues doesn't have children, we
361 * don't replace the sub-tree; instead, below we mark this
362 * sub-tree for requiring an update.
364 (display->m_varKind != VarTree::VKpointer ||
365 newValues->childCount() != 0)))
367 if (isExpanded) {
368 collapseSubTree(display, false);
371 // since children changed, it is likely that the type has also changed
372 display->m_type = 0; /* will re-evaluate the type */
374 // display the new value
375 updateSingleExpr(display, newValues);
376 replaceChildren(display, newValues);
378 // update the m_varKind
379 if (newValues->m_varKind != VarTree::VKdummy) {
380 display->m_varKind = newValues->m_varKind;
381 display->setDelayedExpanding(newValues->m_varKind == VarTree::VKpointer);
384 // get some types (after the new m_varKind has been set!)
385 display->inferTypesOfChildren(typeTable);
387 // (note that the new value might not have a sub-tree at all)
388 return display->m_valueChanged || isExpanded; /* no visible change if not expanded */
391 // display the new value
392 updateSingleExpr(display, newValues);
395 * If this is an expanded pointer, record it for being updated.
397 if (display->m_varKind == VarTree::VKpointer) {
398 if (isExpanded &&
399 // if newValues is a dummy, we have already updated this pointer
400 newValues->m_varKind != VarTree::VKdummy)
402 m_updatePtrs.append(display);
405 * If the visible sub-tree has children, but newValues doesn't, we
406 * can stop here.
408 if (newValues->childCount() == 0) {
409 return display->m_valueChanged;
413 ASSERT(display->childCount() == newValues->childCount());
415 // go for children
416 bool childChanged = false;
418 VarTree* vDisplay = display->firstChild();
419 VarTree* vNew = newValues->firstChild();
420 while (vDisplay != 0) {
421 // check whether the names are the same
422 if (strcmp(vDisplay->getText(), vNew->getText()) != 0) {
423 // set new name
424 vDisplay->setText(vNew->getText());
425 int i = itemRow(vDisplay);
426 if (i >= 0) {
427 updateCell(i, 0, true);
428 childChanged = true;
431 // recurse
432 if (updateExprRec(vDisplay, vNew, typeTable)) {
433 childChanged = true;
435 vDisplay = vDisplay->nextSibling();
436 vNew = vNew->nextSibling();
439 // update of children propagates only if this node is expanded
440 return display->m_valueChanged || (display->isExpanded() && childChanged);
443 void ExprWnd::updateSingleExpr(VarTree* display, VarTree* newValue)
446 * If newValues is a VKdummy, we are only interested in its children.
447 * No need to update anything here.
449 if (newValue->m_varKind == VarTree::VKdummy) {
450 return;
454 * If this node is a struct and we know its type then don't update its
455 * value now. This is a node for which we know how to find a nested
456 * value. So register the node for an update.
458 * wchar_t types are also treated specially here: We consider them
459 * as struct (has been set in inferTypesOfChildren()).
461 if (display->m_varKind == VarTree::VKstruct &&
462 display->m_type != 0 &&
463 display->m_type != TypeInfo::unknownType())
465 ASSERT(newValue->m_varKind == VarTree::VKstruct);
466 if (display->m_type == TypeInfo::wchartType())
469 * We do not copy the new pointer value to the destination right
470 * away, but consider it as the first part of the nested value.
471 * Then the display will change its color only when the new value
472 * is completed.
474 display->m_partialValue = formatWCharPointer(newValue->m_value);
476 else
477 display->m_partialValue = display->m_type->m_displayString[0];
478 m_updateStruct.append(display);
480 else
482 if (display->updateValue(newValue->m_value)) {
483 int i = itemRow(display);
484 if (i >= 0) {
485 updateCell(i, 1, true);
491 void ExprWnd::updateStructValue(VarTree* display)
493 ASSERT(display->m_varKind == VarTree::VKstruct);
495 if (display->updateValue(display->m_partialValue)) {
496 int i = itemRow(display);
497 if (i >= 0) {
498 updateValuesWidth();
499 updateCell(i, 1, true);
502 // reset the value
503 display->m_partialValue = "";
504 display->m_exprIndex = -1;
507 void ExprWnd::replaceChildren(VarTree* display, VarTree* newValues)
509 ASSERT(display->childCount() == 0 || display->m_varKind != VarTree::VKsimple);
511 // delete all children of display
512 while (VarTree* c = display->firstChild()) {
513 unhookSubtree(c);
514 display->removeChild(c);
515 delete c;
517 // insert copies of the newValues
518 for (VarTree* v = newValues->firstChild(); v != 0; v = v->nextSibling())
520 VarTree* vNew = new VarTree(v->getText(), v->m_nameKind);
521 vNew->m_varKind = v->m_varKind;
522 vNew->m_value = v->m_value;
523 vNew->m_type = v->m_type;
524 vNew->setDelayedExpanding(vNew->m_varKind == VarTree::VKpointer);
525 vNew->setExpanded(v->isExpanded());
526 display->appendChild(vNew);
527 // recurse
528 replaceChildren(vNew, v);
532 void ExprWnd::collectUnknownTypes(VarTree* var)
535 * forEveryItem does not scan the root item itself. So we must do it
536 * ourselves.
538 ASSERT(var->m_varKind != VarTree::VKpointer || var->m_nameKind != VarTree::NKtype);
539 if (var->m_type == 0 &&
540 var->m_varKind == VarTree::VKstruct &&
541 var->m_nameKind != VarTree::NKtype)
543 if (!var->isWcharT())
545 /* this struct node doesn't have a type yet: register it */
546 m_updateType.append(var);
548 else
550 var->m_type = TypeInfo::wchartType();
551 // see updateSingleExpr() why we move the value
552 var->m_partialValue = formatWCharPointer(var->m_value);
553 var->m_value.truncate(0);
554 m_updateStruct.append(var);
558 // add pointer pixmap to pointers
559 if (var->m_varKind == VarTree::VKpointer) {
560 var->setPixmap(m_pixPointer);
563 forEveryItem(collectUnknownTypes, this, var);
566 bool ExprWnd::collectUnknownTypes(KTreeViewItem* item, void* user)
568 VarTree* var = static_cast<VarTree*>(item);
569 ExprWnd* tree = static_cast<ExprWnd*>(user);
570 ASSERT(var->m_varKind != VarTree::VKpointer || var->m_nameKind != VarTree::NKtype);
571 if (var->m_type == 0 &&
572 var->m_varKind == VarTree::VKstruct &&
573 var->m_nameKind != VarTree::NKtype)
575 if (!var->isWcharT())
577 /* this struct node doesn't have a type yet: register it */
578 tree->m_updateType.append(var);
580 else
582 var->m_type = TypeInfo::wchartType();
583 // see updateSingleExpr() why we move the value
584 var->m_partialValue = formatWCharPointer(var->m_value);
585 var->m_value.truncate(0);
586 tree->m_updateStruct.append(var);
589 // add pointer pixmap to pointers
590 if (var->m_varKind == VarTree::VKpointer) {
591 var->setPixmap(tree->m_pixPointer);
593 return false;
596 QString ExprWnd::formatWCharPointer(QString value)
598 int pos = value.find(") ");
599 if (pos > 0)
600 value = value.mid(pos+2);
601 return value + " L";
605 VarTree* ExprWnd::topLevelExprByName(const char* name)
607 VarTree* item = firstChild();
608 while (item != 0 && item->getText() != name)
609 item = item->nextSibling();
611 return item;
614 VarTree* ExprWnd::ptrMemberByName(VarTree* v, const QString& name)
616 // v must be a pointer variable, must have children
617 if (v->m_varKind != VarTree::VKpointer || v->childCount() == 0)
618 return 0;
620 // the only child of v is the pointer value that represents the struct
621 VarTree* item = v->firstChild();
622 return memberByName(item, name);
625 VarTree* ExprWnd::memberByName(VarTree* v, const QString& name)
627 // search immediate children for name
628 VarTree* item = v->firstChild();
629 while (item != 0 && item->getText() != name)
630 item = item->nextSibling();
632 if (item != 0)
633 return item;
635 // try in base classes
636 item = v->firstChild();
637 while (item != 0 &&
638 item->m_nameKind == VarTree::NKtype)
640 v = memberByName(item, name);
641 if (v != 0)
642 return v;
643 item = item->nextSibling();
645 return 0;
648 void ExprWnd::removeExpr(VarTree* item)
650 unhookSubtree(item);
652 takeItem(item);
653 delete item;
655 updateValuesWidth();
658 void ExprWnd::unhookSubtree(VarTree* subTree)
660 // must remove any pointers scheduled for update from the list
661 unhookSubtree(m_updatePtrs, subTree);
662 unhookSubtree(m_updateType, subTree);
663 unhookSubtree(m_updateStruct, subTree);
664 emit removingItem(subTree);
667 void ExprWnd::unhookSubtree(QList<VarTree>& list, VarTree* subTree)
669 if (subTree == 0)
670 return;
672 VarTree* checkItem = list.first();
673 while (checkItem != 0) {
674 if (!subTree->isAncestorEq(checkItem)) {
675 // checkItem is not an item from subTree
676 // advance
677 checkItem = list.next();
678 } else {
679 // checkItem is an item from subTree
681 * If checkItem is the last item in the list, we need a special
682 * treatment, because remove()ing it steps the current item of
683 * the list in the "wrong" direction.
685 if (checkItem == list.getLast()) { // does not set current item
686 list.remove();
687 /* we deleted the last element, so we've finished */
688 checkItem = 0;
689 } else {
690 list.remove();
691 /* remove() advanced already */
692 checkItem = list.current();
698 void ExprWnd::clearPendingUpdates()
700 m_updatePtrs.clear();
701 m_updateType.clear();
702 m_updateStruct.clear();
705 VarTree* ExprWnd::nextUpdatePtr()
707 VarTree* ptr = m_updatePtrs.first();
708 if (ptr != 0) {
709 m_updatePtrs.remove();
711 return ptr;
714 VarTree* ExprWnd::nextUpdateType()
716 VarTree* ptr = m_updateType.first();
717 if (ptr != 0) {
718 m_updateType.remove();
720 return ptr;
723 VarTree* ExprWnd::nextUpdateStruct()
725 VarTree* ptr = m_updateStruct.first();
726 if (ptr != 0) {
727 m_updateStruct.remove();
729 return ptr;
732 void ExprWnd::paintCell(QPainter* painter, int row, int col)
734 if (col == 0) {
735 KTreeView::paintCell(painter, row, col);
736 } else {
737 VarTree* item = static_cast<VarTree*>(itemAt(row));
738 if (item != 0) {
739 item->paintValue(painter);
744 int ExprWnd::cellWidth(int col) const
746 if (col == 0) {
747 return KTreeView::cellWidth(col);
748 } else {
749 return maxValueWidth;
753 void ExprWnd::updateValuesWidth()
755 int maxW = 0;
756 forEveryVisibleItem(static_cast<KForEveryFunc>(&getMaxValueWidth), &maxW);
757 maxValueWidth = maxW;
758 updateTableSize();
761 // called by updateValuesWidth() for each item in the visible list
762 bool ExprWnd::getMaxValueWidth(KTreeViewItem* item, void* user)
764 int *maxW = (int *)user;
765 VarTree* v = static_cast<VarTree*>(item);
766 int w = v->valueWidth();
767 if(w > *maxW)
768 *maxW = w;
769 return false;
772 void ExprWnd::slotExpandOrCollapse(int)
774 updateValuesWidth();
777 void ExprWnd::editValue(int row, const QString& text)
779 int x;
780 colXPos(1, &x);
781 int y;
782 rowYPos(row, &y);
783 int w = cellWidth(1);
784 int h = cellHeight(row);
785 QScrollBar* sbV = static_cast<QScrollBar*>(child("table_sbV"));
788 * Make the edit widget at least 5 characters wide (but not wider than
789 * this widget). If less than half of this widget is used to display
790 * the text, scroll this widget so that half of it shows the text (or
791 * less than half of it if the text is shorter).
793 QFontMetrics metr = m_edit.font();
794 int wMin = metr.width("88888");
795 if (w < wMin)
796 w = wMin;
797 int wThis = width();
798 if (sbV->isVisible()) // subtract width of scrollbar
799 wThis -= sbV->width();
800 if (x >= wThis/2 && // less than half the width displays text
801 x+w > wThis) // not all text is visible
803 // scroll so that more text is visible
804 int wScroll = QMIN(x-wThis/2, x+w-wThis);
805 sbHor(xOffset()+wScroll);
806 colXPos(1, &x);
808 else if (x < 0)
810 // don't let the edit move out at the left
811 x = 0;
814 // make the edit box as wide as the visible column
815 QRect rect(x,y, wThis-x,h);
816 m_edit.setText(text);
817 m_edit.selectAll();
819 m_edit.setGeometry(rect);
820 m_edit.m_finished = false;
821 m_edit.m_row = row;
822 m_edit.show();
823 m_edit.setFocus();
826 bool ExprWnd::isEditing() const
828 return m_edit.isVisible();
832 ValueEdit::ValueEdit(ExprWnd* parent) :
833 QLineEdit(parent, "valueedit")
835 setFrame(false);
836 hide();
837 lower(); // lower the window below scrollbars
838 connect(parent, SIGNAL(selected(int)), SLOT(slotSelectionChanged()));
839 connect(parent, SIGNAL(collapsed(int)), SLOT(slotSelectionChanged()));
840 connect(parent, SIGNAL(expanded(int)), SLOT(slotSelectionChanged()));
841 connect(this, SIGNAL(done(int, const QString&)),
842 parent, SIGNAL(editValueCommitted(int, const QString&)));
845 ValueEdit::~ValueEdit()
849 void ValueEdit::terminate(bool commit)
851 TRACE(commit?"ValueEdit::terminate(true)":"ValueEdit::terminate(false)");
852 if (!m_finished)
854 m_finished = true;
855 hide(); // will call focusOutEvent, that's why we need m_finished
856 if (commit) {
857 emit done(m_row, text());
862 void ValueEdit::keyPressEvent(QKeyEvent *e)
864 if(e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter)
865 terminate(true);
866 else if(e->key() == Qt::Key_Escape)
867 terminate(false);
868 else
869 QLineEdit::keyPressEvent(e);
872 void ValueEdit::paintEvent(QPaintEvent* e)
874 QLineEdit::paintEvent(e);
876 QPainter p(this);
877 p.drawRect(rect());
880 void ValueEdit::focusOutEvent(QFocusEvent* ev)
882 TRACE("ValueEdit::focusOutEvent");
883 QFocusEvent* focusEv = static_cast<QFocusEvent*>(ev);
884 // Don't let a RMB close the editor
885 if (focusEv->reason() != QFocusEvent::Popup &&
886 focusEv->reason() != QFocusEvent::ActiveWindow)
888 terminate(true);
892 void ValueEdit::slotSelectionChanged()
894 TRACE("ValueEdit::slotSelectionChanged");
895 terminate(false);