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