changed to behave in same way as native win32 control and generic wxListCtrl when...
[wxWidgets.git] / src / generic / treectlg.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: treectlg.cpp
3 // Purpose: generic tree control implementation
4 // Author: Robert Roebling
5 // Created: 01/02/97
6 // Modified: 22/10/98 - almost total rewrite, simpler interface (VZ)
7 // Id: $Id$
8 // Copyright: (c) 1998 Robert Roebling and Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // =============================================================================
13 // declarations
14 // =============================================================================
15
16 // -----------------------------------------------------------------------------
17 // headers
18 // -----------------------------------------------------------------------------
19
20 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
21 #pragma implementation "treectlg.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #if wxUSE_TREECTRL
32
33 #include "wx/treebase.h"
34 #include "wx/generic/treectlg.h"
35 #include "wx/timer.h"
36 #include "wx/textctrl.h"
37 #include "wx/imaglist.h"
38 #include "wx/settings.h"
39 #include "wx/dcclient.h"
40
41 #include "wx/renderer.h"
42
43 #ifdef __WXMAC__
44 #include "wx/mac/private.h"
45 #endif
46
47 // -----------------------------------------------------------------------------
48 // array types
49 // -----------------------------------------------------------------------------
50
51 class WXDLLEXPORT wxGenericTreeItem;
52
53 WX_DEFINE_EXPORTED_ARRAY_PTR(wxGenericTreeItem *, wxArrayGenericTreeItems);
54
55 // ----------------------------------------------------------------------------
56 // constants
57 // ----------------------------------------------------------------------------
58
59 static const int NO_IMAGE = -1;
60
61 static const int PIXELS_PER_UNIT = 10;
62
63 // -----------------------------------------------------------------------------
64 // private classes
65 // -----------------------------------------------------------------------------
66
67 // timer used for enabling in-place edit
68 class WXDLLEXPORT wxTreeRenameTimer: public wxTimer
69 {
70 public:
71 // start editing the current item after half a second (if the mouse hasn't
72 // been clicked/moved)
73 enum { DELAY = 500 };
74
75 wxTreeRenameTimer( wxGenericTreeCtrl *owner );
76
77 virtual void Notify();
78
79 private:
80 wxGenericTreeCtrl *m_owner;
81
82 DECLARE_NO_COPY_CLASS(wxTreeRenameTimer)
83 };
84
85 // control used for in-place edit
86 class WXDLLEXPORT wxTreeTextCtrl: public wxTextCtrl
87 {
88 public:
89 wxTreeTextCtrl(wxGenericTreeCtrl *owner, wxGenericTreeItem *item);
90
91 protected:
92 void OnChar( wxKeyEvent &event );
93 void OnKeyUp( wxKeyEvent &event );
94 void OnKillFocus( wxFocusEvent &event );
95
96 bool AcceptChanges();
97 void Finish();
98
99 private:
100 wxGenericTreeCtrl *m_owner;
101 wxGenericTreeItem *m_itemEdited;
102 wxString m_startValue;
103 bool m_finished;
104
105 DECLARE_EVENT_TABLE()
106 DECLARE_NO_COPY_CLASS(wxTreeTextCtrl)
107 };
108
109 // timer used to clear wxGenericTreeCtrl::m_findPrefix if no key was pressed
110 // for a sufficiently long time
111 class WXDLLEXPORT wxTreeFindTimer : public wxTimer
112 {
113 public:
114 // reset the current prefix after half a second of inactivity
115 enum { DELAY = 500 };
116
117 wxTreeFindTimer( wxGenericTreeCtrl *owner ) { m_owner = owner; }
118
119 virtual void Notify() { m_owner->m_findPrefix.clear(); }
120
121 private:
122 wxGenericTreeCtrl *m_owner;
123
124 DECLARE_NO_COPY_CLASS(wxTreeFindTimer)
125 };
126
127 // a tree item
128 class WXDLLEXPORT wxGenericTreeItem
129 {
130 public:
131 // ctors & dtor
132 wxGenericTreeItem() { m_data = NULL; }
133 wxGenericTreeItem( wxGenericTreeItem *parent,
134 const wxString& text,
135 int image,
136 int selImage,
137 wxTreeItemData *data );
138
139 ~wxGenericTreeItem();
140
141 // trivial accessors
142 wxArrayGenericTreeItems& GetChildren() { return m_children; }
143
144 const wxString& GetText() const { return m_text; }
145 int GetImage(wxTreeItemIcon which = wxTreeItemIcon_Normal) const
146 { return m_images[which]; }
147 wxTreeItemData *GetData() const { return m_data; }
148
149 // returns the current image for the item (depending on its
150 // selected/expanded/whatever state)
151 int GetCurrentImage() const;
152
153 void SetText( const wxString &text );
154 void SetImage(int image, wxTreeItemIcon which) { m_images[which] = image; }
155 void SetData(wxTreeItemData *data) { m_data = data; }
156
157 void SetHasPlus(bool has = true) { m_hasPlus = has; }
158
159 void SetBold(bool bold) { m_isBold = bold; }
160
161 int GetX() const { return m_x; }
162 int GetY() const { return m_y; }
163
164 void SetX(int x) { m_x = x; }
165 void SetY(int y) { m_y = y; }
166
167 int GetHeight() const { return m_height; }
168 int GetWidth() const { return m_width; }
169
170 void SetHeight(int h) { m_height = h; }
171 void SetWidth(int w) { m_width = w; }
172
173 wxGenericTreeItem *GetParent() const { return m_parent; }
174
175 // operations
176 // deletes all children notifying the treectrl about it if !NULL
177 // pointer given
178 void DeleteChildren(wxGenericTreeCtrl *tree = NULL);
179
180 // get count of all children (and grand children if 'recursively')
181 size_t GetChildrenCount(bool recursively = true) const;
182
183 void Insert(wxGenericTreeItem *child, size_t index)
184 { m_children.Insert(child, index); }
185
186 void GetSize( int &x, int &y, const wxGenericTreeCtrl* );
187
188 // return the item at given position (or NULL if no item), onButton is
189 // true if the point belongs to the item's button, otherwise it lies
190 // on the item's label
191 wxGenericTreeItem *HitTest( const wxPoint& point,
192 const wxGenericTreeCtrl *,
193 int &flags,
194 int level );
195
196 void Expand() { m_isCollapsed = false; }
197 void Collapse() { m_isCollapsed = true; }
198
199 void SetHilight( bool set = true ) { m_hasHilight = set; }
200
201 // status inquiries
202 bool HasChildren() const { return !m_children.IsEmpty(); }
203 bool IsSelected() const { return m_hasHilight != 0; }
204 bool IsExpanded() const { return !m_isCollapsed; }
205 bool HasPlus() const { return m_hasPlus || HasChildren(); }
206 bool IsBold() const { return m_isBold != 0; }
207
208 // attributes
209 // get them - may be NULL
210 wxTreeItemAttr *GetAttributes() const { return m_attr; }
211 // get them ensuring that the pointer is not NULL
212 wxTreeItemAttr& Attr()
213 {
214 if ( !m_attr )
215 {
216 m_attr = new wxTreeItemAttr;
217 m_ownsAttr = true;
218 }
219 return *m_attr;
220 }
221 // set them
222 void SetAttributes(wxTreeItemAttr *attr)
223 {
224 if ( m_ownsAttr ) delete m_attr;
225 m_attr = attr;
226 m_ownsAttr = false;
227 }
228 // set them and delete when done
229 void AssignAttributes(wxTreeItemAttr *attr)
230 {
231 SetAttributes(attr);
232 m_ownsAttr = true;
233 }
234
235 private:
236 // since there can be very many of these, we save size by chosing
237 // the smallest representation for the elements and by ordering
238 // the members to avoid padding.
239 wxString m_text; // label to be rendered for item
240
241 wxTreeItemData *m_data; // user-provided data
242
243 wxArrayGenericTreeItems m_children; // list of children
244 wxGenericTreeItem *m_parent; // parent of this item
245
246 wxTreeItemAttr *m_attr; // attributes???
247
248 // tree ctrl images for the normal, selected, expanded and
249 // expanded+selected states
250 short m_images[wxTreeItemIcon_Max];
251
252 wxCoord m_x; // (virtual) offset from top
253 wxCoord m_y; // (virtual) offset from left
254 short m_width; // width of this item
255 unsigned char m_height; // height of this item
256
257 // use bitfields to save size
258 int m_isCollapsed :1;
259 int m_hasHilight :1; // same as focused
260 int m_hasPlus :1; // used for item which doesn't have
261 // children but has a [+] button
262 int m_isBold :1; // render the label in bold font
263 int m_ownsAttr :1; // delete attribute when done
264
265 DECLARE_NO_COPY_CLASS(wxGenericTreeItem)
266 };
267
268 // =============================================================================
269 // implementation
270 // =============================================================================
271
272 // ----------------------------------------------------------------------------
273 // private functions
274 // ----------------------------------------------------------------------------
275
276 // translate the key or mouse event flags to the type of selection we're
277 // dealing with
278 static void EventFlagsToSelType(long style,
279 bool shiftDown,
280 bool ctrlDown,
281 bool &is_multiple,
282 bool &extended_select,
283 bool &unselect_others)
284 {
285 is_multiple = (style & wxTR_MULTIPLE) != 0;
286 extended_select = shiftDown && is_multiple;
287 unselect_others = !(extended_select || (ctrlDown && is_multiple));
288 }
289
290 // check if the given item is under another one
291 static bool IsDescendantOf(wxGenericTreeItem *parent, wxGenericTreeItem *item)
292 {
293 while ( item )
294 {
295 if ( item == parent )
296 {
297 // item is a descendant of parent
298 return true;
299 }
300
301 item = item->GetParent();
302 }
303
304 return false;
305 }
306
307 // -----------------------------------------------------------------------------
308 // wxTreeRenameTimer (internal)
309 // -----------------------------------------------------------------------------
310
311 wxTreeRenameTimer::wxTreeRenameTimer( wxGenericTreeCtrl *owner )
312 {
313 m_owner = owner;
314 }
315
316 void wxTreeRenameTimer::Notify()
317 {
318 m_owner->OnRenameTimer();
319 }
320
321 //-----------------------------------------------------------------------------
322 // wxTreeTextCtrl (internal)
323 //-----------------------------------------------------------------------------
324
325 BEGIN_EVENT_TABLE(wxTreeTextCtrl,wxTextCtrl)
326 EVT_CHAR (wxTreeTextCtrl::OnChar)
327 EVT_KEY_UP (wxTreeTextCtrl::OnKeyUp)
328 EVT_KILL_FOCUS (wxTreeTextCtrl::OnKillFocus)
329 END_EVENT_TABLE()
330
331 wxTreeTextCtrl::wxTreeTextCtrl(wxGenericTreeCtrl *owner,
332 wxGenericTreeItem *item)
333 : m_itemEdited(item), m_startValue(item->GetText())
334 {
335 m_owner = owner;
336 m_finished = false;
337
338 int w = m_itemEdited->GetWidth(),
339 h = m_itemEdited->GetHeight();
340
341 int x, y;
342 m_owner->CalcScrolledPosition(item->GetX(), item->GetY(), &x, &y);
343
344 int image_h = 0,
345 image_w = 0;
346
347 int image = item->GetCurrentImage();
348 if ( image != NO_IMAGE )
349 {
350 if ( m_owner->m_imageListNormal )
351 {
352 m_owner->m_imageListNormal->GetSize( image, image_w, image_h );
353 image_w += 4;
354 }
355 else
356 {
357 wxFAIL_MSG(_T("you must create an image list to use images!"));
358 }
359 }
360
361 // FIXME: what are all these hardcoded 4, 8 and 11s really?
362 x += image_w;
363 w -= image_w + 4;
364
365 (void)Create(m_owner, wxID_ANY, m_startValue,
366 wxPoint(x - 4, y - 4), wxSize(w + 11, h + 8));
367 }
368
369 bool wxTreeTextCtrl::AcceptChanges()
370 {
371 const wxString value = GetValue();
372
373 if ( value == m_startValue )
374 {
375 // nothing changed, always accept
376 return true;
377 }
378
379 if ( !m_owner->OnRenameAccept(m_itemEdited, value) )
380 {
381 // vetoed by the user
382 return false;
383 }
384
385 // accepted, do rename the item
386 m_owner->SetItemText(m_itemEdited, value);
387
388 return true;
389 }
390
391 void wxTreeTextCtrl::Finish()
392 {
393 if ( !m_finished )
394 {
395 m_owner->ResetTextControl();
396
397 wxPendingDelete.Append(this);
398
399 m_finished = true;
400
401 m_owner->SetFocus(); // This doesn't work. TODO.
402 }
403 }
404
405 void wxTreeTextCtrl::OnChar( wxKeyEvent &event )
406 {
407 switch ( event.m_keyCode )
408 {
409 case WXK_RETURN:
410 if ( AcceptChanges() )
411 {
412 // Close the text control, changes were accepted
413 Finish();
414 }
415 // else do nothing, do not accept and do not close
416
417 break;
418
419 case WXK_ESCAPE:
420 Finish();
421 m_owner->OnRenameCancelled(m_itemEdited);
422 break;
423
424 default:
425 event.Skip();
426 }
427 }
428
429 void wxTreeTextCtrl::OnKeyUp( wxKeyEvent &event )
430 {
431 if ( !m_finished )
432 {
433 // auto-grow the textctrl:
434 wxSize parentSize = m_owner->GetSize();
435 wxPoint myPos = GetPosition();
436 wxSize mySize = GetSize();
437 int sx, sy;
438 GetTextExtent(GetValue() + _T("M"), &sx, &sy);
439 if (myPos.x + sx > parentSize.x)
440 sx = parentSize.x - myPos.x;
441 if (mySize.x > sx)
442 sx = mySize.x;
443 SetSize(sx, wxDefaultCoord);
444 }
445
446 event.Skip();
447 }
448
449 void wxTreeTextCtrl::OnKillFocus( wxFocusEvent &event )
450 {
451 if ( !m_finished )
452 {
453 AcceptChanges();
454 // We must finish regardless of success, otherwise we'll get
455 // focus problems:
456 Finish();
457 }
458
459 // We must let the native text control handle focus, too, otherwise
460 // it could have problems with the cursor (e.g., in wxGTK):
461 event.Skip();
462 }
463
464 // -----------------------------------------------------------------------------
465 // wxGenericTreeItem
466 // -----------------------------------------------------------------------------
467
468 wxGenericTreeItem::wxGenericTreeItem(wxGenericTreeItem *parent,
469 const wxString& text,
470 int image, int selImage,
471 wxTreeItemData *data)
472 : m_text(text)
473 {
474 m_images[wxTreeItemIcon_Normal] = image;
475 m_images[wxTreeItemIcon_Selected] = selImage;
476 m_images[wxTreeItemIcon_Expanded] = NO_IMAGE;
477 m_images[wxTreeItemIcon_SelectedExpanded] = NO_IMAGE;
478
479 m_data = data;
480 m_x = m_y = 0;
481
482 m_isCollapsed = true;
483 m_hasHilight = false;
484 m_hasPlus = false;
485 m_isBold = false;
486
487 m_parent = parent;
488
489 m_attr = (wxTreeItemAttr *)NULL;
490 m_ownsAttr = false;
491
492 // We don't know the height here yet.
493 m_width = 0;
494 m_height = 0;
495 }
496
497 wxGenericTreeItem::~wxGenericTreeItem()
498 {
499 delete m_data;
500
501 if (m_ownsAttr) delete m_attr;
502
503 wxASSERT_MSG( m_children.IsEmpty(),
504 wxT("please call DeleteChildren() before deleting the item") );
505 }
506
507 void wxGenericTreeItem::DeleteChildren(wxGenericTreeCtrl *tree)
508 {
509 size_t count = m_children.Count();
510 for ( size_t n = 0; n < count; n++ )
511 {
512 wxGenericTreeItem *child = m_children[n];
513 if (tree)
514 tree->SendDeleteEvent(child);
515
516 child->DeleteChildren(tree);
517 delete child;
518 }
519
520 m_children.Empty();
521 }
522
523 void wxGenericTreeItem::SetText( const wxString &text )
524 {
525 m_text = text;
526 }
527
528 size_t wxGenericTreeItem::GetChildrenCount(bool recursively) const
529 {
530 size_t count = m_children.Count();
531 if ( !recursively )
532 return count;
533
534 size_t total = count;
535 for (size_t n = 0; n < count; ++n)
536 {
537 total += m_children[n]->GetChildrenCount();
538 }
539
540 return total;
541 }
542
543 void wxGenericTreeItem::GetSize( int &x, int &y,
544 const wxGenericTreeCtrl *theButton )
545 {
546 int bottomY=m_y+theButton->GetLineHeight(this);
547 if ( y < bottomY ) y = bottomY;
548 int width = m_x + m_width;
549 if ( x < width ) x = width;
550
551 if (IsExpanded())
552 {
553 size_t count = m_children.Count();
554 for ( size_t n = 0; n < count; ++n )
555 {
556 m_children[n]->GetSize( x, y, theButton );
557 }
558 }
559 }
560
561 wxGenericTreeItem *wxGenericTreeItem::HitTest(const wxPoint& point,
562 const wxGenericTreeCtrl *theCtrl,
563 int &flags,
564 int level)
565 {
566 // for a hidden root node, don't evaluate it, but do evaluate children
567 if ( !(level == 0 && theCtrl->HasFlag(wxTR_HIDE_ROOT)) )
568 {
569 // evaluate the item
570 int h = theCtrl->GetLineHeight(this);
571 if ((point.y > m_y) && (point.y < m_y + h))
572 {
573 int y_mid = m_y + h/2;
574 if (point.y < y_mid )
575 flags |= wxTREE_HITTEST_ONITEMUPPERPART;
576 else
577 flags |= wxTREE_HITTEST_ONITEMLOWERPART;
578
579 int xCross = m_x - theCtrl->GetSpacing();
580 #ifdef __WXMAC__
581 // according to the drawing code the triangels are drawn
582 // at -4 , -4 from the position up to +10/+10 max
583 if ((point.x > xCross-4) && (point.x < xCross+10) &&
584 (point.y > y_mid-4) && (point.y < y_mid+10) &&
585 HasPlus() && theCtrl->HasButtons() )
586 #else
587 // 5 is the size of the plus sign
588 if ((point.x > xCross-6) && (point.x < xCross+6) &&
589 (point.y > y_mid-6) && (point.y < y_mid+6) &&
590 HasPlus() && theCtrl->HasButtons() )
591 #endif
592 {
593 flags |= wxTREE_HITTEST_ONITEMBUTTON;
594 return this;
595 }
596
597 if ((point.x >= m_x) && (point.x <= m_x+m_width))
598 {
599 int image_w = -1;
600 int image_h;
601
602 // assuming every image (normal and selected) has the same size!
603 if ( (GetImage() != NO_IMAGE) && theCtrl->m_imageListNormal )
604 theCtrl->m_imageListNormal->GetSize(GetImage(),
605 image_w, image_h);
606
607 if ((image_w != -1) && (point.x <= m_x + image_w + 1))
608 flags |= wxTREE_HITTEST_ONITEMICON;
609 else
610 flags |= wxTREE_HITTEST_ONITEMLABEL;
611
612 return this;
613 }
614
615 if (point.x < m_x)
616 flags |= wxTREE_HITTEST_ONITEMINDENT;
617 if (point.x > m_x+m_width)
618 flags |= wxTREE_HITTEST_ONITEMRIGHT;
619
620 return this;
621 }
622
623 // if children are expanded, fall through to evaluate them
624 if (m_isCollapsed) return (wxGenericTreeItem*) NULL;
625 }
626
627 // evaluate children
628 size_t count = m_children.Count();
629 for ( size_t n = 0; n < count; n++ )
630 {
631 wxGenericTreeItem *res = m_children[n]->HitTest( point,
632 theCtrl,
633 flags,
634 level + 1 );
635 if ( res != NULL )
636 return res;
637 }
638
639 return (wxGenericTreeItem*) NULL;
640 }
641
642 int wxGenericTreeItem::GetCurrentImage() const
643 {
644 int image = NO_IMAGE;
645 if ( IsExpanded() )
646 {
647 if ( IsSelected() )
648 {
649 image = GetImage(wxTreeItemIcon_SelectedExpanded);
650 }
651
652 if ( image == NO_IMAGE )
653 {
654 // we usually fall back to the normal item, but try just the
655 // expanded one (and not selected) first in this case
656 image = GetImage(wxTreeItemIcon_Expanded);
657 }
658 }
659 else // not expanded
660 {
661 if ( IsSelected() )
662 image = GetImage(wxTreeItemIcon_Selected);
663 }
664
665 // maybe it doesn't have the specific image we want,
666 // try the default one instead
667 if ( image == NO_IMAGE ) image = GetImage();
668
669 return image;
670 }
671
672 // -----------------------------------------------------------------------------
673 // wxGenericTreeCtrl implementation
674 // -----------------------------------------------------------------------------
675
676 IMPLEMENT_DYNAMIC_CLASS(wxGenericTreeCtrl, wxScrolledWindow)
677
678 BEGIN_EVENT_TABLE(wxGenericTreeCtrl,wxScrolledWindow)
679 EVT_PAINT (wxGenericTreeCtrl::OnPaint)
680 EVT_MOUSE_EVENTS (wxGenericTreeCtrl::OnMouse)
681 EVT_CHAR (wxGenericTreeCtrl::OnChar)
682 EVT_SET_FOCUS (wxGenericTreeCtrl::OnSetFocus)
683 EVT_KILL_FOCUS (wxGenericTreeCtrl::OnKillFocus)
684 EVT_TREE_ITEM_GETTOOLTIP(wxID_ANY, wxGenericTreeCtrl::OnGetToolTip)
685 END_EVENT_TABLE()
686
687 #if !defined(__WXMSW__) || defined(__WXUNIVERSAL__)
688 /*
689 * wxTreeCtrl has to be a real class or we have problems with
690 * the run-time information.
691 */
692
693 IMPLEMENT_DYNAMIC_CLASS(wxTreeCtrl, wxGenericTreeCtrl)
694 #endif
695
696 // -----------------------------------------------------------------------------
697 // construction/destruction
698 // -----------------------------------------------------------------------------
699
700 void wxGenericTreeCtrl::Init()
701 {
702 m_current = m_key_current = m_anchor = m_select_me = (wxGenericTreeItem *) NULL;
703 m_hasFocus = false;
704 m_dirty = false;
705
706 m_lineHeight = 10;
707 m_indent = 15;
708 m_spacing = 18;
709
710 m_hilightBrush = new wxBrush
711 (
712 wxSystemSettings::GetColour
713 (
714 wxSYS_COLOUR_HIGHLIGHT
715 ),
716 wxSOLID
717 );
718
719 m_hilightUnfocusedBrush = new wxBrush
720 (
721 wxSystemSettings::GetColour
722 (
723 wxSYS_COLOUR_BTNSHADOW
724 ),
725 wxSOLID
726 );
727
728 m_imageListNormal = m_imageListButtons =
729 m_imageListState = (wxImageList *) NULL;
730 m_ownsImageListNormal = m_ownsImageListButtons =
731 m_ownsImageListState = false;
732
733 m_dragCount = 0;
734 m_isDragging = false;
735 m_dropTarget = m_oldSelection = NULL;
736 m_underMouse = NULL;
737 m_textCtrl = NULL;
738
739 m_renameTimer = NULL;
740 m_freezeCount = 0;
741
742 m_findTimer = NULL;
743
744 m_lastOnSame = false;
745
746 #if defined( __WXMAC__ ) && __WXMAC_CARBON__
747 m_normalFont.MacCreateThemeFont( kThemeViewsFont ) ;
748 #else
749 m_normalFont = wxSystemSettings::GetFont( wxSYS_DEFAULT_GUI_FONT );
750 #endif
751 m_boldFont = wxFont(m_normalFont.GetPointSize(),
752 m_normalFont.GetFamily(),
753 m_normalFont.GetStyle(),
754 wxBOLD,
755 m_normalFont.GetUnderlined(),
756 m_normalFont.GetFaceName(),
757 m_normalFont.GetEncoding());
758 }
759
760 bool wxGenericTreeCtrl::Create(wxWindow *parent,
761 wxWindowID id,
762 const wxPoint& pos,
763 const wxSize& size,
764 long style,
765 const wxValidator& wxVALIDATOR_PARAM(validator),
766 const wxString& name )
767 {
768 #ifdef __WXMAC__
769 int major,minor;
770 wxGetOsVersion( &major, &minor );
771
772 style &= ~wxTR_LINES_AT_ROOT;
773 style |= wxTR_NO_LINES;
774 if (major < 10)
775 style |= wxTR_ROW_LINES;
776 #endif // __WXMAC__
777
778 wxScrolledWindow::Create( parent, id, pos, size,
779 style|wxHSCROLL|wxVSCROLL, name );
780
781 // If the tree display has no buttons, but does have
782 // connecting lines, we can use a narrower layout.
783 // It may not be a good idea to force this...
784 if (!HasButtons() && !HasFlag(wxTR_NO_LINES))
785 {
786 m_indent= 10;
787 m_spacing = 10;
788 }
789
790 #if wxUSE_VALIDATORS
791 SetValidator( validator );
792 #endif
793
794 wxVisualAttributes attr = GetDefaultAttributes();
795 SetOwnForegroundColour( attr.colFg );
796 SetOwnBackgroundColour( attr.colBg );
797 if (!m_hasFont)
798 SetOwnFont(attr.font);
799
800 // m_dottedPen = wxPen( "grey", 0, wxDOT ); too slow under XFree86
801 m_dottedPen = wxPen( wxT("grey"), 0, 0 );
802
803 SetBestSize(size);
804
805 return true;
806 }
807
808 wxGenericTreeCtrl::~wxGenericTreeCtrl()
809 {
810 delete m_hilightBrush;
811 delete m_hilightUnfocusedBrush;
812
813 DeleteAllItems();
814
815 delete m_renameTimer;
816 delete m_findTimer;
817
818 if (m_ownsImageListNormal)
819 delete m_imageListNormal;
820 if (m_ownsImageListState)
821 delete m_imageListState;
822 if (m_ownsImageListButtons)
823 delete m_imageListButtons;
824 }
825
826 // -----------------------------------------------------------------------------
827 // accessors
828 // -----------------------------------------------------------------------------
829
830 size_t wxGenericTreeCtrl::GetCount() const
831 {
832 if ( !m_anchor )
833 {
834 // the tree is empty
835 return 0;
836 }
837
838 size_t count = m_anchor->GetChildrenCount();
839 if ( !HasFlag(wxTR_HIDE_ROOT) )
840 {
841 // take the root itself into account
842 count++;
843 }
844
845 return count;
846 }
847
848 void wxGenericTreeCtrl::SetIndent(unsigned int indent)
849 {
850 m_indent = (unsigned short) indent;
851 m_dirty = true;
852 }
853
854 void wxGenericTreeCtrl::SetSpacing(unsigned int spacing)
855 {
856 m_spacing = (unsigned short) spacing;
857 m_dirty = true;
858 }
859
860 size_t
861 wxGenericTreeCtrl::GetChildrenCount(const wxTreeItemId& item,
862 bool recursively) const
863 {
864 wxCHECK_MSG( item.IsOk(), 0u, wxT("invalid tree item") );
865
866 return ((wxGenericTreeItem*) item.m_pItem)->GetChildrenCount(recursively);
867 }
868
869 void wxGenericTreeCtrl::SetWindowStyle(const long styles)
870 {
871 if (!HasFlag(wxTR_HIDE_ROOT) && (styles & wxTR_HIDE_ROOT))
872 {
873 // if we will hide the root, make sure children are visible
874 m_anchor->SetHasPlus();
875 m_anchor->Expand();
876 CalculatePositions();
877 }
878
879 // right now, just sets the styles. Eventually, we may
880 // want to update the inherited styles, but right now
881 // none of the parents has updatable styles
882 m_windowStyle = styles;
883 m_dirty = true;
884 }
885
886 // -----------------------------------------------------------------------------
887 // functions to work with tree items
888 // -----------------------------------------------------------------------------
889
890 wxString wxGenericTreeCtrl::GetItemText(const wxTreeItemId& item) const
891 {
892 wxCHECK_MSG( item.IsOk(), wxT(""), wxT("invalid tree item") );
893
894 return ((wxGenericTreeItem*) item.m_pItem)->GetText();
895 }
896
897 int wxGenericTreeCtrl::GetItemImage(const wxTreeItemId& item,
898 wxTreeItemIcon which) const
899 {
900 wxCHECK_MSG( item.IsOk(), -1, wxT("invalid tree item") );
901
902 return ((wxGenericTreeItem*) item.m_pItem)->GetImage(which);
903 }
904
905 wxTreeItemData *wxGenericTreeCtrl::GetItemData(const wxTreeItemId& item) const
906 {
907 wxCHECK_MSG( item.IsOk(), NULL, wxT("invalid tree item") );
908
909 return ((wxGenericTreeItem*) item.m_pItem)->GetData();
910 }
911
912 wxColour wxGenericTreeCtrl::GetItemTextColour(const wxTreeItemId& item) const
913 {
914 wxCHECK_MSG( item.IsOk(), wxNullColour, wxT("invalid tree item") );
915
916 wxGenericTreeItem *pItem = (wxGenericTreeItem*) item.m_pItem;
917 return pItem->Attr().GetTextColour();
918 }
919
920 wxColour wxGenericTreeCtrl::GetItemBackgroundColour(const wxTreeItemId& item) const
921 {
922 wxCHECK_MSG( item.IsOk(), wxNullColour, wxT("invalid tree item") );
923
924 wxGenericTreeItem *pItem = (wxGenericTreeItem*) item.m_pItem;
925 return pItem->Attr().GetBackgroundColour();
926 }
927
928 wxFont wxGenericTreeCtrl::GetItemFont(const wxTreeItemId& item) const
929 {
930 wxCHECK_MSG( item.IsOk(), wxNullFont, wxT("invalid tree item") );
931
932 wxGenericTreeItem *pItem = (wxGenericTreeItem*) item.m_pItem;
933 return pItem->Attr().GetFont();
934 }
935
936 void wxGenericTreeCtrl::SetItemText(const wxTreeItemId& item, const wxString& text)
937 {
938 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
939
940 wxClientDC dc(this);
941 wxGenericTreeItem *pItem = (wxGenericTreeItem*) item.m_pItem;
942 pItem->SetText(text);
943 CalculateSize(pItem, dc);
944 RefreshLine(pItem);
945 }
946
947 void wxGenericTreeCtrl::SetItemImage(const wxTreeItemId& item,
948 int image,
949 wxTreeItemIcon which)
950 {
951 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
952
953 wxGenericTreeItem *pItem = (wxGenericTreeItem*) item.m_pItem;
954 pItem->SetImage(image, which);
955
956 wxClientDC dc(this);
957 CalculateSize(pItem, dc);
958 RefreshLine(pItem);
959 }
960
961 void wxGenericTreeCtrl::SetItemData(const wxTreeItemId& item, wxTreeItemData *data)
962 {
963 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
964
965 if (data)
966 data->SetId( item );
967
968 ((wxGenericTreeItem*) item.m_pItem)->SetData(data);
969 }
970
971 void wxGenericTreeCtrl::SetItemHasChildren(const wxTreeItemId& item, bool has)
972 {
973 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
974
975 wxGenericTreeItem *pItem = (wxGenericTreeItem*) item.m_pItem;
976 pItem->SetHasPlus(has);
977 RefreshLine(pItem);
978 }
979
980 void wxGenericTreeCtrl::SetItemBold(const wxTreeItemId& item, bool bold)
981 {
982 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
983
984 // avoid redrawing the tree if no real change
985 wxGenericTreeItem *pItem = (wxGenericTreeItem*) item.m_pItem;
986 if ( pItem->IsBold() != bold )
987 {
988 pItem->SetBold(bold);
989 RefreshLine(pItem);
990 }
991 }
992
993 void wxGenericTreeCtrl::SetItemTextColour(const wxTreeItemId& item,
994 const wxColour& col)
995 {
996 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
997
998 wxGenericTreeItem *pItem = (wxGenericTreeItem*) item.m_pItem;
999 pItem->Attr().SetTextColour(col);
1000 RefreshLine(pItem);
1001 }
1002
1003 void wxGenericTreeCtrl::SetItemBackgroundColour(const wxTreeItemId& item,
1004 const wxColour& col)
1005 {
1006 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1007
1008 wxGenericTreeItem *pItem = (wxGenericTreeItem*) item.m_pItem;
1009 pItem->Attr().SetBackgroundColour(col);
1010 RefreshLine(pItem);
1011 }
1012
1013 void wxGenericTreeCtrl::SetItemFont(const wxTreeItemId& item, const wxFont& font)
1014 {
1015 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1016
1017 wxGenericTreeItem *pItem = (wxGenericTreeItem*) item.m_pItem;
1018 pItem->Attr().SetFont(font);
1019 RefreshLine(pItem);
1020 }
1021
1022 bool wxGenericTreeCtrl::SetFont( const wxFont &font )
1023 {
1024 wxScrolledWindow::SetFont(font);
1025
1026 m_normalFont = font ;
1027 m_boldFont = wxFont(m_normalFont.GetPointSize(),
1028 m_normalFont.GetFamily(),
1029 m_normalFont.GetStyle(),
1030 wxBOLD,
1031 m_normalFont.GetUnderlined(),
1032 m_normalFont.GetFaceName(),
1033 m_normalFont.GetEncoding());
1034
1035 return true;
1036 }
1037
1038
1039 // -----------------------------------------------------------------------------
1040 // item status inquiries
1041 // -----------------------------------------------------------------------------
1042
1043 bool wxGenericTreeCtrl::IsVisible(const wxTreeItemId& item) const
1044 {
1045 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1046
1047 // An item is only visible if it's not a descendant of a collapsed item
1048 wxGenericTreeItem *pItem = (wxGenericTreeItem*) item.m_pItem;
1049 wxGenericTreeItem* parent = pItem->GetParent();
1050 while (parent)
1051 {
1052 if (!parent->IsExpanded())
1053 return false;
1054 parent = parent->GetParent();
1055 }
1056
1057 int startX, startY;
1058 GetViewStart(& startX, & startY);
1059
1060 wxSize clientSize = GetClientSize();
1061
1062 wxRect rect;
1063 if (!GetBoundingRect(item, rect))
1064 return false;
1065 if (rect.GetWidth() == 0 || rect.GetHeight() == 0)
1066 return false;
1067 if (rect.GetBottom() < 0 || rect.GetTop() > clientSize.y)
1068 return false;
1069 if (rect.GetRight() < 0 || rect.GetLeft() > clientSize.x)
1070 return false;
1071
1072 return true;
1073 }
1074
1075 bool wxGenericTreeCtrl::ItemHasChildren(const wxTreeItemId& item) const
1076 {
1077 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1078
1079 // consider that the item does have children if it has the "+" button: it
1080 // might not have them (if it had never been expanded yet) but then it
1081 // could have them as well and it's better to err on this side rather than
1082 // disabling some operations which are restricted to the items with
1083 // children for an item which does have them
1084 return ((wxGenericTreeItem*) item.m_pItem)->HasPlus();
1085 }
1086
1087 bool wxGenericTreeCtrl::IsExpanded(const wxTreeItemId& item) const
1088 {
1089 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1090
1091 return ((wxGenericTreeItem*) item.m_pItem)->IsExpanded();
1092 }
1093
1094 bool wxGenericTreeCtrl::IsSelected(const wxTreeItemId& item) const
1095 {
1096 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1097
1098 return ((wxGenericTreeItem*) item.m_pItem)->IsSelected();
1099 }
1100
1101 bool wxGenericTreeCtrl::IsBold(const wxTreeItemId& item) const
1102 {
1103 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1104
1105 return ((wxGenericTreeItem*) item.m_pItem)->IsBold();
1106 }
1107
1108 // -----------------------------------------------------------------------------
1109 // navigation
1110 // -----------------------------------------------------------------------------
1111
1112 wxTreeItemId wxGenericTreeCtrl::GetItemParent(const wxTreeItemId& item) const
1113 {
1114 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1115
1116 return ((wxGenericTreeItem*) item.m_pItem)->GetParent();
1117 }
1118
1119 wxTreeItemId wxGenericTreeCtrl::GetFirstChild(const wxTreeItemId& item,
1120 wxTreeItemIdValue& cookie) const
1121 {
1122 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1123
1124 cookie = 0;
1125 return GetNextChild(item, cookie);
1126 }
1127
1128 wxTreeItemId wxGenericTreeCtrl::GetNextChild(const wxTreeItemId& item,
1129 wxTreeItemIdValue& cookie) const
1130 {
1131 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1132
1133 wxArrayGenericTreeItems& children = ((wxGenericTreeItem*) item.m_pItem)->GetChildren();
1134
1135 // it's ok to cast cookie to size_t, we never have indices big enough to
1136 // overflow "void *"
1137 size_t *pIndex = (size_t *)&cookie;
1138 if ( *pIndex < children.Count() )
1139 {
1140 return children.Item((*pIndex)++);
1141 }
1142 else
1143 {
1144 // there are no more of them
1145 return wxTreeItemId();
1146 }
1147 }
1148
1149 #if WXWIN_COMPATIBILITY_2_4
1150
1151 wxTreeItemId wxGenericTreeCtrl::GetFirstChild(const wxTreeItemId& item,
1152 long& cookie) const
1153 {
1154 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1155
1156 cookie = 0;
1157 return GetNextChild(item, cookie);
1158 }
1159
1160 wxTreeItemId wxGenericTreeCtrl::GetNextChild(const wxTreeItemId& item,
1161 long& cookie) const
1162 {
1163 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1164
1165 wxArrayGenericTreeItems& children = ((wxGenericTreeItem*) item.m_pItem)->GetChildren();
1166 if ( (size_t)cookie < children.Count() )
1167 {
1168 return children.Item((size_t)cookie++);
1169 }
1170 else
1171 {
1172 // there are no more of them
1173 return wxTreeItemId();
1174 }
1175 }
1176
1177 #endif // WXWIN_COMPATIBILITY_2_4
1178
1179 wxTreeItemId wxGenericTreeCtrl::GetLastChild(const wxTreeItemId& item) const
1180 {
1181 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1182
1183 wxArrayGenericTreeItems& children = ((wxGenericTreeItem*) item.m_pItem)->GetChildren();
1184 return (children.IsEmpty() ? wxTreeItemId() : wxTreeItemId(children.Last()));
1185 }
1186
1187 wxTreeItemId wxGenericTreeCtrl::GetNextSibling(const wxTreeItemId& item) const
1188 {
1189 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1190
1191 wxGenericTreeItem *i = (wxGenericTreeItem*) item.m_pItem;
1192 wxGenericTreeItem *parent = i->GetParent();
1193 if ( parent == NULL )
1194 {
1195 // root item doesn't have any siblings
1196 return wxTreeItemId();
1197 }
1198
1199 wxArrayGenericTreeItems& siblings = parent->GetChildren();
1200 int index = siblings.Index(i);
1201 wxASSERT( index != wxNOT_FOUND ); // I'm not a child of my parent?
1202
1203 size_t n = (size_t)(index + 1);
1204 return n == siblings.Count() ? wxTreeItemId() : wxTreeItemId(siblings[n]);
1205 }
1206
1207 wxTreeItemId wxGenericTreeCtrl::GetPrevSibling(const wxTreeItemId& item) const
1208 {
1209 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1210
1211 wxGenericTreeItem *i = (wxGenericTreeItem*) item.m_pItem;
1212 wxGenericTreeItem *parent = i->GetParent();
1213 if ( parent == NULL )
1214 {
1215 // root item doesn't have any siblings
1216 return wxTreeItemId();
1217 }
1218
1219 wxArrayGenericTreeItems& siblings = parent->GetChildren();
1220 int index = siblings.Index(i);
1221 wxASSERT( index != wxNOT_FOUND ); // I'm not a child of my parent?
1222
1223 return index == 0 ? wxTreeItemId()
1224 : wxTreeItemId(siblings[(size_t)(index - 1)]);
1225 }
1226
1227 // Only for internal use right now, but should probably be public
1228 wxTreeItemId wxGenericTreeCtrl::GetNext(const wxTreeItemId& item) const
1229 {
1230 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1231
1232 wxGenericTreeItem *i = (wxGenericTreeItem*) item.m_pItem;
1233
1234 // First see if there are any children.
1235 wxArrayGenericTreeItems& children = i->GetChildren();
1236 if (children.GetCount() > 0)
1237 {
1238 return children.Item(0);
1239 }
1240 else
1241 {
1242 // Try a sibling of this or ancestor instead
1243 wxTreeItemId p = item;
1244 wxTreeItemId toFind;
1245 do
1246 {
1247 toFind = GetNextSibling(p);
1248 p = GetItemParent(p);
1249 } while (p.IsOk() && !toFind.IsOk());
1250 return toFind;
1251 }
1252 }
1253
1254 wxTreeItemId wxGenericTreeCtrl::GetFirstVisibleItem() const
1255 {
1256 wxTreeItemId id = GetRootItem();
1257 if (!id.IsOk())
1258 return id;
1259
1260 do
1261 {
1262 if (IsVisible(id))
1263 return id;
1264 id = GetNext(id);
1265 } while (id.IsOk());
1266
1267 return wxTreeItemId();
1268 }
1269
1270 wxTreeItemId wxGenericTreeCtrl::GetNextVisible(const wxTreeItemId& item) const
1271 {
1272 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1273
1274 wxTreeItemId id = item;
1275 if (id.IsOk())
1276 {
1277 while (id = GetNext(id), id.IsOk())
1278 {
1279 if (IsVisible(id))
1280 return id;
1281 }
1282 }
1283 return wxTreeItemId();
1284 }
1285
1286 wxTreeItemId wxGenericTreeCtrl::GetPrevVisible(const wxTreeItemId& item) const
1287 {
1288 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1289
1290 wxFAIL_MSG(wxT("not implemented"));
1291
1292 return wxTreeItemId();
1293 }
1294
1295 // called by wxTextTreeCtrl when it marks itself for deletion
1296 void wxGenericTreeCtrl::ResetTextControl()
1297 {
1298 m_textCtrl = NULL;
1299 }
1300
1301 // find the first item starting with the given prefix after the given item
1302 wxTreeItemId wxGenericTreeCtrl::FindItem(const wxTreeItemId& idParent,
1303 const wxString& prefixOrig) const
1304 {
1305 // match is case insensitive as this is more convenient to the user: having
1306 // to press Shift-letter to go to the item starting with a capital letter
1307 // would be too bothersome
1308 wxString prefix = prefixOrig.Lower();
1309
1310 // determine the starting point: we shouldn't take the current item (this
1311 // allows to switch between two items starting with the same letter just by
1312 // pressing it) but we shouldn't jump to the next one if the user is
1313 // continuing to type as otherwise he might easily skip the item he wanted
1314 wxTreeItemId id = idParent;
1315 if ( prefix.length() == 1 )
1316 {
1317 id = GetNext(id);
1318 }
1319
1320 // look for the item starting with the given prefix after it
1321 while ( id.IsOk() && !GetItemText(id).Lower().StartsWith(prefix) )
1322 {
1323 id = GetNext(id);
1324 }
1325
1326 // if we haven't found anything...
1327 if ( !id.IsOk() )
1328 {
1329 // ... wrap to the beginning
1330 id = GetRootItem();
1331 if ( HasFlag(wxTR_HIDE_ROOT) )
1332 {
1333 // can't select virtual root
1334 id = GetNext(id);
1335 }
1336
1337 // and try all the items (stop when we get to the one we started from)
1338 while ( id != idParent && !GetItemText(id).Lower().StartsWith(prefix) )
1339 {
1340 id = GetNext(id);
1341 }
1342 }
1343
1344 return id;
1345 }
1346
1347 // -----------------------------------------------------------------------------
1348 // operations
1349 // -----------------------------------------------------------------------------
1350
1351 wxTreeItemId wxGenericTreeCtrl::DoInsertItem(const wxTreeItemId& parentId,
1352 size_t previous,
1353 const wxString& text,
1354 int image, int selImage,
1355 wxTreeItemData *data)
1356 {
1357 wxGenericTreeItem *parent = (wxGenericTreeItem*) parentId.m_pItem;
1358 if ( !parent )
1359 {
1360 // should we give a warning here?
1361 return AddRoot(text, image, selImage, data);
1362 }
1363
1364 m_dirty = true; // do this first so stuff below doesn't cause flicker
1365
1366 wxGenericTreeItem *item =
1367 new wxGenericTreeItem( parent, text, image, selImage, data );
1368
1369 if ( data != NULL )
1370 {
1371 data->m_pItem = item;
1372 }
1373
1374 parent->Insert( item, previous );
1375
1376 return item;
1377 }
1378
1379 wxTreeItemId wxGenericTreeCtrl::AddRoot(const wxString& text,
1380 int image, int selImage,
1381 wxTreeItemData *data)
1382 {
1383 wxCHECK_MSG( !m_anchor, wxTreeItemId(), wxT("tree can have only one root") );
1384
1385 m_dirty = true; // do this first so stuff below doesn't cause flicker
1386
1387 m_anchor = new wxGenericTreeItem((wxGenericTreeItem *)NULL, text,
1388 image, selImage, data);
1389 if ( data != NULL )
1390 {
1391 data->m_pItem = m_anchor;
1392 }
1393
1394 if (HasFlag(wxTR_HIDE_ROOT))
1395 {
1396 // if root is hidden, make sure we can navigate
1397 // into children
1398 m_anchor->SetHasPlus();
1399 m_anchor->Expand();
1400 CalculatePositions();
1401 }
1402
1403 if (!HasFlag(wxTR_MULTIPLE))
1404 {
1405 m_current = m_key_current = m_anchor;
1406 m_current->SetHilight( true );
1407 }
1408
1409 return m_anchor;
1410 }
1411
1412 wxTreeItemId wxGenericTreeCtrl::PrependItem(const wxTreeItemId& parent,
1413 const wxString& text,
1414 int image, int selImage,
1415 wxTreeItemData *data)
1416 {
1417 return DoInsertItem(parent, 0u, text, image, selImage, data);
1418 }
1419
1420 wxTreeItemId wxGenericTreeCtrl::InsertItem(const wxTreeItemId& parentId,
1421 const wxTreeItemId& idPrevious,
1422 const wxString& text,
1423 int image, int selImage,
1424 wxTreeItemData *data)
1425 {
1426 wxGenericTreeItem *parent = (wxGenericTreeItem*) parentId.m_pItem;
1427 if ( !parent )
1428 {
1429 // should we give a warning here?
1430 return AddRoot(text, image, selImage, data);
1431 }
1432
1433 int index = -1;
1434 if (idPrevious.IsOk())
1435 {
1436 index = parent->GetChildren().Index((wxGenericTreeItem*) idPrevious.m_pItem);
1437 wxASSERT_MSG( index != wxNOT_FOUND,
1438 wxT("previous item in wxGenericTreeCtrl::InsertItem() is not a sibling") );
1439 }
1440
1441 return DoInsertItem(parentId, (size_t)++index, text, image, selImage, data);
1442 }
1443
1444 wxTreeItemId wxGenericTreeCtrl::InsertItem(const wxTreeItemId& parentId,
1445 size_t before,
1446 const wxString& text,
1447 int image, int selImage,
1448 wxTreeItemData *data)
1449 {
1450 wxGenericTreeItem *parent = (wxGenericTreeItem*) parentId.m_pItem;
1451 if ( !parent )
1452 {
1453 // should we give a warning here?
1454 return AddRoot(text, image, selImage, data);
1455 }
1456
1457 return DoInsertItem(parentId, before, text, image, selImage, data);
1458 }
1459
1460 wxTreeItemId wxGenericTreeCtrl::AppendItem(const wxTreeItemId& parentId,
1461 const wxString& text,
1462 int image, int selImage,
1463 wxTreeItemData *data)
1464 {
1465 wxGenericTreeItem *parent = (wxGenericTreeItem*) parentId.m_pItem;
1466 if ( !parent )
1467 {
1468 // should we give a warning here?
1469 return AddRoot(text, image, selImage, data);
1470 }
1471
1472 return DoInsertItem( parent, parent->GetChildren().Count(), text,
1473 image, selImage, data);
1474 }
1475
1476 void wxGenericTreeCtrl::SendDeleteEvent(wxGenericTreeItem *item)
1477 {
1478 wxTreeEvent event( wxEVT_COMMAND_TREE_DELETE_ITEM, GetId() );
1479 event.m_item = item;
1480 event.SetEventObject( this );
1481 ProcessEvent( event );
1482 }
1483
1484 void wxGenericTreeCtrl::DeleteChildren(const wxTreeItemId& itemId)
1485 {
1486 m_dirty = true; // do this first so stuff below doesn't cause flicker
1487
1488 wxGenericTreeItem *item = (wxGenericTreeItem*) itemId.m_pItem;
1489 item->DeleteChildren(this);
1490 }
1491
1492 void wxGenericTreeCtrl::Delete(const wxTreeItemId& itemId)
1493 {
1494 m_dirty = true; // do this first so stuff below doesn't cause flicker
1495
1496 wxGenericTreeItem *item = (wxGenericTreeItem*) itemId.m_pItem;
1497
1498 wxGenericTreeItem *parent = item->GetParent();
1499
1500 // don't keep stale pointers around!
1501 if ( IsDescendantOf(item, m_key_current) )
1502 {
1503 // Don't silently change the selection:
1504 // do it properly in idle time, so event
1505 // handlers get called.
1506
1507 // m_key_current = parent;
1508 m_key_current = NULL;
1509 }
1510
1511 // m_select_me records whether we need to select
1512 // a different item, in idle time.
1513 if ( m_select_me && IsDescendantOf(item, m_select_me) )
1514 {
1515 m_select_me = parent;
1516 }
1517
1518 if ( IsDescendantOf(item, m_current) )
1519 {
1520 // Don't silently change the selection:
1521 // do it properly in idle time, so event
1522 // handlers get called.
1523
1524 // m_current = parent;
1525 m_current = NULL;
1526 m_select_me = parent;
1527 }
1528
1529 // remove the item from the tree
1530 if ( parent )
1531 {
1532 parent->GetChildren().Remove( item ); // remove by value
1533 }
1534 else // deleting the root
1535 {
1536 // nothing will be left in the tree
1537 m_anchor = NULL;
1538 }
1539
1540 // and delete all of its children and the item itself now
1541 item->DeleteChildren(this);
1542 SendDeleteEvent(item);
1543 delete item;
1544 }
1545
1546 void wxGenericTreeCtrl::DeleteAllItems()
1547 {
1548 if ( m_anchor )
1549 {
1550 Delete(m_anchor);
1551 }
1552 }
1553
1554 void wxGenericTreeCtrl::Expand(const wxTreeItemId& itemId)
1555 {
1556 wxGenericTreeItem *item = (wxGenericTreeItem*) itemId.m_pItem;
1557
1558 wxCHECK_RET( item, _T("invalid item in wxGenericTreeCtrl::Expand") );
1559 wxCHECK_RET( !HasFlag(wxTR_HIDE_ROOT) || itemId != GetRootItem(),
1560 _T("can't expand hidden root") );
1561
1562 if ( !item->HasPlus() )
1563 return;
1564
1565 if ( item->IsExpanded() )
1566 return;
1567
1568 wxTreeEvent event( wxEVT_COMMAND_TREE_ITEM_EXPANDING, GetId() );
1569 event.m_item = item;
1570 event.SetEventObject( this );
1571
1572 if ( ProcessEvent( event ) && !event.IsAllowed() )
1573 {
1574 // cancelled by program
1575 return;
1576 }
1577
1578 item->Expand();
1579 CalculatePositions();
1580
1581 RefreshSubtree(item);
1582
1583 event.SetEventType(wxEVT_COMMAND_TREE_ITEM_EXPANDED);
1584 ProcessEvent( event );
1585 }
1586
1587 void wxGenericTreeCtrl::ExpandAll(const wxTreeItemId& item)
1588 {
1589 if ( !HasFlag(wxTR_HIDE_ROOT) || item != GetRootItem())
1590 {
1591 Expand(item);
1592 if ( !IsExpanded(item) )
1593 return;
1594 }
1595
1596 wxTreeItemIdValue cookie;
1597 wxTreeItemId child = GetFirstChild(item, cookie);
1598 while ( child.IsOk() )
1599 {
1600 ExpandAll(child);
1601
1602 child = GetNextChild(item, cookie);
1603 }
1604 }
1605
1606 void wxGenericTreeCtrl::Collapse(const wxTreeItemId& itemId)
1607 {
1608 wxCHECK_RET( !HasFlag(wxTR_HIDE_ROOT) || itemId != GetRootItem(),
1609 _T("can't collapse hidden root") );
1610
1611 wxGenericTreeItem *item = (wxGenericTreeItem*) itemId.m_pItem;
1612
1613 if ( !item->IsExpanded() )
1614 return;
1615
1616 wxTreeEvent event( wxEVT_COMMAND_TREE_ITEM_COLLAPSING, GetId() );
1617 event.m_item = item;
1618 event.SetEventObject( this );
1619 if ( ProcessEvent( event ) && !event.IsAllowed() )
1620 {
1621 // cancelled by program
1622 return;
1623 }
1624
1625 item->Collapse();
1626
1627 #if 0 // TODO why should items be collapsed recursively?
1628 wxArrayGenericTreeItems& children = item->GetChildren();
1629 size_t count = children.Count();
1630 for ( size_t n = 0; n < count; n++ )
1631 {
1632 Collapse(children[n]);
1633 }
1634 #endif
1635
1636 CalculatePositions();
1637
1638 RefreshSubtree(item);
1639
1640 event.SetEventType(wxEVT_COMMAND_TREE_ITEM_COLLAPSED);
1641 ProcessEvent( event );
1642 }
1643
1644 void wxGenericTreeCtrl::CollapseAndReset(const wxTreeItemId& item)
1645 {
1646 Collapse(item);
1647 DeleteChildren(item);
1648 }
1649
1650 void wxGenericTreeCtrl::Toggle(const wxTreeItemId& itemId)
1651 {
1652 wxGenericTreeItem *item = (wxGenericTreeItem*) itemId.m_pItem;
1653
1654 if (item->IsExpanded())
1655 Collapse(itemId);
1656 else
1657 Expand(itemId);
1658 }
1659
1660 void wxGenericTreeCtrl::Unselect()
1661 {
1662 if (m_current)
1663 {
1664 m_current->SetHilight( false );
1665 RefreshLine( m_current );
1666
1667 m_current = NULL;
1668 m_select_me = NULL;
1669 }
1670 }
1671
1672 void wxGenericTreeCtrl::UnselectAllChildren(wxGenericTreeItem *item)
1673 {
1674 if (item->IsSelected())
1675 {
1676 item->SetHilight(false);
1677 RefreshLine(item);
1678 }
1679
1680 if (item->HasChildren())
1681 {
1682 wxArrayGenericTreeItems& children = item->GetChildren();
1683 size_t count = children.Count();
1684 for ( size_t n = 0; n < count; ++n )
1685 {
1686 UnselectAllChildren(children[n]);
1687 }
1688 }
1689 }
1690
1691 void wxGenericTreeCtrl::UnselectAll()
1692 {
1693 wxTreeItemId rootItem = GetRootItem();
1694
1695 // the tree might not have the root item at all
1696 if ( rootItem )
1697 {
1698 UnselectAllChildren((wxGenericTreeItem*) rootItem.m_pItem);
1699 }
1700 }
1701
1702 // Recursive function !
1703 // To stop we must have crt_item<last_item
1704 // Algorithm :
1705 // Tag all next children, when no more children,
1706 // Move to parent (not to tag)
1707 // Keep going... if we found last_item, we stop.
1708 bool wxGenericTreeCtrl::TagNextChildren(wxGenericTreeItem *crt_item, wxGenericTreeItem *last_item, bool select)
1709 {
1710 wxGenericTreeItem *parent = crt_item->GetParent();
1711
1712 if (parent == NULL) // This is root item
1713 return TagAllChildrenUntilLast(crt_item, last_item, select);
1714
1715 wxArrayGenericTreeItems& children = parent->GetChildren();
1716 int index = children.Index(crt_item);
1717 wxASSERT( index != wxNOT_FOUND ); // I'm not a child of my parent?
1718
1719 size_t count = children.Count();
1720 for (size_t n=(size_t)(index+1); n<count; ++n)
1721 {
1722 if (TagAllChildrenUntilLast(children[n], last_item, select)) return true;
1723 }
1724
1725 return TagNextChildren(parent, last_item, select);
1726 }
1727
1728 bool wxGenericTreeCtrl::TagAllChildrenUntilLast(wxGenericTreeItem *crt_item, wxGenericTreeItem *last_item, bool select)
1729 {
1730 crt_item->SetHilight(select);
1731 RefreshLine(crt_item);
1732
1733 if (crt_item==last_item)
1734 return true;
1735
1736 if (crt_item->HasChildren())
1737 {
1738 wxArrayGenericTreeItems& children = crt_item->GetChildren();
1739 size_t count = children.Count();
1740 for ( size_t n = 0; n < count; ++n )
1741 {
1742 if (TagAllChildrenUntilLast(children[n], last_item, select))
1743 return true;
1744 }
1745 }
1746
1747 return false;
1748 }
1749
1750 void wxGenericTreeCtrl::SelectItemRange(wxGenericTreeItem *item1, wxGenericTreeItem *item2)
1751 {
1752 m_select_me = NULL;
1753
1754 // item2 is not necessary after item1
1755 // choice first' and 'last' between item1 and item2
1756 wxGenericTreeItem *first= (item1->GetY()<item2->GetY()) ? item1 : item2;
1757 wxGenericTreeItem *last = (item1->GetY()<item2->GetY()) ? item2 : item1;
1758
1759 bool select = m_current->IsSelected();
1760
1761 if ( TagAllChildrenUntilLast(first,last,select) )
1762 return;
1763
1764 TagNextChildren(first,last,select);
1765 }
1766
1767 void wxGenericTreeCtrl::DoSelectItem(const wxTreeItemId& itemId,
1768 bool unselect_others,
1769 bool extended_select)
1770 {
1771 wxCHECK_RET( itemId.IsOk(), wxT("invalid tree item") );
1772
1773 m_select_me = NULL;
1774
1775 bool is_single=!(GetWindowStyleFlag() & wxTR_MULTIPLE);
1776 wxGenericTreeItem *item = (wxGenericTreeItem*) itemId.m_pItem;
1777
1778 //wxCHECK_RET( ( (!unselect_others) && is_single),
1779 // wxT("this is a single selection tree") );
1780
1781 // to keep going anyhow !!!
1782 if (is_single)
1783 {
1784 if (item->IsSelected())
1785 return; // nothing to do
1786 unselect_others = true;
1787 extended_select = false;
1788 }
1789 else if ( unselect_others && item->IsSelected() )
1790 {
1791 // selection change if there is more than one item currently selected
1792 wxArrayTreeItemIds selected_items;
1793 if ( GetSelections(selected_items) == 1 )
1794 return;
1795 }
1796
1797 wxTreeEvent event( wxEVT_COMMAND_TREE_SEL_CHANGING, GetId() );
1798 event.m_item = item;
1799 event.m_itemOld = m_current;
1800 event.SetEventObject( this );
1801 // TODO : Here we don't send any selection mode yet !
1802
1803 if ( GetEventHandler()->ProcessEvent( event ) && !event.IsAllowed() )
1804 return;
1805
1806 wxTreeItemId parent = GetItemParent( itemId );
1807 while (parent.IsOk())
1808 {
1809 if (!IsExpanded(parent))
1810 Expand( parent );
1811
1812 parent = GetItemParent( parent );
1813 }
1814
1815 EnsureVisible( itemId );
1816
1817 // ctrl press
1818 if (unselect_others)
1819 {
1820 if (is_single) Unselect(); // to speed up thing
1821 else UnselectAll();
1822 }
1823
1824 // shift press
1825 if (extended_select)
1826 {
1827 if ( !m_current )
1828 {
1829 m_current = m_key_current = (wxGenericTreeItem*) GetRootItem().m_pItem;
1830 }
1831
1832 // don't change the mark (m_current)
1833 SelectItemRange(m_current, item);
1834 }
1835 else
1836 {
1837 bool select = true; // the default
1838
1839 // Check if we need to toggle hilight (ctrl mode)
1840 if (!unselect_others)
1841 select=!item->IsSelected();
1842
1843 m_current = m_key_current = item;
1844 m_current->SetHilight(select);
1845 RefreshLine( m_current );
1846 }
1847
1848 event.SetEventType(wxEVT_COMMAND_TREE_SEL_CHANGED);
1849 GetEventHandler()->ProcessEvent( event );
1850 }
1851
1852 void wxGenericTreeCtrl::SelectItem(const wxTreeItemId& itemId, bool select)
1853 {
1854 if ( select )
1855 {
1856 DoSelectItem(itemId);
1857 }
1858 else // deselect
1859 {
1860 wxGenericTreeItem *item = (wxGenericTreeItem*) itemId.m_pItem;
1861 wxCHECK_RET( item, wxT("SelectItem(): invalid tree item") );
1862
1863 item->SetHilight(false);
1864 RefreshLine(item);
1865 }
1866 }
1867
1868 void wxGenericTreeCtrl::FillArray(wxGenericTreeItem *item,
1869 wxArrayTreeItemIds &array) const
1870 {
1871 if ( item->IsSelected() )
1872 array.Add(wxTreeItemId(item));
1873
1874 if ( item->HasChildren() )
1875 {
1876 wxArrayGenericTreeItems& children = item->GetChildren();
1877 size_t count = children.GetCount();
1878 for ( size_t n = 0; n < count; ++n )
1879 FillArray(children[n], array);
1880 }
1881 }
1882
1883 size_t wxGenericTreeCtrl::GetSelections(wxArrayTreeItemIds &array) const
1884 {
1885 array.Empty();
1886 wxTreeItemId idRoot = GetRootItem();
1887 if ( idRoot.IsOk() )
1888 {
1889 FillArray((wxGenericTreeItem*) idRoot.m_pItem, array);
1890 }
1891 //else: the tree is empty, so no selections
1892
1893 return array.Count();
1894 }
1895
1896 void wxGenericTreeCtrl::EnsureVisible(const wxTreeItemId& item)
1897 {
1898 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1899
1900 if (!item.IsOk()) return;
1901
1902 wxGenericTreeItem *gitem = (wxGenericTreeItem*) item.m_pItem;
1903
1904 // first expand all parent branches
1905 wxGenericTreeItem *parent = gitem->GetParent();
1906
1907 if ( HasFlag(wxTR_HIDE_ROOT) )
1908 {
1909 while ( parent && parent != m_anchor )
1910 {
1911 Expand(parent);
1912 parent = parent->GetParent();
1913 }
1914 }
1915 else
1916 {
1917 while ( parent )
1918 {
1919 Expand(parent);
1920 parent = parent->GetParent();
1921 }
1922 }
1923
1924 //if (parent) CalculatePositions();
1925
1926 ScrollTo(item);
1927 }
1928
1929 void wxGenericTreeCtrl::ScrollTo(const wxTreeItemId &item)
1930 {
1931 if (!item.IsOk()) return;
1932
1933 // We have to call this here because the label in
1934 // question might just have been added and no screen
1935 // update taken place.
1936 if (m_dirty)
1937 #if defined( __WXMSW__ ) || defined(__WXMAC__)
1938 Update();
1939 #else
1940 wxYieldIfNeeded();
1941 #endif
1942 wxGenericTreeItem *gitem = (wxGenericTreeItem*) item.m_pItem;
1943
1944 // now scroll to the item
1945 int item_y = gitem->GetY();
1946
1947 int start_x = 0;
1948 int start_y = 0;
1949 GetViewStart( &start_x, &start_y );
1950 start_y *= PIXELS_PER_UNIT;
1951
1952 int client_h = 0;
1953 int client_w = 0;
1954 GetClientSize( &client_w, &client_h );
1955
1956 if (item_y < start_y+3)
1957 {
1958 // going down
1959 int x = 0;
1960 int y = 0;
1961 m_anchor->GetSize( x, y, this );
1962 y += PIXELS_PER_UNIT+2; // one more scrollbar unit + 2 pixels
1963 x += PIXELS_PER_UNIT+2; // one more scrollbar unit + 2 pixels
1964 int x_pos = GetScrollPos( wxHORIZONTAL );
1965 // Item should appear at top
1966 SetScrollbars( PIXELS_PER_UNIT, PIXELS_PER_UNIT, x/PIXELS_PER_UNIT, y/PIXELS_PER_UNIT, x_pos, item_y/PIXELS_PER_UNIT );
1967 }
1968 else if (item_y+GetLineHeight(gitem) > start_y+client_h)
1969 {
1970 // going up
1971 int x = 0;
1972 int y = 0;
1973 m_anchor->GetSize( x, y, this );
1974 y += PIXELS_PER_UNIT+2; // one more scrollbar unit + 2 pixels
1975 x += PIXELS_PER_UNIT+2; // one more scrollbar unit + 2 pixels
1976 item_y += PIXELS_PER_UNIT+2;
1977 int x_pos = GetScrollPos( wxHORIZONTAL );
1978 // Item should appear at bottom
1979 SetScrollbars( PIXELS_PER_UNIT, PIXELS_PER_UNIT, x/PIXELS_PER_UNIT, y/PIXELS_PER_UNIT, x_pos, (item_y+GetLineHeight(gitem)-client_h)/PIXELS_PER_UNIT );
1980 }
1981 }
1982
1983 // FIXME: tree sorting functions are not reentrant and not MT-safe!
1984 static wxGenericTreeCtrl *s_treeBeingSorted = NULL;
1985
1986 static int LINKAGEMODE tree_ctrl_compare_func(wxGenericTreeItem **item1,
1987 wxGenericTreeItem **item2)
1988 {
1989 wxCHECK_MSG( s_treeBeingSorted, 0, wxT("bug in wxGenericTreeCtrl::SortChildren()") );
1990
1991 return s_treeBeingSorted->OnCompareItems(*item1, *item2);
1992 }
1993
1994 int wxGenericTreeCtrl::OnCompareItems(const wxTreeItemId& item1,
1995 const wxTreeItemId& item2)
1996 {
1997 return wxStrcmp(GetItemText(item1), GetItemText(item2));
1998 }
1999
2000 void wxGenericTreeCtrl::SortChildren(const wxTreeItemId& itemId)
2001 {
2002 wxCHECK_RET( itemId.IsOk(), wxT("invalid tree item") );
2003
2004 wxGenericTreeItem *item = (wxGenericTreeItem*) itemId.m_pItem;
2005
2006 wxCHECK_RET( !s_treeBeingSorted,
2007 wxT("wxGenericTreeCtrl::SortChildren is not reentrant") );
2008
2009 wxArrayGenericTreeItems& children = item->GetChildren();
2010 if ( children.Count() > 1 )
2011 {
2012 m_dirty = true;
2013
2014 s_treeBeingSorted = this;
2015 children.Sort(tree_ctrl_compare_func);
2016 s_treeBeingSorted = NULL;
2017 }
2018 //else: don't make the tree dirty as nothing changed
2019 }
2020
2021 wxImageList *wxGenericTreeCtrl::GetImageList() const
2022 {
2023 return m_imageListNormal;
2024 }
2025
2026 wxImageList *wxGenericTreeCtrl::GetButtonsImageList() const
2027 {
2028 return m_imageListButtons;
2029 }
2030
2031 wxImageList *wxGenericTreeCtrl::GetStateImageList() const
2032 {
2033 return m_imageListState;
2034 }
2035
2036 void wxGenericTreeCtrl::CalculateLineHeight()
2037 {
2038 wxClientDC dc(this);
2039 m_lineHeight = (int)(dc.GetCharHeight() + 4);
2040
2041 if ( m_imageListNormal )
2042 {
2043 // Calculate a m_lineHeight value from the normal Image sizes.
2044 // May be toggle off. Then wxGenericTreeCtrl will spread when
2045 // necessary (which might look ugly).
2046 int n = m_imageListNormal->GetImageCount();
2047 for (int i = 0; i < n ; i++)
2048 {
2049 int width = 0, height = 0;
2050 m_imageListNormal->GetSize(i, width, height);
2051 if (height > m_lineHeight) m_lineHeight = height;
2052 }
2053 }
2054
2055 if (m_imageListButtons)
2056 {
2057 // Calculate a m_lineHeight value from the Button image sizes.
2058 // May be toggle off. Then wxGenericTreeCtrl will spread when
2059 // necessary (which might look ugly).
2060 int n = m_imageListButtons->GetImageCount();
2061 for (int i = 0; i < n ; i++)
2062 {
2063 int width = 0, height = 0;
2064 m_imageListButtons->GetSize(i, width, height);
2065 if (height > m_lineHeight) m_lineHeight = height;
2066 }
2067 }
2068
2069 if (m_lineHeight < 30)
2070 m_lineHeight += 2; // at least 2 pixels
2071 else
2072 m_lineHeight += m_lineHeight/10; // otherwise 10% extra spacing
2073 }
2074
2075 void wxGenericTreeCtrl::SetImageList(wxImageList *imageList)
2076 {
2077 if (m_ownsImageListNormal) delete m_imageListNormal;
2078 m_imageListNormal = imageList;
2079 m_ownsImageListNormal = false;
2080 m_dirty = true;
2081 // Don't do any drawing if we're setting the list to NULL,
2082 // since we may be in the process of deleting the tree control.
2083 if (imageList)
2084 CalculateLineHeight();
2085 }
2086
2087 void wxGenericTreeCtrl::SetStateImageList(wxImageList *imageList)
2088 {
2089 if (m_ownsImageListState) delete m_imageListState;
2090 m_imageListState = imageList;
2091 m_ownsImageListState = false;
2092 }
2093
2094 void wxGenericTreeCtrl::SetButtonsImageList(wxImageList *imageList)
2095 {
2096 if (m_ownsImageListButtons) delete m_imageListButtons;
2097 m_imageListButtons = imageList;
2098 m_ownsImageListButtons = false;
2099 m_dirty = true;
2100 CalculateLineHeight();
2101 }
2102
2103 void wxGenericTreeCtrl::AssignImageList(wxImageList *imageList)
2104 {
2105 SetImageList(imageList);
2106 m_ownsImageListNormal = true;
2107 }
2108
2109 void wxGenericTreeCtrl::AssignStateImageList(wxImageList *imageList)
2110 {
2111 SetStateImageList(imageList);
2112 m_ownsImageListState = true;
2113 }
2114
2115 void wxGenericTreeCtrl::AssignButtonsImageList(wxImageList *imageList)
2116 {
2117 SetButtonsImageList(imageList);
2118 m_ownsImageListButtons = true;
2119 }
2120
2121 // -----------------------------------------------------------------------------
2122 // helpers
2123 // -----------------------------------------------------------------------------
2124
2125 void wxGenericTreeCtrl::AdjustMyScrollbars()
2126 {
2127 if (m_anchor)
2128 {
2129 int x = 0, y = 0;
2130 m_anchor->GetSize( x, y, this );
2131 y += PIXELS_PER_UNIT+2; // one more scrollbar unit + 2 pixels
2132 x += PIXELS_PER_UNIT+2; // one more scrollbar unit + 2 pixels
2133 int x_pos = GetScrollPos( wxHORIZONTAL );
2134 int y_pos = GetScrollPos( wxVERTICAL );
2135 SetScrollbars( PIXELS_PER_UNIT, PIXELS_PER_UNIT, x/PIXELS_PER_UNIT, y/PIXELS_PER_UNIT, x_pos, y_pos );
2136 }
2137 else
2138 {
2139 SetScrollbars( 0, 0, 0, 0 );
2140 }
2141 }
2142
2143 int wxGenericTreeCtrl::GetLineHeight(wxGenericTreeItem *item) const
2144 {
2145 if (GetWindowStyleFlag() & wxTR_HAS_VARIABLE_ROW_HEIGHT)
2146 return item->GetHeight();
2147 else
2148 return m_lineHeight;
2149 }
2150
2151 void wxGenericTreeCtrl::PaintItem(wxGenericTreeItem *item, wxDC& dc)
2152 {
2153 // TODO implement "state" icon on items
2154
2155 wxTreeItemAttr *attr = item->GetAttributes();
2156 if ( attr && attr->HasFont() )
2157 dc.SetFont(attr->GetFont());
2158 else if (item->IsBold())
2159 dc.SetFont(m_boldFont);
2160
2161 long text_w = 0, text_h = 0;
2162 dc.GetTextExtent( item->GetText(), &text_w, &text_h );
2163
2164 int image_h = 0, image_w = 0;
2165 int image = item->GetCurrentImage();
2166 if ( image != NO_IMAGE )
2167 {
2168 if ( m_imageListNormal )
2169 {
2170 m_imageListNormal->GetSize( image, image_w, image_h );
2171 image_w += 4;
2172 }
2173 else
2174 {
2175 image = NO_IMAGE;
2176 }
2177 }
2178
2179 int total_h = GetLineHeight(item);
2180
2181 if ( item->IsSelected() )
2182 {
2183 // under mac selections are only a rectangle in case they don't have the focus
2184 #ifdef __WXMAC__
2185 if ( !m_hasFocus )
2186 {
2187 dc.SetBrush( *wxTRANSPARENT_BRUSH ) ;
2188 dc.SetPen( wxPen( wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT ) , 1 , wxSOLID ) ) ;
2189 }
2190 else
2191 {
2192 dc.SetBrush( *m_hilightBrush ) ;
2193 }
2194 #else
2195 dc.SetBrush(*(m_hasFocus ? m_hilightBrush : m_hilightUnfocusedBrush));
2196 #endif
2197 }
2198 else
2199 {
2200 wxColour colBg;
2201 if ( attr && attr->HasBackgroundColour() )
2202 colBg = attr->GetBackgroundColour();
2203 else
2204 colBg = m_backgroundColour;
2205 dc.SetBrush(wxBrush(colBg, wxSOLID));
2206 }
2207
2208 int offset = HasFlag(wxTR_ROW_LINES) ? 1 : 0;
2209
2210 if ( HasFlag(wxTR_FULL_ROW_HIGHLIGHT) )
2211 {
2212 int x, y, w, h;
2213
2214 DoGetPosition(&x, &y);
2215 DoGetSize(&w, &h);
2216 dc.DrawRectangle(x, item->GetY()+offset, w, total_h-offset);
2217 }
2218 else
2219 {
2220 if ( item->IsSelected() && image != NO_IMAGE )
2221 {
2222 // If it's selected, and there's an image, then we should
2223 // take care to leave the area under the image painted in the
2224 // background colour.
2225 dc.DrawRectangle( item->GetX() + image_w - 2, item->GetY()+offset,
2226 item->GetWidth() - image_w + 2, total_h-offset );
2227 }
2228 else
2229 {
2230 dc.DrawRectangle( item->GetX()-2, item->GetY()+offset,
2231 item->GetWidth()+2, total_h-offset );
2232 }
2233 }
2234
2235 if ( image != NO_IMAGE )
2236 {
2237 dc.SetClippingRegion( item->GetX(), item->GetY(), image_w-2, total_h );
2238 m_imageListNormal->Draw( image, dc,
2239 item->GetX(),
2240 item->GetY() +((total_h > image_h)?((total_h-image_h)/2):0),
2241 wxIMAGELIST_DRAW_TRANSPARENT );
2242 dc.DestroyClippingRegion();
2243 }
2244
2245 dc.SetBackgroundMode(wxTRANSPARENT);
2246 int extraH = (total_h > text_h) ? (total_h - text_h)/2 : 0;
2247 dc.DrawText( item->GetText(),
2248 (wxCoord)(image_w + item->GetX()),
2249 (wxCoord)(item->GetY() + extraH));
2250
2251 // restore normal font
2252 dc.SetFont( m_normalFont );
2253 }
2254
2255 // Now y stands for the top of the item, whereas it used to stand for middle !
2256 void wxGenericTreeCtrl::PaintLevel( wxGenericTreeItem *item, wxDC &dc, int level, int &y )
2257 {
2258 int x = level*m_indent;
2259 if (!HasFlag(wxTR_HIDE_ROOT))
2260 {
2261 x += m_indent;
2262 }
2263 else if (level == 0)
2264 {
2265 // always expand hidden root
2266 int origY = y;
2267 wxArrayGenericTreeItems& children = item->GetChildren();
2268 int count = children.Count();
2269 if (count > 0)
2270 {
2271 int n = 0, oldY;
2272 do {
2273 oldY = y;
2274 PaintLevel(children[n], dc, 1, y);
2275 } while (++n < count);
2276
2277 if (!HasFlag(wxTR_NO_LINES) && HasFlag(wxTR_LINES_AT_ROOT) && count > 0)
2278 {
2279 // draw line down to last child
2280 origY += GetLineHeight(children[0])>>1;
2281 oldY += GetLineHeight(children[n-1])>>1;
2282 dc.DrawLine(3, origY, 3, oldY);
2283 }
2284 }
2285 return;
2286 }
2287
2288 item->SetX(x+m_spacing);
2289 item->SetY(y);
2290
2291 int h = GetLineHeight(item);
2292 int y_top = y;
2293 int y_mid = y_top + (h>>1);
2294 y += h;
2295
2296 int exposed_x = dc.LogicalToDeviceX(0);
2297 int exposed_y = dc.LogicalToDeviceY(y_top);
2298
2299 if (IsExposed(exposed_x, exposed_y, 10000, h)) // 10000 = very much
2300 {
2301 wxPen *pen =
2302 #ifndef __WXMAC__
2303 // don't draw rect outline if we already have the
2304 // background color under Mac
2305 (item->IsSelected() && m_hasFocus) ? wxBLACK_PEN :
2306 #endif // !__WXMAC__
2307 wxTRANSPARENT_PEN;
2308
2309 wxColour colText;
2310 if ( item->IsSelected() )
2311 {
2312 colText = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
2313 }
2314 else
2315 {
2316 wxTreeItemAttr *attr = item->GetAttributes();
2317 if (attr && attr->HasTextColour())
2318 colText = attr->GetTextColour();
2319 else
2320 colText = GetForegroundColour();
2321 }
2322
2323 // prepare to draw
2324 dc.SetTextForeground(colText);
2325 dc.SetPen(*pen);
2326
2327 // draw
2328 PaintItem(item, dc);
2329
2330 if (HasFlag(wxTR_ROW_LINES))
2331 {
2332 // if the background colour is white, choose a
2333 // contrasting color for the lines
2334 dc.SetPen(*((GetBackgroundColour() == *wxWHITE)
2335 ? wxMEDIUM_GREY_PEN : wxWHITE_PEN));
2336 dc.DrawLine(0, y_top, 10000, y_top);
2337 dc.DrawLine(0, y, 10000, y);
2338 }
2339
2340 // restore DC objects
2341 dc.SetBrush(*wxWHITE_BRUSH);
2342 dc.SetPen(m_dottedPen);
2343 dc.SetTextForeground(*wxBLACK);
2344
2345 if ( !HasFlag(wxTR_NO_LINES) )
2346 {
2347 // draw the horizontal line here
2348 int x_start = x;
2349 if (x > (signed)m_indent)
2350 x_start -= m_indent;
2351 else if (HasFlag(wxTR_LINES_AT_ROOT))
2352 x_start = 3;
2353 dc.DrawLine(x_start, y_mid, x + m_spacing, y_mid);
2354 }
2355
2356 // should the item show a button?
2357 if ( item->HasPlus() && HasButtons() )
2358 {
2359 if ( m_imageListButtons )
2360 {
2361 // draw the image button here
2362 int image_h = 0,
2363 image_w = 0;
2364 int image = item->IsExpanded() ? wxTreeItemIcon_Expanded
2365 : wxTreeItemIcon_Normal;
2366 if ( item->IsSelected() )
2367 image += wxTreeItemIcon_Selected - wxTreeItemIcon_Normal;
2368
2369 m_imageListButtons->GetSize(image, image_w, image_h);
2370 int xx = x - image_w/2;
2371 int yy = y_mid - image_h/2;
2372
2373 wxDCClipper clip(dc, xx, yy, image_w, image_h);
2374 m_imageListButtons->Draw(image, dc, xx, yy,
2375 wxIMAGELIST_DRAW_TRANSPARENT);
2376 }
2377 else // no custom buttons
2378 {
2379 static const int wImage = 9;
2380 static const int hImage = 9;
2381
2382 int flag = 0;
2383 if (item->IsExpanded())
2384 flag |= wxCONTROL_EXPANDED;
2385 if (item == m_underMouse)
2386 flag |= wxCONTROL_CURRENT;
2387
2388 wxRendererNative::Get().DrawTreeItemButton
2389 (
2390 this,
2391 dc,
2392 wxRect(x - wImage/2,
2393 y_mid - hImage/2,
2394 wImage, hImage),
2395 flag
2396 );
2397 }
2398 }
2399 }
2400
2401 if (item->IsExpanded())
2402 {
2403 wxArrayGenericTreeItems& children = item->GetChildren();
2404 int count = children.Count();
2405 if (count > 0)
2406 {
2407 int n = 0, oldY;
2408 ++level;
2409 do {
2410 oldY = y;
2411 PaintLevel(children[n], dc, level, y);
2412 } while (++n < count);
2413
2414 if (!HasFlag(wxTR_NO_LINES) && count > 0)
2415 {
2416 // draw line down to last child
2417 oldY += GetLineHeight(children[n-1])>>1;
2418 if (HasButtons()) y_mid += 5;
2419
2420 // Only draw the portion of the line that is visible, in case it is huge
2421 wxCoord xOrigin=0, yOrigin=0, width, height;
2422 dc.GetDeviceOrigin(&xOrigin, &yOrigin);
2423 yOrigin = abs(yOrigin);
2424 GetClientSize(&width, &height);
2425
2426 // Move end points to the begining/end of the view?
2427 if (y_mid < yOrigin)
2428 y_mid = yOrigin;
2429 if (oldY > yOrigin + height)
2430 oldY = yOrigin + height;
2431
2432 // after the adjustments if y_mid is larger than oldY then the line
2433 // isn't visible at all so don't draw anything
2434 if (y_mid < oldY)
2435 dc.DrawLine(x, y_mid, x, oldY);
2436 }
2437 }
2438 }
2439 }
2440
2441 void wxGenericTreeCtrl::DrawDropEffect(wxGenericTreeItem *item)
2442 {
2443 if ( item )
2444 {
2445 if ( item->HasPlus() )
2446 {
2447 // it's a folder, indicate it by a border
2448 DrawBorder(item);
2449 }
2450 else
2451 {
2452 // draw a line under the drop target because the item will be
2453 // dropped there
2454 DrawLine(item, true /* below */);
2455 }
2456
2457 SetCursor(wxCURSOR_BULLSEYE);
2458 }
2459 else
2460 {
2461 // can't drop here
2462 SetCursor(wxCURSOR_NO_ENTRY);
2463 }
2464 }
2465
2466 void wxGenericTreeCtrl::DrawBorder(const wxTreeItemId &item)
2467 {
2468 wxCHECK_RET( item.IsOk(), _T("invalid item in wxGenericTreeCtrl::DrawLine") );
2469
2470 wxGenericTreeItem *i = (wxGenericTreeItem*) item.m_pItem;
2471
2472 wxClientDC dc(this);
2473 PrepareDC( dc );
2474 dc.SetLogicalFunction(wxINVERT);
2475 dc.SetBrush(*wxTRANSPARENT_BRUSH);
2476
2477 int w = i->GetWidth() + 2;
2478 int h = GetLineHeight(i) + 2;
2479
2480 dc.DrawRectangle( i->GetX() - 1, i->GetY() - 1, w, h);
2481 }
2482
2483 void wxGenericTreeCtrl::DrawLine(const wxTreeItemId &item, bool below)
2484 {
2485 wxCHECK_RET( item.IsOk(), _T("invalid item in wxGenericTreeCtrl::DrawLine") );
2486
2487 wxGenericTreeItem *i = (wxGenericTreeItem*) item.m_pItem;
2488
2489 wxClientDC dc(this);
2490 PrepareDC( dc );
2491 dc.SetLogicalFunction(wxINVERT);
2492
2493 int x = i->GetX(),
2494 y = i->GetY();
2495 if ( below )
2496 {
2497 y += GetLineHeight(i) - 1;
2498 }
2499
2500 dc.DrawLine( x, y, x + i->GetWidth(), y);
2501 }
2502
2503 // -----------------------------------------------------------------------------
2504 // wxWidgets callbacks
2505 // -----------------------------------------------------------------------------
2506
2507 void wxGenericTreeCtrl::OnPaint( wxPaintEvent &WXUNUSED(event) )
2508 {
2509 wxPaintDC dc(this);
2510 PrepareDC( dc );
2511
2512 if ( !m_anchor)
2513 return;
2514
2515 dc.SetFont( m_normalFont );
2516 dc.SetPen( m_dottedPen );
2517
2518 // this is now done dynamically
2519 //if(GetImageList() == NULL)
2520 // m_lineHeight = (int)(dc.GetCharHeight() + 4);
2521
2522 int y = 2;
2523 PaintLevel( m_anchor, dc, 0, y );
2524 }
2525
2526 void wxGenericTreeCtrl::OnSetFocus( wxFocusEvent &event )
2527 {
2528 m_hasFocus = true;
2529
2530 RefreshSelected();
2531
2532 event.Skip();
2533 }
2534
2535 void wxGenericTreeCtrl::OnKillFocus( wxFocusEvent &event )
2536 {
2537 m_hasFocus = false;
2538
2539 RefreshSelected();
2540
2541 event.Skip();
2542 }
2543
2544 void wxGenericTreeCtrl::OnChar( wxKeyEvent &event )
2545 {
2546 wxTreeEvent te( wxEVT_COMMAND_TREE_KEY_DOWN, GetId() );
2547 te.m_evtKey = event;
2548 te.SetEventObject( this );
2549 if ( GetEventHandler()->ProcessEvent( te ) )
2550 {
2551 // intercepted by the user code
2552 return;
2553 }
2554
2555 if ( (m_current == 0) || (m_key_current == 0) )
2556 {
2557 event.Skip();
2558 return;
2559 }
2560
2561 // how should the selection work for this event?
2562 bool is_multiple, extended_select, unselect_others;
2563 EventFlagsToSelType(GetWindowStyleFlag(),
2564 event.ShiftDown(),
2565 event.ControlDown(),
2566 is_multiple, extended_select, unselect_others);
2567
2568 // + : Expand
2569 // - : Collaspe
2570 // * : Expand all/Collapse all
2571 // ' ' | return : activate
2572 // up : go up (not last children!)
2573 // down : go down
2574 // left : go to parent
2575 // right : open if parent and go next
2576 // home : go to root
2577 // end : go to last item without opening parents
2578 // alnum : start or continue searching for the item with this prefix
2579 int keyCode = event.GetKeyCode();
2580 switch ( keyCode )
2581 {
2582 case '+':
2583 case WXK_ADD:
2584 if (m_current->HasPlus() && !IsExpanded(m_current))
2585 {
2586 Expand(m_current);
2587 }
2588 break;
2589
2590 case '*':
2591 case WXK_MULTIPLY:
2592 if ( !IsExpanded(m_current) )
2593 {
2594 // expand all
2595 ExpandAll(m_current);
2596 break;
2597 }
2598 //else: fall through to Collapse() it
2599
2600 case '-':
2601 case WXK_SUBTRACT:
2602 if (IsExpanded(m_current))
2603 {
2604 Collapse(m_current);
2605 }
2606 break;
2607
2608 case ' ':
2609 case WXK_RETURN:
2610 if ( !event.HasModifiers() )
2611 {
2612 wxTreeEvent event( wxEVT_COMMAND_TREE_ITEM_ACTIVATED, GetId() );
2613 event.m_item = m_current;
2614 event.SetEventObject( this );
2615 GetEventHandler()->ProcessEvent( event );
2616 }
2617
2618 // in any case, also generate the normal key event for this key,
2619 // even if we generated the ACTIVATED event above: this is what
2620 // wxMSW does and it makes sense because you might not want to
2621 // process ACTIVATED event at all and handle Space and Return
2622 // directly (and differently) which would be impossible otherwise
2623 event.Skip();
2624 break;
2625
2626 // up goes to the previous sibling or to the last
2627 // of its children if it's expanded
2628 case WXK_UP:
2629 {
2630 wxTreeItemId prev = GetPrevSibling( m_key_current );
2631 if (!prev)
2632 {
2633 prev = GetItemParent( m_key_current );
2634 if ((prev == GetRootItem()) && HasFlag(wxTR_HIDE_ROOT))
2635 {
2636 break; // don't go to root if it is hidden
2637 }
2638 if (prev)
2639 {
2640 wxTreeItemIdValue cookie;
2641 wxTreeItemId current = m_key_current;
2642 // TODO: Huh? If we get here, we'd better be the first child of our parent. How else could it be?
2643 if (current == GetFirstChild( prev, cookie ))
2644 {
2645 // otherwise we return to where we came from
2646 DoSelectItem( prev, unselect_others, extended_select );
2647 m_key_current= (wxGenericTreeItem*) prev.m_pItem;
2648 break;
2649 }
2650 }
2651 }
2652 if (prev)
2653 {
2654 while ( IsExpanded(prev) && HasChildren(prev) )
2655 {
2656 wxTreeItemId child = GetLastChild(prev);
2657 if ( child )
2658 {
2659 prev = child;
2660 }
2661 }
2662
2663 DoSelectItem( prev, unselect_others, extended_select );
2664 m_key_current=(wxGenericTreeItem*) prev.m_pItem;
2665 }
2666 }
2667 break;
2668
2669 // left arrow goes to the parent
2670 case WXK_LEFT:
2671 {
2672 wxTreeItemId prev = GetItemParent( m_current );
2673 if ((prev == GetRootItem()) && HasFlag(wxTR_HIDE_ROOT))
2674 {
2675 // don't go to root if it is hidden
2676 prev = GetPrevSibling( m_current );
2677 }
2678 if (prev)
2679 {
2680 DoSelectItem( prev, unselect_others, extended_select );
2681 }
2682 }
2683 break;
2684
2685 case WXK_RIGHT:
2686 // this works the same as the down arrow except that we
2687 // also expand the item if it wasn't expanded yet
2688 Expand(m_current);
2689 // fall through
2690
2691 case WXK_DOWN:
2692 {
2693 if (IsExpanded(m_key_current) && HasChildren(m_key_current))
2694 {
2695 wxTreeItemIdValue cookie;
2696 wxTreeItemId child = GetFirstChild( m_key_current, cookie );
2697 DoSelectItem( child, unselect_others, extended_select );
2698 m_key_current=(wxGenericTreeItem*) child.m_pItem;
2699 }
2700 else
2701 {
2702 wxTreeItemId next = GetNextSibling( m_key_current );
2703 if (!next)
2704 {
2705 wxTreeItemId current = m_key_current;
2706 while (current.IsOk() && !next)
2707 {
2708 current = GetItemParent( current );
2709 if (current) next = GetNextSibling( current );
2710 }
2711 }
2712 if (next)
2713 {
2714 DoSelectItem( next, unselect_others, extended_select );
2715 m_key_current=(wxGenericTreeItem*) next.m_pItem;
2716 }
2717 }
2718 }
2719 break;
2720
2721 // <End> selects the last visible tree item
2722 case WXK_END:
2723 {
2724 wxTreeItemId last = GetRootItem();
2725
2726 while ( last.IsOk() && IsExpanded(last) )
2727 {
2728 wxTreeItemId lastChild = GetLastChild(last);
2729
2730 // it may happen if the item was expanded but then all of
2731 // its children have been deleted - so IsExpanded() returned
2732 // true, but GetLastChild() returned invalid item
2733 if ( !lastChild )
2734 break;
2735
2736 last = lastChild;
2737 }
2738
2739 if ( last.IsOk() )
2740 {
2741 DoSelectItem( last, unselect_others, extended_select );
2742 }
2743 }
2744 break;
2745
2746 // <Home> selects the root item
2747 case WXK_HOME:
2748 {
2749 wxTreeItemId prev = GetRootItem();
2750 if (!prev)
2751 break;
2752
2753 if ( HasFlag(wxTR_HIDE_ROOT) )
2754 {
2755 wxTreeItemIdValue cookie;
2756 prev = GetFirstChild(prev, cookie);
2757 if (!prev)
2758 break;
2759 }
2760
2761 DoSelectItem( prev, unselect_others, extended_select );
2762 }
2763 break;
2764
2765 default:
2766 // do not use wxIsalnum() here
2767 if ( !event.HasModifiers() &&
2768 ((keyCode >= '0' && keyCode <= '9') ||
2769 (keyCode >= 'a' && keyCode <= 'z') ||
2770 (keyCode >= 'A' && keyCode <= 'Z' )))
2771 {
2772 // find the next item starting with the given prefix
2773 wxChar ch = (wxChar)keyCode;
2774
2775 wxTreeItemId id = FindItem(m_current, m_findPrefix + ch);
2776 if ( !id.IsOk() )
2777 {
2778 // no such item
2779 break;
2780 }
2781
2782 SelectItem(id);
2783
2784 m_findPrefix += ch;
2785
2786 // also start the timer to reset the current prefix if the user
2787 // doesn't press any more alnum keys soon -- we wouldn't want
2788 // to use this prefix for a new item search
2789 if ( !m_findTimer )
2790 {
2791 m_findTimer = new wxTreeFindTimer(this);
2792 }
2793
2794 m_findTimer->Start(wxTreeFindTimer::DELAY, wxTIMER_ONE_SHOT);
2795 }
2796 else
2797 {
2798 event.Skip();
2799 }
2800 }
2801 }
2802
2803 wxTreeItemId wxGenericTreeCtrl::HitTest(const wxPoint& point, int& flags)
2804 {
2805 // JACS: removed wxYieldIfNeeded() because it can cause the window
2806 // to be deleted from under us if a close window event is pending
2807
2808 int w, h;
2809 GetSize(&w, &h);
2810 flags=0;
2811 if (point.x<0) flags |= wxTREE_HITTEST_TOLEFT;
2812 if (point.x>w) flags |= wxTREE_HITTEST_TORIGHT;
2813 if (point.y<0) flags |= wxTREE_HITTEST_ABOVE;
2814 if (point.y>h) flags |= wxTREE_HITTEST_BELOW;
2815 if (flags) return wxTreeItemId();
2816
2817 if (m_anchor == NULL)
2818 {
2819 flags = wxTREE_HITTEST_NOWHERE;
2820 return wxTreeItemId();
2821 }
2822
2823 wxGenericTreeItem *hit = m_anchor->HitTest(CalcUnscrolledPosition(point),
2824 this, flags, 0);
2825 if (hit == NULL)
2826 {
2827 flags = wxTREE_HITTEST_NOWHERE;
2828 return wxTreeItemId();
2829 }
2830 return hit;
2831 }
2832
2833 // get the bounding rectangle of the item (or of its label only)
2834 bool wxGenericTreeCtrl::GetBoundingRect(const wxTreeItemId& item,
2835 wxRect& rect,
2836 bool WXUNUSED(textOnly)) const
2837 {
2838 wxCHECK_MSG( item.IsOk(), false, _T("invalid item in wxGenericTreeCtrl::GetBoundingRect") );
2839
2840 wxGenericTreeItem *i = (wxGenericTreeItem*) item.m_pItem;
2841
2842 int startX, startY;
2843 GetViewStart(& startX, & startY);
2844
2845 rect.x = i->GetX() - startX*PIXELS_PER_UNIT;
2846 rect.y = i->GetY() - startY*PIXELS_PER_UNIT;
2847 rect.width = i->GetWidth();
2848 //rect.height = i->GetHeight();
2849 rect.height = GetLineHeight(i);
2850
2851 return true;
2852 }
2853
2854 void wxGenericTreeCtrl::Edit( const wxTreeItemId& item )
2855 {
2856 wxCHECK_RET( item.IsOk(), _T("can't edit an invalid item") );
2857
2858 wxGenericTreeItem *itemEdit = (wxGenericTreeItem *)item.m_pItem;
2859
2860 wxTreeEvent te( wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT, GetId() );
2861 te.m_item = itemEdit;
2862 te.SetEventObject( this );
2863 if ( GetEventHandler()->ProcessEvent( te ) && !te.IsAllowed() )
2864 {
2865 // vetoed by user
2866 return;
2867 }
2868
2869 // We have to call this here because the label in
2870 // question might just have been added and no screen
2871 // update taken place.
2872 if ( m_dirty )
2873 #if defined( __WXMSW__ ) || defined(__WXMAC__)
2874 Update();
2875 #else
2876 wxYieldIfNeeded();
2877 #endif
2878
2879 m_textCtrl = new wxTreeTextCtrl(this, itemEdit);
2880
2881 m_textCtrl->SetFocus();
2882 }
2883
2884 // returns a pointer to the text edit control if the item is being
2885 // edited, NULL otherwise (it's assumed that no more than one item may
2886 // be edited simultaneously)
2887 wxTextCtrl* wxGenericTreeCtrl::GetEditControl() const
2888 {
2889 return m_textCtrl;
2890 }
2891
2892 bool wxGenericTreeCtrl::OnRenameAccept(wxGenericTreeItem *item,
2893 const wxString& value)
2894 {
2895 wxTreeEvent le( wxEVT_COMMAND_TREE_END_LABEL_EDIT, GetId() );
2896 le.m_item = item;
2897 le.SetEventObject( this );
2898 le.m_label = value;
2899 le.m_editCancelled = false;
2900
2901 return !GetEventHandler()->ProcessEvent( le ) || le.IsAllowed();
2902 }
2903
2904 void wxGenericTreeCtrl::OnRenameCancelled(wxGenericTreeItem *item)
2905 {
2906 // let owner know that the edit was cancelled
2907 wxTreeEvent le( wxEVT_COMMAND_TREE_END_LABEL_EDIT, GetId() );
2908 le.m_item = item;
2909 le.SetEventObject( this );
2910 le.m_label = wxEmptyString;
2911 le.m_editCancelled = true;
2912
2913 GetEventHandler()->ProcessEvent( le );
2914 }
2915
2916
2917
2918
2919 void wxGenericTreeCtrl::OnRenameTimer()
2920 {
2921 Edit( m_current );
2922 }
2923
2924 void wxGenericTreeCtrl::OnMouse( wxMouseEvent &event )
2925 {
2926 if ( !m_anchor ) return;
2927
2928 wxPoint pt = CalcUnscrolledPosition(event.GetPosition());
2929
2930 // Is the mouse over a tree item button?
2931 int flags = 0;
2932 wxGenericTreeItem *thisItem = m_anchor->HitTest(pt, this, flags, 0);
2933 wxGenericTreeItem *underMouse = thisItem;
2934 #if wxUSE_TOOLTIPS
2935 bool underMouseChanged = (underMouse != m_underMouse) ;
2936 #endif // wxUSE_TOOLTIPS
2937
2938 if ((underMouse) &&
2939 (flags & wxTREE_HITTEST_ONITEMBUTTON) &&
2940 (!event.LeftIsDown()) &&
2941 (!m_isDragging) &&
2942 (!m_renameTimer || !m_renameTimer->IsRunning()))
2943 {
2944 }
2945 else
2946 {
2947 underMouse = NULL;
2948 }
2949
2950 if (underMouse != m_underMouse)
2951 {
2952 if (m_underMouse)
2953 {
2954 // unhighlight old item
2955 wxGenericTreeItem *tmp = m_underMouse;
2956 m_underMouse = NULL;
2957 RefreshLine( tmp );
2958 }
2959
2960 m_underMouse = underMouse;
2961 if (m_underMouse)
2962 RefreshLine( m_underMouse );
2963 }
2964
2965 #if wxUSE_TOOLTIPS
2966 // Determines what item we are hovering over and need a tooltip for
2967 wxTreeItemId hoverItem = thisItem;
2968
2969 // We do not want a tooltip if we are dragging, or if the rename timer is running
2970 if (underMouseChanged && hoverItem.IsOk() && !m_isDragging && (!m_renameTimer || !m_renameTimer->IsRunning()))
2971 {
2972 // Ask the tree control what tooltip (if any) should be shown
2973 wxTreeEvent hevent(wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP, GetId());
2974 hevent.m_item = hoverItem;
2975 hevent.SetEventObject(this);
2976
2977 if ( GetEventHandler()->ProcessEvent(hevent) && hevent.IsAllowed() )
2978 {
2979 SetToolTip(hevent.m_label);
2980 }
2981 }
2982 #endif
2983
2984 // we process left mouse up event (enables in-place edit), right down
2985 // (pass to the user code), left dbl click (activate item) and
2986 // dragging/moving events for items drag-and-drop
2987 if ( !(event.LeftDown() ||
2988 event.LeftUp() ||
2989 event.RightDown() ||
2990 event.LeftDClick() ||
2991 event.Dragging() ||
2992 ((event.Moving() || event.RightUp()) && m_isDragging)) )
2993 {
2994 event.Skip();
2995
2996 return;
2997 }
2998
2999
3000 flags = 0;
3001 wxGenericTreeItem *item = m_anchor->HitTest(pt, this, flags, 0);
3002
3003 if ( event.Dragging() && !m_isDragging )
3004 {
3005 if (m_dragCount == 0)
3006 m_dragStart = pt;
3007
3008 m_dragCount++;
3009
3010 if (m_dragCount != 3)
3011 {
3012 // wait until user drags a bit further...
3013 return;
3014 }
3015
3016 wxEventType command = event.RightIsDown()
3017 ? wxEVT_COMMAND_TREE_BEGIN_RDRAG
3018 : wxEVT_COMMAND_TREE_BEGIN_DRAG;
3019
3020 wxTreeEvent nevent( command, GetId() );
3021 nevent.m_item = m_current;
3022 nevent.SetEventObject(this);
3023
3024 // by default the dragging is not supported, the user code must
3025 // explicitly allow the event for it to take place
3026 nevent.Veto();
3027
3028 if ( GetEventHandler()->ProcessEvent(nevent) && nevent.IsAllowed() )
3029 {
3030 // we're going to drag this item
3031 m_isDragging = true;
3032
3033 // remember the old cursor because we will change it while
3034 // dragging
3035 m_oldCursor = m_cursor;
3036
3037 // in a single selection control, hide the selection temporarily
3038 if ( !(GetWindowStyleFlag() & wxTR_MULTIPLE) )
3039 {
3040 m_oldSelection = (wxGenericTreeItem*) GetSelection().m_pItem;
3041
3042 if ( m_oldSelection )
3043 {
3044 m_oldSelection->SetHilight(false);
3045 RefreshLine(m_oldSelection);
3046 }
3047 }
3048
3049 CaptureMouse();
3050 }
3051 }
3052 else if ( event.Moving() )
3053 {
3054 if ( item != m_dropTarget )
3055 {
3056 // unhighlight the previous drop target
3057 DrawDropEffect(m_dropTarget);
3058
3059 m_dropTarget = item;
3060
3061 // highlight the current drop target if any
3062 DrawDropEffect(m_dropTarget);
3063
3064 #if defined( __WXMSW__ ) || defined(__WXMAC__)
3065 Update();
3066 #else
3067 wxYieldIfNeeded();
3068 #endif
3069 }
3070 }
3071 else if ( (event.LeftUp() || event.RightUp()) && m_isDragging )
3072 {
3073 // erase the highlighting
3074 DrawDropEffect(m_dropTarget);
3075
3076 if ( m_oldSelection )
3077 {
3078 m_oldSelection->SetHilight(true);
3079 RefreshLine(m_oldSelection);
3080 m_oldSelection = (wxGenericTreeItem *)NULL;
3081 }
3082
3083 // generate the drag end event
3084 wxTreeEvent event(wxEVT_COMMAND_TREE_END_DRAG, GetId());
3085
3086 event.m_item = item;
3087 event.m_pointDrag = pt;
3088 event.SetEventObject(this);
3089
3090 (void)GetEventHandler()->ProcessEvent(event);
3091
3092 m_isDragging = false;
3093 m_dropTarget = (wxGenericTreeItem *)NULL;
3094
3095 ReleaseMouse();
3096
3097 SetCursor(m_oldCursor);
3098
3099 #if defined( __WXMSW__ ) || defined(__WXMAC__)
3100 Update();
3101 #else
3102 wxYieldIfNeeded();
3103 #endif
3104 }
3105 else
3106 {
3107 // here we process only the messages which happen on tree items
3108
3109 m_dragCount = 0;
3110
3111 if (item == NULL) return; /* we hit the blank area */
3112
3113 if ( event.RightDown() )
3114 {
3115 wxTreeEvent nevent(wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK, GetId());
3116 nevent.m_item = item;
3117 nevent.m_pointDrag = CalcScrolledPosition(pt);
3118 nevent.SetEventObject(this);
3119 GetEventHandler()->ProcessEvent(nevent);
3120 }
3121 else if ( event.LeftUp() )
3122 {
3123 // this facilitates multiple-item drag-and-drop
3124
3125 if (item && HasFlag(wxTR_MULTIPLE))
3126 {
3127 wxArrayTreeItemIds selections;
3128 size_t count = GetSelections(selections);
3129
3130 if (count > 1 &&
3131 !event.ControlDown() &&
3132 !event.ShiftDown())
3133 {
3134 DoSelectItem(item, true, false);
3135 }
3136 }
3137
3138 if ( m_lastOnSame )
3139 {
3140 if ( (item == m_current) &&
3141 (flags & wxTREE_HITTEST_ONITEMLABEL) &&
3142 HasFlag(wxTR_EDIT_LABELS) )
3143 {
3144 if ( m_renameTimer )
3145 {
3146 if ( m_renameTimer->IsRunning() )
3147 m_renameTimer->Stop();
3148 }
3149 else
3150 {
3151 m_renameTimer = new wxTreeRenameTimer( this );
3152 }
3153
3154 m_renameTimer->Start( wxTreeRenameTimer::DELAY, true );
3155 }
3156
3157 m_lastOnSame = false;
3158 }
3159 }
3160 else // !RightDown() && !LeftUp() ==> LeftDown() || LeftDClick()
3161 {
3162 if ( event.LeftDown() )
3163 {
3164 m_lastOnSame = item == m_current;
3165 }
3166
3167 if ( flags & wxTREE_HITTEST_ONITEMBUTTON )
3168 {
3169 // only toggle the item for a single click, double click on
3170 // the button doesn't do anything (it toggles the item twice)
3171 if ( event.LeftDown() )
3172 {
3173 Toggle( item );
3174 }
3175
3176 // don't select the item if the button was clicked
3177 return;
3178 }
3179
3180
3181 // clear the previously selected items, if the
3182 // user clicked outside of the present selection.
3183 // otherwise, perform the deselection on mouse-up.
3184 // this allows multiple drag and drop to work.
3185
3186 if (!IsSelected(item))
3187 {
3188 // how should the selection work for this event?
3189 bool is_multiple, extended_select, unselect_others;
3190 EventFlagsToSelType(GetWindowStyleFlag(),
3191 event.ShiftDown(),
3192 event.ControlDown(),
3193 is_multiple, extended_select, unselect_others);
3194
3195 DoSelectItem(item, unselect_others, extended_select);
3196 }
3197
3198
3199 // For some reason, Windows isn't recognizing a left double-click,
3200 // so we need to simulate it here. Allow 200 milliseconds for now.
3201 if ( event.LeftDClick() )
3202 {
3203 // double clicking should not start editing the item label
3204 if ( m_renameTimer )
3205 m_renameTimer->Stop();
3206
3207 m_lastOnSame = false;
3208
3209 // send activate event first
3210 wxTreeEvent nevent( wxEVT_COMMAND_TREE_ITEM_ACTIVATED, GetId() );
3211 nevent.m_item = item;
3212 nevent.m_pointDrag = CalcScrolledPosition(pt);
3213 nevent.SetEventObject( this );
3214 if ( !GetEventHandler()->ProcessEvent( nevent ) )
3215 {
3216 // if the user code didn't process the activate event,
3217 // handle it ourselves by toggling the item when it is
3218 // double clicked
3219 if ( item->HasPlus() )
3220 {
3221 Toggle(item);
3222 }
3223 }
3224 }
3225 }
3226 }
3227 }
3228
3229 void wxGenericTreeCtrl::OnInternalIdle()
3230 {
3231 wxWindow::OnInternalIdle();
3232
3233 // Check if we need to select the root item
3234 // because nothing else has been selected.
3235 // Delaying it means that we can invoke event handlers
3236 // as required, when a first item is selected.
3237 if (!HasFlag(wxTR_MULTIPLE) && !GetSelection().IsOk())
3238 {
3239 if (m_select_me)
3240 SelectItem(m_select_me);
3241 else if (GetRootItem().IsOk())
3242 SelectItem(GetRootItem());
3243 }
3244
3245 /* after all changes have been done to the tree control,
3246 * we actually redraw the tree when everything is over */
3247
3248 if (!m_dirty) return;
3249 if (m_freezeCount) return;
3250
3251 m_dirty = false;
3252
3253 CalculatePositions();
3254 Refresh();
3255 AdjustMyScrollbars();
3256 }
3257
3258 void wxGenericTreeCtrl::CalculateSize( wxGenericTreeItem *item, wxDC &dc )
3259 {
3260 wxCoord text_w = 0;
3261 wxCoord text_h = 0;
3262
3263 wxTreeItemAttr *attr = item->GetAttributes();
3264 if ( attr && attr->HasFont() )
3265 dc.SetFont(attr->GetFont());
3266 else if ( item->IsBold() )
3267 dc.SetFont(m_boldFont);
3268 else
3269 dc.SetFont(m_normalFont);
3270
3271 dc.GetTextExtent( item->GetText(), &text_w, &text_h );
3272 text_h+=2;
3273
3274 // restore normal font
3275 dc.SetFont( m_normalFont );
3276
3277 int image_h = 0;
3278 int image_w = 0;
3279 int image = item->GetCurrentImage();
3280 if ( image != NO_IMAGE )
3281 {
3282 if ( m_imageListNormal )
3283 {
3284 m_imageListNormal->GetSize( image, image_w, image_h );
3285 image_w += 4;
3286 }
3287 }
3288
3289 int total_h = (image_h > text_h) ? image_h : text_h;
3290
3291 if (total_h < 30)
3292 total_h += 2; // at least 2 pixels
3293 else
3294 total_h += total_h/10; // otherwise 10% extra spacing
3295
3296 item->SetHeight(total_h);
3297 if (total_h>m_lineHeight)
3298 m_lineHeight=total_h;
3299
3300 item->SetWidth(image_w+text_w+2);
3301 }
3302
3303 // -----------------------------------------------------------------------------
3304 // for developper : y is now the top of the level
3305 // not the middle of it !
3306 void wxGenericTreeCtrl::CalculateLevel( wxGenericTreeItem *item, wxDC &dc, int level, int &y )
3307 {
3308 int x = level*m_indent;
3309 if (!HasFlag(wxTR_HIDE_ROOT))
3310 {
3311 x += m_indent;
3312 }
3313 else if (level == 0)
3314 {
3315 // a hidden root is not evaluated, but its
3316 // children are always calculated
3317 goto Recurse;
3318 }
3319
3320 CalculateSize( item, dc );
3321
3322 // set its position
3323 item->SetX( x+m_spacing );
3324 item->SetY( y );
3325 y += GetLineHeight(item);
3326
3327 if ( !item->IsExpanded() )
3328 {
3329 // we don't need to calculate collapsed branches
3330 return;
3331 }
3332
3333 Recurse:
3334 wxArrayGenericTreeItems& children = item->GetChildren();
3335 size_t n, count = children.Count();
3336 ++level;
3337 for (n = 0; n < count; ++n )
3338 CalculateLevel( children[n], dc, level, y ); // recurse
3339 }
3340
3341 void wxGenericTreeCtrl::CalculatePositions()
3342 {
3343 if ( !m_anchor ) return;
3344
3345 wxClientDC dc(this);
3346 PrepareDC( dc );
3347
3348 dc.SetFont( m_normalFont );
3349
3350 dc.SetPen( m_dottedPen );
3351 //if(GetImageList() == NULL)
3352 // m_lineHeight = (int)(dc.GetCharHeight() + 4);
3353
3354 int y = 2;
3355 CalculateLevel( m_anchor, dc, 0, y ); // start recursion
3356 }
3357
3358 void wxGenericTreeCtrl::RefreshSubtree(wxGenericTreeItem *item)
3359 {
3360 if (m_dirty) return;
3361 if (m_freezeCount) return;
3362
3363 wxSize client = GetClientSize();
3364
3365 wxRect rect;
3366 CalcScrolledPosition(0, item->GetY(), NULL, &rect.y);
3367 rect.width = client.x;
3368 rect.height = client.y;
3369
3370 Refresh(true, &rect);
3371
3372 AdjustMyScrollbars();
3373 }
3374
3375 void wxGenericTreeCtrl::RefreshLine( wxGenericTreeItem *item )
3376 {
3377 if (m_dirty) return;
3378 if (m_freezeCount) return;
3379
3380 wxRect rect;
3381 CalcScrolledPosition(0, item->GetY(), NULL, &rect.y);
3382 rect.width = GetClientSize().x;
3383 rect.height = GetLineHeight(item); //dc.GetCharHeight() + 6;
3384
3385 Refresh(true, &rect);
3386 }
3387
3388 void wxGenericTreeCtrl::RefreshSelected()
3389 {
3390 if (m_freezeCount) return;
3391
3392 // TODO: this is awfully inefficient, we should keep the list of all
3393 // selected items internally, should be much faster
3394 if ( m_anchor )
3395 RefreshSelectedUnder(m_anchor);
3396 }
3397
3398 void wxGenericTreeCtrl::RefreshSelectedUnder(wxGenericTreeItem *item)
3399 {
3400 if (m_freezeCount) return;
3401
3402 if ( item->IsSelected() )
3403 RefreshLine(item);
3404
3405 const wxArrayGenericTreeItems& children = item->GetChildren();
3406 size_t count = children.GetCount();
3407 for ( size_t n = 0; n < count; n++ )
3408 {
3409 RefreshSelectedUnder(children[n]);
3410 }
3411 }
3412
3413 void wxGenericTreeCtrl::Freeze()
3414 {
3415 m_freezeCount++;
3416 }
3417
3418 void wxGenericTreeCtrl::Thaw()
3419 {
3420 wxCHECK_RET( m_freezeCount > 0, _T("thawing unfrozen tree control?") );
3421
3422 if ( !--m_freezeCount )
3423 {
3424 Refresh();
3425 }
3426 }
3427
3428 // ----------------------------------------------------------------------------
3429 // changing colours: we need to refresh the tree control
3430 // ----------------------------------------------------------------------------
3431
3432 bool wxGenericTreeCtrl::SetBackgroundColour(const wxColour& colour)
3433 {
3434 if ( !wxWindow::SetBackgroundColour(colour) )
3435 return false;
3436
3437 if (m_freezeCount) return true;
3438
3439 Refresh();
3440
3441 return true;
3442 }
3443
3444 bool wxGenericTreeCtrl::SetForegroundColour(const wxColour& colour)
3445 {
3446 if ( !wxWindow::SetForegroundColour(colour) )
3447 return false;
3448
3449 if (m_freezeCount) return true;
3450
3451 Refresh();
3452
3453 return true;
3454 }
3455
3456 // Process the tooltip event, to speed up event processing.
3457 // Doesn't actually get a tooltip.
3458 void wxGenericTreeCtrl::OnGetToolTip( wxTreeEvent &event )
3459 {
3460 event.Veto();
3461 }
3462
3463
3464 // NOTE: If using the wxListBox visual attributes works everywhere then this can
3465 // be removed, as well as the #else case below.
3466 #define _USE_VISATTR 0
3467
3468 #if _USE_VISATTR
3469 #include "wx/listbox.h"
3470 #endif
3471
3472 //static
3473 wxVisualAttributes
3474 #if _USE_VISATTR
3475 wxGenericTreeCtrl::GetClassDefaultAttributes(wxWindowVariant variant)
3476 #else
3477 wxGenericTreeCtrl::GetClassDefaultAttributes(wxWindowVariant WXUNUSED(variant))
3478 #endif
3479 {
3480 #if _USE_VISATTR
3481 // Use the same color scheme as wxListBox
3482 return wxListBox::GetClassDefaultAttributes(variant);
3483 #else
3484 wxVisualAttributes attr;
3485 attr.colFg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
3486 attr.colBg = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX);
3487 attr.font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
3488 return attr;
3489 #endif
3490 }
3491
3492 #endif // wxUSE_TREECTRL