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