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