1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/treectrl.cpp
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin to be less MSW-specific on 10.10.98
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
29 #include "wx/treectrl.h"
32 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
33 #include "wx/msw/missing.h"
34 #include "wx/dynarray.h"
37 #include "wx/settings.h"
40 #include "wx/dynlib.h"
41 #include "wx/msw/private.h"
43 // Set this to 1 to be _absolutely_ sure that repainting will work for all
44 // comctl32.dll versions
45 #define wxUSE_COMCTL32_SAFELY 0
47 #include "wx/imaglist.h"
48 #include "wx/msw/dragimag.h"
50 // macros to hide the cast ugliness
51 // --------------------------------
53 // get HTREEITEM from wxTreeItemId
54 #define HITEM(item) ((HTREEITEM)(((item).m_pItem)))
57 // older SDKs are missing these
58 #ifndef TVN_ITEMCHANGINGA
60 #define TVN_ITEMCHANGINGA (TVN_FIRST-16)
61 #define TVN_ITEMCHANGINGW (TVN_FIRST-17)
63 typedef struct tagNMTVITEMCHANGE
76 // this helper class is used on vista systems for preventing unwanted
77 // item state changes in the vista tree control. It is only effective in
78 // multi-select mode on vista systems.
80 // The vista tree control includes some new code that originally broke the
81 // multi-selection tree, causing seemingly spurious item selection state changes
82 // during Shift or Ctrl-click item selection. (To witness the original broken
83 // behavior, simply make IsLocked() below always return false). This problem was
84 // solved by using the following class to 'unlock' an item's selection state.
86 class TreeItemUnlocker
89 // unlock a single item
90 TreeItemUnlocker(HTREEITEM item
) { ms_unlockedItem
= item
; }
92 // unlock all items, don't use unless absolutely necessary
93 TreeItemUnlocker() { ms_unlockedItem
= (HTREEITEM
)-1; }
95 // lock everything back
96 ~TreeItemUnlocker() { ms_unlockedItem
= NULL
; }
99 // check if the item state is currently locked
100 static bool IsLocked(HTREEITEM item
)
101 { return ms_unlockedItem
!= (HTREEITEM
)-1 && item
!= ms_unlockedItem
; }
104 static HTREEITEM ms_unlockedItem
;
107 HTREEITEM
TreeItemUnlocker::ms_unlockedItem
= NULL
;
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
113 // wrappers for TreeView_GetItem/TreeView_SetItem
114 static bool IsItemSelected(HWND hwndTV
, HTREEITEM hItem
)
118 tvi
.mask
= TVIF_STATE
| TVIF_HANDLE
;
119 tvi
.stateMask
= TVIS_SELECTED
;
122 TreeItemUnlocker
unlocker(hItem
);
124 if ( !TreeView_GetItem(hwndTV
, &tvi
) )
126 wxLogLastError(wxT("TreeView_GetItem"));
129 return (tvi
.state
& TVIS_SELECTED
) != 0;
132 static bool SelectItem(HWND hwndTV
, HTREEITEM hItem
, bool select
= true)
135 tvi
.mask
= TVIF_STATE
| TVIF_HANDLE
;
136 tvi
.stateMask
= TVIS_SELECTED
;
137 tvi
.state
= select
? TVIS_SELECTED
: 0;
140 TreeItemUnlocker
unlocker(hItem
);
142 if ( TreeView_SetItem(hwndTV
, &tvi
) == -1 )
144 wxLogLastError(wxT("TreeView_SetItem"));
151 static inline void UnselectItem(HWND hwndTV
, HTREEITEM htItem
)
153 SelectItem(hwndTV
, htItem
, false);
156 // helper function which selects all items in a range and, optionally,
157 // unselects all others
158 static void SelectRange(HWND hwndTV
,
161 bool unselectOthers
= true)
163 // find the first (or last) item and select it
165 HTREEITEM htItem
= (HTREEITEM
)TreeView_GetRoot(hwndTV
);
166 while ( htItem
&& cont
)
168 if ( (htItem
== htFirst
) || (htItem
== htLast
) )
170 if ( !IsItemSelected(hwndTV
, htItem
) )
172 SelectItem(hwndTV
, htItem
);
179 if ( unselectOthers
&& IsItemSelected(hwndTV
, htItem
) )
181 UnselectItem(hwndTV
, htItem
);
185 htItem
= (HTREEITEM
)TreeView_GetNextVisible(hwndTV
, htItem
);
188 // select the items in range
189 cont
= htFirst
!= htLast
;
190 while ( htItem
&& cont
)
192 if ( !IsItemSelected(hwndTV
, htItem
) )
194 SelectItem(hwndTV
, htItem
);
197 cont
= (htItem
!= htFirst
) && (htItem
!= htLast
);
199 htItem
= (HTREEITEM
)TreeView_GetNextVisible(hwndTV
, htItem
);
203 if ( unselectOthers
)
207 if ( IsItemSelected(hwndTV
, htItem
) )
209 UnselectItem(hwndTV
, htItem
);
212 htItem
= (HTREEITEM
)TreeView_GetNextVisible(hwndTV
, htItem
);
216 // seems to be necessary - otherwise the just selected items don't always
217 // appear as selected
218 UpdateWindow(hwndTV
);
221 // helper function which tricks the standard control into changing the focused
222 // item without changing anything else (if someone knows why Microsoft doesn't
223 // allow to do it by just setting TVIS_FOCUSED flag, please tell me!)
225 // returns true if the focus was changed, false if the given item was already
227 static bool SetFocus(HWND hwndTV
, HTREEITEM htItem
)
230 HTREEITEM htFocus
= (HTREEITEM
)TreeView_GetSelection(hwndTV
);
232 if ( htItem
== htFocus
)
237 // remember the selection state of the item
238 bool wasSelected
= IsItemSelected(hwndTV
, htItem
);
240 if ( htFocus
&& IsItemSelected(hwndTV
, htFocus
) )
242 // prevent the tree from unselecting the old focus which it
243 // would do by default (TreeView_SelectItem unselects the
245 TreeView_SelectItem(hwndTV
, 0);
246 SelectItem(hwndTV
, htFocus
);
249 TreeView_SelectItem(hwndTV
, htItem
);
253 // need to clear the selection which TreeView_SelectItem() gave
255 UnselectItem(hwndTV
, htItem
);
257 //else: was selected, still selected - ok
261 bool wasFocusSelected
= IsItemSelected(hwndTV
, htFocus
);
263 // just clear the focus
264 TreeView_SelectItem(hwndTV
, 0);
266 if ( wasFocusSelected
)
268 // restore the selection state
269 SelectItem(hwndTV
, htFocus
);
276 // ----------------------------------------------------------------------------
278 // ----------------------------------------------------------------------------
280 // a convenient wrapper around TV_ITEM struct which adds a ctor
282 #pragma warning( disable : 4097 ) // inheriting from typedef
285 struct wxTreeViewItem
: public TV_ITEM
287 wxTreeViewItem(const wxTreeItemId
& item
, // the item handle
288 UINT mask_
, // fields which are valid
289 UINT stateMask_
= 0) // for TVIF_STATE only
293 // hItem member is always valid
294 mask
= mask_
| TVIF_HANDLE
;
295 stateMask
= stateMask_
;
300 // ----------------------------------------------------------------------------
301 // This class is our userdata/lParam for the TV_ITEMs stored in the treeview.
303 // We need this for a couple of reasons:
305 // 1) This class is needed for support of different images: the Win32 common
306 // control natively supports only 2 images (the normal one and another for the
307 // selected state). We wish to provide support for 2 more of them for folder
308 // items (i.e. those which have children): for expanded state and for expanded
309 // selected state. For this we use this structure to store the additional items
312 // 2) This class is also needed to hold the HITEM so that we can sort
313 // it correctly in the MSW sort callback.
315 // In addition it makes other workarounds such as this easier and helps
316 // simplify the code.
317 // ----------------------------------------------------------------------------
319 class wxTreeItemParam
326 for ( size_t n
= 0; n
< WXSIZEOF(m_images
); n
++ )
332 // dtor deletes the associated data as well
333 virtual ~wxTreeItemParam() { delete m_data
; }
336 // get the real data associated with the item
337 wxTreeItemData
*GetData() const { return m_data
; }
339 void SetData(wxTreeItemData
*data
) { m_data
= data
; }
341 // do we have such image?
342 bool HasImage(wxTreeItemIcon which
) const { return m_images
[which
] != -1; }
343 // get image, falling back to the other images if this one is not
345 int GetImage(wxTreeItemIcon which
) const
347 int image
= m_images
[which
];
352 case wxTreeItemIcon_SelectedExpanded
:
353 image
= GetImage(wxTreeItemIcon_Expanded
);
358 case wxTreeItemIcon_Selected
:
359 case wxTreeItemIcon_Expanded
:
360 image
= GetImage(wxTreeItemIcon_Normal
);
363 case wxTreeItemIcon_Normal
:
368 wxFAIL_MSG( _T("unsupported wxTreeItemIcon value") );
374 // change the given image
375 void SetImage(int image
, wxTreeItemIcon which
) { m_images
[which
] = image
; }
378 const wxTreeItemId
& GetItem() const { return m_item
; }
380 void SetItem(const wxTreeItemId
& item
) { m_item
= item
; }
383 // all the images associated with the item
384 int m_images
[wxTreeItemIcon_Max
];
386 // item for sort callbacks
389 // the real client data
390 wxTreeItemData
*m_data
;
392 DECLARE_NO_COPY_CLASS(wxTreeItemParam
)
395 // wxVirutalNode is used in place of a single root when 'hidden' root is
397 class wxVirtualNode
: public wxTreeViewItem
400 wxVirtualNode(wxTreeItemParam
*param
)
401 : wxTreeViewItem(TVI_ROOT
, 0)
411 wxTreeItemParam
*GetParam() const { return m_param
; }
412 void SetParam(wxTreeItemParam
*param
) { delete m_param
; m_param
= param
; }
415 wxTreeItemParam
*m_param
;
417 DECLARE_NO_COPY_CLASS(wxVirtualNode
)
421 #pragma warning( default : 4097 )
424 // a macro to get the virtual root, returns NULL if none
425 #define GET_VIRTUAL_ROOT() ((wxVirtualNode *)m_pVirtualRoot)
427 // returns true if the item is the virtual root
428 #define IS_VIRTUAL_ROOT(item) (HITEM(item) == TVI_ROOT)
430 // a class which encapsulates the tree traversal logic: it vists all (unless
431 // OnVisit() returns false) items under the given one
432 class wxTreeTraversal
435 wxTreeTraversal(const wxTreeCtrl
*tree
)
440 // give it a virtual dtor: not really needed as the class is never used
441 // polymorphically and not even allocated on heap at all, but this is safer
442 // (in case it ever is) and silences the compiler warnings for now
443 virtual ~wxTreeTraversal() { }
445 // do traverse the tree: visit all items (recursively by default) under the
446 // given one; return true if all items were traversed or false if the
447 // traversal was aborted because OnVisit returned false
448 bool DoTraverse(const wxTreeItemId
& root
, bool recursively
= true);
450 // override this function to do whatever is needed for each item, return
451 // false to stop traversing
452 virtual bool OnVisit(const wxTreeItemId
& item
) = 0;
455 const wxTreeCtrl
*GetTree() const { return m_tree
; }
458 bool Traverse(const wxTreeItemId
& root
, bool recursively
);
460 const wxTreeCtrl
*m_tree
;
462 DECLARE_NO_COPY_CLASS(wxTreeTraversal
)
465 // internal class for getting the selected items
466 class TraverseSelections
: public wxTreeTraversal
469 TraverseSelections(const wxTreeCtrl
*tree
,
470 wxArrayTreeItemIds
& selections
)
471 : wxTreeTraversal(tree
), m_selections(selections
)
473 m_selections
.Empty();
475 if (tree
->GetCount() > 0)
476 DoTraverse(tree
->GetRootItem());
479 virtual bool OnVisit(const wxTreeItemId
& item
)
481 const wxTreeCtrl
* const tree
= GetTree();
483 // can't visit a virtual node.
484 if ( (tree
->GetRootItem() == item
) && tree
->HasFlag(wxTR_HIDE_ROOT
) )
489 if ( ::IsItemSelected(GetHwndOf(tree
), HITEM(item
)) )
491 m_selections
.Add(item
);
497 size_t GetCount() const { return m_selections
.GetCount(); }
500 wxArrayTreeItemIds
& m_selections
;
502 DECLARE_NO_COPY_CLASS(TraverseSelections
)
505 // internal class for counting tree items
506 class TraverseCounter
: public wxTreeTraversal
509 TraverseCounter(const wxTreeCtrl
*tree
,
510 const wxTreeItemId
& root
,
512 : wxTreeTraversal(tree
)
516 DoTraverse(root
, recursively
);
519 virtual bool OnVisit(const wxTreeItemId
& WXUNUSED(item
))
526 size_t GetCount() const { return m_count
; }
531 DECLARE_NO_COPY_CLASS(TraverseCounter
)
534 // ----------------------------------------------------------------------------
536 // ----------------------------------------------------------------------------
538 #if wxUSE_EXTENDED_RTTI
539 WX_DEFINE_FLAGS( wxTreeCtrlStyle
)
541 wxBEGIN_FLAGS( wxTreeCtrlStyle
)
542 // new style border flags, we put them first to
543 // use them for streaming out
544 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
545 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
546 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
547 wxFLAGS_MEMBER(wxBORDER_RAISED
)
548 wxFLAGS_MEMBER(wxBORDER_STATIC
)
549 wxFLAGS_MEMBER(wxBORDER_NONE
)
551 // old style border flags
552 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
553 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
554 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
555 wxFLAGS_MEMBER(wxRAISED_BORDER
)
556 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
557 wxFLAGS_MEMBER(wxBORDER
)
559 // standard window styles
560 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
561 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
562 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
563 wxFLAGS_MEMBER(wxWANTS_CHARS
)
564 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
565 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
566 wxFLAGS_MEMBER(wxVSCROLL
)
567 wxFLAGS_MEMBER(wxHSCROLL
)
569 wxFLAGS_MEMBER(wxTR_EDIT_LABELS
)
570 wxFLAGS_MEMBER(wxTR_NO_BUTTONS
)
571 wxFLAGS_MEMBER(wxTR_HAS_BUTTONS
)
572 wxFLAGS_MEMBER(wxTR_TWIST_BUTTONS
)
573 wxFLAGS_MEMBER(wxTR_NO_LINES
)
574 wxFLAGS_MEMBER(wxTR_FULL_ROW_HIGHLIGHT
)
575 wxFLAGS_MEMBER(wxTR_LINES_AT_ROOT
)
576 wxFLAGS_MEMBER(wxTR_HIDE_ROOT
)
577 wxFLAGS_MEMBER(wxTR_ROW_LINES
)
578 wxFLAGS_MEMBER(wxTR_HAS_VARIABLE_ROW_HEIGHT
)
579 wxFLAGS_MEMBER(wxTR_SINGLE
)
580 wxFLAGS_MEMBER(wxTR_MULTIPLE
)
581 #if WXWIN_COMPATIBILITY_2_8
582 wxFLAGS_MEMBER(wxTR_EXTENDED
)
584 wxFLAGS_MEMBER(wxTR_DEFAULT_STYLE
)
586 wxEND_FLAGS( wxTreeCtrlStyle
)
588 IMPLEMENT_DYNAMIC_CLASS_XTI(wxTreeCtrl
, wxControl
,"wx/treectrl.h")
590 wxBEGIN_PROPERTIES_TABLE(wxTreeCtrl
)
591 wxEVENT_PROPERTY( TextUpdated
, wxEVT_COMMAND_TEXT_UPDATED
, wxCommandEvent
)
592 wxEVENT_RANGE_PROPERTY( TreeEvent
, wxEVT_COMMAND_TREE_BEGIN_DRAG
, wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK
, wxTreeEvent
)
593 wxPROPERTY_FLAGS( WindowStyle
, wxTreeCtrlStyle
, long , SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
594 wxEND_PROPERTIES_TABLE()
596 wxBEGIN_HANDLERS_TABLE(wxTreeCtrl
)
597 wxEND_HANDLERS_TABLE()
599 wxCONSTRUCTOR_5( wxTreeCtrl
, wxWindow
* , Parent
, wxWindowID
, Id
, wxPoint
, Position
, wxSize
, Size
, long , WindowStyle
)
601 IMPLEMENT_DYNAMIC_CLASS(wxTreeCtrl
, wxControl
)
604 // ----------------------------------------------------------------------------
606 // ----------------------------------------------------------------------------
608 // indices in gs_expandEvents table below
623 // handy table for sending events - it has to be initialized during run-time
624 // now so can't be const any more
625 static /* const */ wxEventType gs_expandEvents
[IDX_WHAT_MAX
][IDX_HOW_MAX
];
628 but logically it's a const table with the following entries:
631 { wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxEVT_COMMAND_TREE_ITEM_COLLAPSING },
632 { wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxEVT_COMMAND_TREE_ITEM_EXPANDING }
636 // ============================================================================
638 // ============================================================================
640 // ----------------------------------------------------------------------------
642 // ----------------------------------------------------------------------------
644 bool wxTreeTraversal::DoTraverse(const wxTreeItemId
& root
, bool recursively
)
646 if ( !OnVisit(root
) )
649 return Traverse(root
, recursively
);
652 bool wxTreeTraversal::Traverse(const wxTreeItemId
& root
, bool recursively
)
654 wxTreeItemIdValue cookie
;
655 wxTreeItemId child
= m_tree
->GetFirstChild(root
, cookie
);
656 while ( child
.IsOk() )
658 // depth first traversal
659 if ( recursively
&& !Traverse(child
, true) )
662 if ( !OnVisit(child
) )
665 child
= m_tree
->GetNextChild(root
, cookie
);
671 // ----------------------------------------------------------------------------
672 // construction and destruction
673 // ----------------------------------------------------------------------------
675 void wxTreeCtrl::Init()
678 m_hasAnyAttr
= false;
682 m_pVirtualRoot
= NULL
;
684 // initialize the global array of events now as it can't be done statically
685 // with the wxEVT_XXX values being allocated during run-time only
686 gs_expandEvents
[IDX_COLLAPSE
][IDX_DONE
] = wxEVT_COMMAND_TREE_ITEM_COLLAPSED
;
687 gs_expandEvents
[IDX_COLLAPSE
][IDX_DOING
] = wxEVT_COMMAND_TREE_ITEM_COLLAPSING
;
688 gs_expandEvents
[IDX_EXPAND
][IDX_DONE
] = wxEVT_COMMAND_TREE_ITEM_EXPANDED
;
689 gs_expandEvents
[IDX_EXPAND
][IDX_DOING
] = wxEVT_COMMAND_TREE_ITEM_EXPANDING
;
692 bool wxTreeCtrl::Create(wxWindow
*parent
,
697 const wxValidator
& validator
,
698 const wxString
& name
)
702 if ( (style
& wxBORDER_MASK
) == wxBORDER_DEFAULT
)
703 style
|= wxBORDER_SUNKEN
;
705 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
709 DWORD wstyle
= MSWGetStyle(m_windowStyle
, & exStyle
);
710 wstyle
|= WS_TABSTOP
| TVS_SHOWSELALWAYS
;
712 if ((m_windowStyle
& wxTR_NO_LINES
) == 0)
713 wstyle
|= TVS_HASLINES
;
714 if ( m_windowStyle
& wxTR_HAS_BUTTONS
)
715 wstyle
|= TVS_HASBUTTONS
;
717 if ( m_windowStyle
& wxTR_EDIT_LABELS
)
718 wstyle
|= TVS_EDITLABELS
;
720 if ( m_windowStyle
& wxTR_LINES_AT_ROOT
)
721 wstyle
|= TVS_LINESATROOT
;
723 if ( m_windowStyle
& wxTR_FULL_ROW_HIGHLIGHT
)
725 if ( wxApp::GetComCtl32Version() >= 471 )
726 wstyle
|= TVS_FULLROWSELECT
;
729 #if !defined(__WXWINCE__) && defined(TVS_INFOTIP)
730 // Need so that TVN_GETINFOTIP messages will be sent
731 wstyle
|= TVS_INFOTIP
;
734 // Create the tree control.
735 if ( !MSWCreateControl(WC_TREEVIEW
, wstyle
, pos
, size
) )
738 #if wxUSE_COMCTL32_SAFELY
739 wxWindow::SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
740 wxWindow::SetForegroundColour(wxWindow::GetParent()->GetForegroundColour());
742 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
743 SetForegroundColour(wxWindow::GetParent()->GetForegroundColour());
745 // This works around a bug in the Windows tree control whereby for some versions
746 // of comctrl32, setting any colour actually draws the background in black.
747 // This will initialise the background to the system colour.
748 // THIS FIX NOW REVERTED since it caused problems on _other_ systems.
749 // Assume the user has an updated comctl32.dll.
750 ::SendMessage(GetHwnd(), TVM_SETBKCOLOR
, 0,-1);
751 wxWindow::SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
752 SetForegroundColour(wxWindow::GetParent()->GetForegroundColour());
755 wxSetCCUnicodeFormat(GetHwnd());
760 wxTreeCtrl::~wxTreeCtrl()
762 // delete any attributes
765 WX_CLEAR_HASH_MAP(wxMapTreeAttr
, m_attrs
);
767 // prevent TVN_DELETEITEM handler from deleting the attributes again!
768 m_hasAnyAttr
= false;
773 // delete user data to prevent memory leaks
774 // also deletes hidden root node storage.
778 // ----------------------------------------------------------------------------
780 // ----------------------------------------------------------------------------
782 /* static */ wxVisualAttributes
783 wxTreeCtrl::GetClassDefaultAttributes(wxWindowVariant variant
)
785 wxVisualAttributes attrs
= GetCompositeControlsDefaultAttributes(variant
);
787 // common controls have their own default font
788 attrs
.font
= wxGetCCDefaultFont();
794 // simple wrappers which add error checking in debug mode
796 bool wxTreeCtrl::DoGetItem(wxTreeViewItem
*tvItem
) const
798 wxCHECK_MSG( tvItem
->hItem
!= TVI_ROOT
, false,
799 _T("can't retrieve virtual root item") );
801 if ( !TreeView_GetItem(GetHwnd(), tvItem
) )
803 wxLogLastError(wxT("TreeView_GetItem"));
811 void wxTreeCtrl::DoSetItem(wxTreeViewItem
*tvItem
)
813 TreeItemUnlocker
unlocker(tvItem
->hItem
);
815 if ( TreeView_SetItem(GetHwnd(), tvItem
) == -1 )
817 wxLogLastError(wxT("TreeView_SetItem"));
821 unsigned int wxTreeCtrl::GetCount() const
823 return (unsigned int)TreeView_GetCount(GetHwnd());
826 unsigned int wxTreeCtrl::GetIndent() const
828 return TreeView_GetIndent(GetHwnd());
831 void wxTreeCtrl::SetIndent(unsigned int indent
)
833 TreeView_SetIndent(GetHwnd(), indent
);
836 void wxTreeCtrl::SetAnyImageList(wxImageList
*imageList
, int which
)
839 (void) TreeView_SetImageList(GetHwnd(),
840 imageList
? imageList
->GetHIMAGELIST() : 0,
844 void wxTreeCtrl::SetImageList(wxImageList
*imageList
)
846 if (m_ownsImageListNormal
)
847 delete m_imageListNormal
;
849 SetAnyImageList(m_imageListNormal
= imageList
, TVSIL_NORMAL
);
850 m_ownsImageListNormal
= false;
853 void wxTreeCtrl::SetStateImageList(wxImageList
*imageList
)
855 if (m_ownsImageListState
) delete m_imageListState
;
856 SetAnyImageList(m_imageListState
= imageList
, TVSIL_STATE
);
857 m_ownsImageListState
= false;
860 size_t wxTreeCtrl::GetChildrenCount(const wxTreeItemId
& item
,
861 bool recursively
) const
863 wxCHECK_MSG( item
.IsOk(), 0u, wxT("invalid tree item") );
865 TraverseCounter
counter(this, item
, recursively
);
866 return counter
.GetCount() - 1;
869 // ----------------------------------------------------------------------------
871 // ----------------------------------------------------------------------------
873 bool wxTreeCtrl::SetBackgroundColour(const wxColour
&colour
)
875 #if !wxUSE_COMCTL32_SAFELY
876 if ( !wxWindowBase::SetBackgroundColour(colour
) )
879 ::SendMessage(GetHwnd(), TVM_SETBKCOLOR
, 0, colour
.GetPixel());
885 bool wxTreeCtrl::SetForegroundColour(const wxColour
&colour
)
887 #if !wxUSE_COMCTL32_SAFELY
888 if ( !wxWindowBase::SetForegroundColour(colour
) )
891 ::SendMessage(GetHwnd(), TVM_SETTEXTCOLOR
, 0, colour
.GetPixel());
897 // ----------------------------------------------------------------------------
899 // ----------------------------------------------------------------------------
901 bool wxTreeCtrl::IsHiddenRoot(const wxTreeItemId
& item
) const
903 return HITEM(item
) == TVI_ROOT
&& HasFlag(wxTR_HIDE_ROOT
);
906 wxString
wxTreeCtrl::GetItemText(const wxTreeItemId
& item
) const
908 wxCHECK_MSG( item
.IsOk(), wxEmptyString
, wxT("invalid tree item") );
910 wxChar buf
[512]; // the size is arbitrary...
912 wxTreeViewItem
tvItem(item
, TVIF_TEXT
);
913 tvItem
.pszText
= buf
;
914 tvItem
.cchTextMax
= WXSIZEOF(buf
);
915 if ( !DoGetItem(&tvItem
) )
917 // don't return some garbage which was on stack, but an empty string
921 return wxString(buf
);
924 void wxTreeCtrl::SetItemText(const wxTreeItemId
& item
, const wxString
& text
)
926 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
928 if ( IS_VIRTUAL_ROOT(item
) )
931 wxTreeViewItem
tvItem(item
, TVIF_TEXT
);
932 tvItem
.pszText
= (wxChar
*)text
.wx_str(); // conversion is ok
935 // when setting the text of the item being edited, the text control should
936 // be updated to reflect the new text as well, otherwise calling
937 // SetItemText() in the OnBeginLabelEdit() handler doesn't have any effect
939 // don't use GetEditControl() here because m_textCtrl is not set yet
940 HWND hwndEdit
= TreeView_GetEditControl(GetHwnd());
943 if ( item
== m_idEdited
)
945 ::SetWindowText(hwndEdit
, text
.wx_str());
950 int wxTreeCtrl::GetItemImage(const wxTreeItemId
& item
,
951 wxTreeItemIcon which
) const
953 wxCHECK_MSG( item
.IsOk(), -1, wxT("invalid tree item") );
955 if ( IsHiddenRoot(item
) )
957 // no images for hidden root item
961 wxTreeItemParam
*param
= GetItemParam(item
);
963 return param
&& param
->HasImage(which
) ? param
->GetImage(which
) : -1;
966 void wxTreeCtrl::SetItemImage(const wxTreeItemId
& item
, int image
,
967 wxTreeItemIcon which
)
969 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
970 wxCHECK_RET( which
>= 0 &&
971 which
< wxTreeItemIcon_Max
,
972 wxT("invalid image index"));
975 if ( IsHiddenRoot(item
) )
977 // no images for hidden root item
981 wxTreeItemParam
*data
= GetItemParam(item
);
985 data
->SetImage(image
, which
);
990 wxTreeItemParam
*wxTreeCtrl::GetItemParam(const wxTreeItemId
& item
) const
992 wxCHECK_MSG( item
.IsOk(), NULL
, wxT("invalid tree item") );
994 wxTreeViewItem
tvItem(item
, TVIF_PARAM
);
996 // hidden root may still have data.
997 if ( IS_VIRTUAL_ROOT(item
) )
999 return GET_VIRTUAL_ROOT()->GetParam();
1003 if ( !DoGetItem(&tvItem
) )
1008 return (wxTreeItemParam
*)tvItem
.lParam
;
1011 wxTreeItemData
*wxTreeCtrl::GetItemData(const wxTreeItemId
& item
) const
1013 wxTreeItemParam
*data
= GetItemParam(item
);
1015 return data
? data
->GetData() : NULL
;
1018 void wxTreeCtrl::SetItemData(const wxTreeItemId
& item
, wxTreeItemData
*data
)
1020 // first, associate this piece of data with this item
1026 wxTreeItemParam
*param
= GetItemParam(item
);
1028 wxCHECK_RET( param
, wxT("failed to change tree items data") );
1030 param
->SetData(data
);
1033 void wxTreeCtrl::SetItemHasChildren(const wxTreeItemId
& item
, bool has
)
1035 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1037 if ( IS_VIRTUAL_ROOT(item
) )
1040 wxTreeViewItem
tvItem(item
, TVIF_CHILDREN
);
1041 tvItem
.cChildren
= (int)has
;
1045 void wxTreeCtrl::SetItemBold(const wxTreeItemId
& item
, bool bold
)
1047 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1049 if ( IS_VIRTUAL_ROOT(item
) )
1052 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_BOLD
);
1053 tvItem
.state
= bold
? TVIS_BOLD
: 0;
1057 void wxTreeCtrl::SetItemDropHighlight(const wxTreeItemId
& item
, bool highlight
)
1059 if ( IS_VIRTUAL_ROOT(item
) )
1062 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_DROPHILITED
);
1063 tvItem
.state
= highlight
? TVIS_DROPHILITED
: 0;
1067 void wxTreeCtrl::RefreshItem(const wxTreeItemId
& item
)
1069 if ( IS_VIRTUAL_ROOT(item
) )
1073 if ( GetBoundingRect(item
, rect
) )
1079 wxColour
wxTreeCtrl::GetItemTextColour(const wxTreeItemId
& item
) const
1081 wxCHECK_MSG( item
.IsOk(), wxNullColour
, wxT("invalid tree item") );
1083 wxMapTreeAttr::const_iterator it
= m_attrs
.find(item
.m_pItem
);
1084 return it
== m_attrs
.end() ? wxNullColour
: it
->second
->GetTextColour();
1087 wxColour
wxTreeCtrl::GetItemBackgroundColour(const wxTreeItemId
& item
) const
1089 wxCHECK_MSG( item
.IsOk(), wxNullColour
, wxT("invalid tree item") );
1091 wxMapTreeAttr::const_iterator it
= m_attrs
.find(item
.m_pItem
);
1092 return it
== m_attrs
.end() ? wxNullColour
: it
->second
->GetBackgroundColour();
1095 wxFont
wxTreeCtrl::GetItemFont(const wxTreeItemId
& item
) const
1097 wxCHECK_MSG( item
.IsOk(), wxNullFont
, wxT("invalid tree item") );
1099 wxMapTreeAttr::const_iterator it
= m_attrs
.find(item
.m_pItem
);
1100 return it
== m_attrs
.end() ? wxNullFont
: it
->second
->GetFont();
1103 void wxTreeCtrl::SetItemTextColour(const wxTreeItemId
& item
,
1104 const wxColour
& col
)
1106 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1108 wxTreeItemAttr
*attr
;
1109 wxMapTreeAttr::iterator it
= m_attrs
.find(item
.m_pItem
);
1110 if ( it
== m_attrs
.end() )
1112 m_hasAnyAttr
= true;
1114 m_attrs
[item
.m_pItem
] =
1115 attr
= new wxTreeItemAttr
;
1122 attr
->SetTextColour(col
);
1127 void wxTreeCtrl::SetItemBackgroundColour(const wxTreeItemId
& item
,
1128 const wxColour
& col
)
1130 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1132 wxTreeItemAttr
*attr
;
1133 wxMapTreeAttr::iterator it
= m_attrs
.find(item
.m_pItem
);
1134 if ( it
== m_attrs
.end() )
1136 m_hasAnyAttr
= true;
1138 m_attrs
[item
.m_pItem
] =
1139 attr
= new wxTreeItemAttr
;
1141 else // already in the hash
1146 attr
->SetBackgroundColour(col
);
1151 void wxTreeCtrl::SetItemFont(const wxTreeItemId
& item
, const wxFont
& font
)
1153 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1155 wxTreeItemAttr
*attr
;
1156 wxMapTreeAttr::iterator it
= m_attrs
.find(item
.m_pItem
);
1157 if ( it
== m_attrs
.end() )
1159 m_hasAnyAttr
= true;
1161 m_attrs
[item
.m_pItem
] =
1162 attr
= new wxTreeItemAttr
;
1164 else // already in the hash
1169 attr
->SetFont(font
);
1171 // Reset the item's text to ensure that the bounding rect will be adjusted
1172 // for the new font.
1173 SetItemText(item
, GetItemText(item
));
1178 // ----------------------------------------------------------------------------
1180 // ----------------------------------------------------------------------------
1182 bool wxTreeCtrl::IsVisible(const wxTreeItemId
& item
) const
1184 wxCHECK_MSG( item
.IsOk(), false, wxT("invalid tree item") );
1186 if ( item
== wxTreeItemId(TVI_ROOT
) )
1188 // virtual (hidden) root is never visible
1192 // Bug in Gnu-Win32 headers, so don't use the macro TreeView_GetItemRect
1195 // this ugliness comes directly from MSDN - it *is* the correct way to pass
1196 // the HTREEITEM with TVM_GETITEMRECT
1197 *(HTREEITEM
*)&rect
= HITEM(item
);
1199 // true means to get rect for just the text, not the whole line
1200 if ( !::SendMessage(GetHwnd(), TVM_GETITEMRECT
, true, (LPARAM
)&rect
) )
1202 // if TVM_GETITEMRECT returned false, then the item is definitely not
1203 // visible (because its parent is not expanded)
1207 // however if it returned true, the item might still be outside the
1208 // currently visible part of the tree, test for it (notice that partly
1209 // visible means visible here)
1210 return rect
.bottom
> 0 && rect
.top
< GetClientSize().y
;
1213 bool wxTreeCtrl::ItemHasChildren(const wxTreeItemId
& item
) const
1215 wxCHECK_MSG( item
.IsOk(), false, wxT("invalid tree item") );
1217 if ( IS_VIRTUAL_ROOT(item
) )
1219 wxTreeItemIdValue cookie
;
1220 return GetFirstChild(item
, cookie
).IsOk();
1223 wxTreeViewItem
tvItem(item
, TVIF_CHILDREN
);
1226 return tvItem
.cChildren
!= 0;
1229 bool wxTreeCtrl::IsExpanded(const wxTreeItemId
& item
) const
1231 wxCHECK_MSG( item
.IsOk(), false, wxT("invalid tree item") );
1233 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_EXPANDED
);
1236 return (tvItem
.state
& TVIS_EXPANDED
) != 0;
1239 bool wxTreeCtrl::IsSelected(const wxTreeItemId
& item
) const
1241 wxCHECK_MSG( item
.IsOk(), false, wxT("invalid tree item") );
1243 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_SELECTED
);
1246 return (tvItem
.state
& TVIS_SELECTED
) != 0;
1249 bool wxTreeCtrl::IsBold(const wxTreeItemId
& item
) const
1251 wxCHECK_MSG( item
.IsOk(), false, wxT("invalid tree item") );
1253 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_BOLD
);
1256 return (tvItem
.state
& TVIS_BOLD
) != 0;
1259 // ----------------------------------------------------------------------------
1261 // ----------------------------------------------------------------------------
1263 wxTreeItemId
wxTreeCtrl::GetRootItem() const
1265 // Root may be real (visible) or virtual (hidden).
1266 if ( GET_VIRTUAL_ROOT() )
1269 return wxTreeItemId(TreeView_GetRoot(GetHwnd()));
1272 wxTreeItemId
wxTreeCtrl::GetSelection() const
1274 wxCHECK_MSG( !(m_windowStyle
& wxTR_MULTIPLE
), wxTreeItemId(),
1275 wxT("this only works with single selection controls") );
1277 return wxTreeItemId(TreeView_GetSelection(GetHwnd()));
1280 wxTreeItemId
wxTreeCtrl::GetItemParent(const wxTreeItemId
& item
) const
1282 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1286 if ( IS_VIRTUAL_ROOT(item
) )
1288 // no parent for the virtual root
1293 hItem
= TreeView_GetParent(GetHwnd(), HITEM(item
));
1294 if ( !hItem
&& HasFlag(wxTR_HIDE_ROOT
) )
1296 // the top level items should have the virtual root as their parent
1301 return wxTreeItemId(hItem
);
1304 wxTreeItemId
wxTreeCtrl::GetFirstChild(const wxTreeItemId
& item
,
1305 wxTreeItemIdValue
& cookie
) const
1307 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1309 // remember the last child returned in 'cookie'
1310 cookie
= TreeView_GetChild(GetHwnd(), HITEM(item
));
1312 return wxTreeItemId(cookie
);
1315 wxTreeItemId
wxTreeCtrl::GetNextChild(const wxTreeItemId
& WXUNUSED(item
),
1316 wxTreeItemIdValue
& cookie
) const
1318 wxTreeItemId
fromCookie(cookie
);
1320 HTREEITEM hitem
= HITEM(fromCookie
);
1322 hitem
= TreeView_GetNextSibling(GetHwnd(), hitem
);
1324 wxTreeItemId
item(hitem
);
1326 cookie
= item
.m_pItem
;
1331 wxTreeItemId
wxTreeCtrl::GetLastChild(const wxTreeItemId
& item
) const
1333 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1335 // can this be done more efficiently?
1336 wxTreeItemIdValue cookie
;
1338 wxTreeItemId childLast
,
1339 child
= GetFirstChild(item
, cookie
);
1340 while ( child
.IsOk() )
1343 child
= GetNextChild(item
, cookie
);
1349 wxTreeItemId
wxTreeCtrl::GetNextSibling(const wxTreeItemId
& item
) const
1351 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1352 return wxTreeItemId(TreeView_GetNextSibling(GetHwnd(), HITEM(item
)));
1355 wxTreeItemId
wxTreeCtrl::GetPrevSibling(const wxTreeItemId
& item
) const
1357 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1358 return wxTreeItemId(TreeView_GetPrevSibling(GetHwnd(), HITEM(item
)));
1361 wxTreeItemId
wxTreeCtrl::GetFirstVisibleItem() const
1363 return wxTreeItemId(TreeView_GetFirstVisible(GetHwnd()));
1366 wxTreeItemId
wxTreeCtrl::GetNextVisible(const wxTreeItemId
& item
) const
1368 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1369 wxASSERT_MSG( IsVisible(item
), wxT("The item you call GetNextVisible() for must be visible itself!"));
1371 wxTreeItemId
next(TreeView_GetNextVisible(GetHwnd(), HITEM(item
)));
1372 if ( next
.IsOk() && !IsVisible(next
) )
1374 // Win32 considers that any non-collapsed item is visible while we want
1375 // to return only really visible items
1382 wxTreeItemId
wxTreeCtrl::GetPrevVisible(const wxTreeItemId
& item
) const
1384 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1385 wxASSERT_MSG( IsVisible(item
), wxT("The item you call GetPrevVisible() for must be visible itself!"));
1387 wxTreeItemId
prev(TreeView_GetPrevVisible(GetHwnd(), HITEM(item
)));
1388 if ( prev
.IsOk() && !IsVisible(prev
) )
1390 // just as above, Win32 function will happily return the previous item
1391 // in the tree for the first visible item too
1398 // ----------------------------------------------------------------------------
1399 // multiple selections emulation
1400 // ----------------------------------------------------------------------------
1402 size_t wxTreeCtrl::GetSelections(wxArrayTreeItemIds
& selections
) const
1404 TraverseSelections
selector(this, selections
);
1406 return selector
.GetCount();
1409 // ----------------------------------------------------------------------------
1411 // ----------------------------------------------------------------------------
1413 wxTreeItemId
wxTreeCtrl::DoInsertAfter(const wxTreeItemId
& parent
,
1414 const wxTreeItemId
& hInsertAfter
,
1415 const wxString
& text
,
1416 int image
, int selectedImage
,
1417 wxTreeItemData
*data
)
1419 wxCHECK_MSG( parent
.IsOk() || !TreeView_GetRoot(GetHwnd()),
1421 _T("can't have more than one root in the tree") );
1423 TV_INSERTSTRUCT tvIns
;
1424 tvIns
.hParent
= HITEM(parent
);
1425 tvIns
.hInsertAfter
= HITEM(hInsertAfter
);
1427 // this is how we insert the item as the first child: supply a NULL
1429 if ( !tvIns
.hInsertAfter
)
1431 tvIns
.hInsertAfter
= TVI_FIRST
;
1435 if ( !text
.empty() )
1438 tvIns
.item
.pszText
= (wxChar
*)text
.wx_str(); // cast is ok
1442 tvIns
.item
.pszText
= NULL
;
1443 tvIns
.item
.cchTextMax
= 0;
1446 // create the param which will store the other item parameters
1447 wxTreeItemParam
*param
= new wxTreeItemParam
;
1449 // we return the images on demand as they depend on whether the item is
1450 // expanded or collapsed too in our case
1451 mask
|= TVIF_IMAGE
| TVIF_SELECTEDIMAGE
;
1452 tvIns
.item
.iImage
= I_IMAGECALLBACK
;
1453 tvIns
.item
.iSelectedImage
= I_IMAGECALLBACK
;
1455 param
->SetImage(image
, wxTreeItemIcon_Normal
);
1456 param
->SetImage(selectedImage
, wxTreeItemIcon_Selected
);
1459 tvIns
.item
.lParam
= (LPARAM
)param
;
1460 tvIns
.item
.mask
= mask
;
1462 // don't use the hack below for the children of hidden root: this results
1463 // in a crash inside comctl32.dll when we call TreeView_GetItemRect()
1464 const bool firstChild
= !IsHiddenRoot(parent
) &&
1465 !TreeView_GetChild(GetHwnd(), HITEM(parent
));
1467 HTREEITEM id
= TreeView_InsertItem(GetHwnd(), &tvIns
);
1470 wxLogLastError(wxT("TreeView_InsertItem"));
1473 // apparently some Windows versions (2000 and XP are reported to do this)
1474 // sometimes don't refresh the tree after adding the first child and so we
1475 // need this to make the "[+]" appear
1479 TreeView_GetItemRect(GetHwnd(), HITEM(parent
), &rect
, FALSE
);
1480 ::InvalidateRect(GetHwnd(), &rect
, FALSE
);
1483 // associate the application tree item with Win32 tree item handle
1486 // setup wxTreeItemData
1489 param
->SetData(data
);
1493 return wxTreeItemId(id
);
1496 wxTreeItemId
wxTreeCtrl::AddRoot(const wxString
& text
,
1497 int image
, int selectedImage
,
1498 wxTreeItemData
*data
)
1500 if ( HasFlag(wxTR_HIDE_ROOT
) )
1502 wxASSERT_MSG( !m_pVirtualRoot
, _T("tree can have only a single root") );
1504 // create a virtual root item, the parent for all the others
1505 wxTreeItemParam
*param
= new wxTreeItemParam
;
1506 param
->SetData(data
);
1508 m_pVirtualRoot
= new wxVirtualNode(param
);
1513 return DoInsertAfter(wxTreeItemId(), wxTreeItemId(),
1514 text
, image
, selectedImage
, data
);
1517 wxTreeItemId
wxTreeCtrl::DoInsertItem(const wxTreeItemId
& parent
,
1519 const wxString
& text
,
1520 int image
, int selectedImage
,
1521 wxTreeItemData
*data
)
1523 wxTreeItemId idPrev
;
1524 if ( index
== (size_t)-1 )
1526 // special value: append to the end
1529 else // find the item from index
1531 wxTreeItemIdValue cookie
;
1532 wxTreeItemId idCur
= GetFirstChild(parent
, cookie
);
1533 while ( index
!= 0 && idCur
.IsOk() )
1538 idCur
= GetNextChild(parent
, cookie
);
1541 // assert, not check: if the index is invalid, we will append the item
1543 wxASSERT_MSG( index
== 0, _T("bad index in wxTreeCtrl::InsertItem") );
1546 return DoInsertAfter(parent
, idPrev
, text
, image
, selectedImage
, data
);
1549 void wxTreeCtrl::Delete(const wxTreeItemId
& item
)
1551 // unlock tree selections on vista, without this the
1552 // tree ctrl will eventually crash after item deletion
1553 TreeItemUnlocker unlock_all
;
1555 if ( !TreeView_DeleteItem(GetHwnd(), HITEM(item
)) )
1557 wxLogLastError(wxT("TreeView_DeleteItem"));
1561 // delete all children (but don't delete the item itself)
1562 void wxTreeCtrl::DeleteChildren(const wxTreeItemId
& item
)
1564 // unlock tree selections on vista for the duration of this call
1565 TreeItemUnlocker unlock_all
;
1567 wxTreeItemIdValue cookie
;
1569 wxArrayTreeItemIds children
;
1570 wxTreeItemId child
= GetFirstChild(item
, cookie
);
1571 while ( child
.IsOk() )
1573 children
.Add(child
);
1575 child
= GetNextChild(item
, cookie
);
1578 size_t nCount
= children
.Count();
1579 for ( size_t n
= 0; n
< nCount
; n
++ )
1581 if ( !TreeView_DeleteItem(GetHwnd(), HITEM(children
[n
])) )
1583 wxLogLastError(wxT("TreeView_DeleteItem"));
1588 void wxTreeCtrl::DeleteAllItems()
1590 // unlock tree selections on vista for the duration of this call
1591 TreeItemUnlocker unlock_all
;
1593 // delete the "virtual" root item.
1594 if ( GET_VIRTUAL_ROOT() )
1596 delete GET_VIRTUAL_ROOT();
1597 m_pVirtualRoot
= NULL
;
1600 // and all the real items
1602 if ( !TreeView_DeleteAllItems(GetHwnd()) )
1604 wxLogLastError(wxT("TreeView_DeleteAllItems"));
1608 void wxTreeCtrl::DoExpand(const wxTreeItemId
& item
, int flag
)
1610 wxASSERT_MSG( flag
== TVE_COLLAPSE
||
1611 flag
== (TVE_COLLAPSE
| TVE_COLLAPSERESET
) ||
1612 flag
== TVE_EXPAND
||
1614 wxT("Unknown flag in wxTreeCtrl::DoExpand") );
1616 // A hidden root can be neither expanded nor collapsed.
1617 wxCHECK_RET( !IsHiddenRoot(item
),
1618 wxT("Can't expand/collapse hidden root node!") );
1620 // TreeView_Expand doesn't send TVN_ITEMEXPAND(ING) messages, so we must
1621 // emulate them. This behaviour has changed slightly with comctl32.dll
1622 // v 4.70 - now it does send them but only the first time. To maintain
1623 // compatible behaviour and also in order to not have surprises with the
1624 // future versions, don't rely on this and still do everything ourselves.
1625 // To avoid that the messages be sent twice when the item is expanded for
1626 // the first time we must clear TVIS_EXPANDEDONCE style manually.
1628 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_EXPANDEDONCE
);
1632 if ( TreeView_Expand(GetHwnd(), HITEM(item
), flag
) != 0 )
1634 // note that the {EXPAND|COLLAPS}ING event is sent by TreeView_Expand()
1636 wxTreeEvent
event(gs_expandEvents
[IsExpanded(item
) ? IDX_EXPAND
1640 (void)HandleWindowEvent(event
);
1642 //else: change didn't took place, so do nothing at all
1645 void wxTreeCtrl::Expand(const wxTreeItemId
& item
)
1647 DoExpand(item
, TVE_EXPAND
);
1650 void wxTreeCtrl::Collapse(const wxTreeItemId
& item
)
1652 DoExpand(item
, TVE_COLLAPSE
);
1655 void wxTreeCtrl::CollapseAndReset(const wxTreeItemId
& item
)
1657 DoExpand(item
, TVE_COLLAPSE
| TVE_COLLAPSERESET
);
1660 void wxTreeCtrl::Toggle(const wxTreeItemId
& item
)
1662 DoExpand(item
, TVE_TOGGLE
);
1665 void wxTreeCtrl::Unselect()
1667 wxASSERT_MSG( !(m_windowStyle
& wxTR_MULTIPLE
),
1668 wxT("doesn't make sense, may be you want UnselectAll()?") );
1670 // just remove the selection
1671 SelectItem(wxTreeItemId());
1674 void wxTreeCtrl::UnselectAll()
1676 if ( m_windowStyle
& wxTR_MULTIPLE
)
1678 wxArrayTreeItemIds selections
;
1679 size_t count
= GetSelections(selections
);
1680 for ( size_t n
= 0; n
< count
; n
++ )
1682 ::UnselectItem(GetHwnd(), HITEM(selections
[n
]));
1685 m_htSelStart
.Unset();
1689 // just remove the selection
1694 void wxTreeCtrl::SelectItem(const wxTreeItemId
& item
, bool select
)
1696 wxCHECK_RET( !IsHiddenRoot(item
), _T("can't select hidden root item") );
1698 wxASSERT_MSG( select
|| HasFlag(wxTR_MULTIPLE
),
1699 _T("SelectItem(false) works only for multiselect") );
1701 wxTreeEvent
event(wxEVT_COMMAND_TREE_SEL_CHANGING
, this, item
);
1702 if ( !HandleWindowEvent(event
) || event
.IsAllowed() )
1704 if ( HasFlag(wxTR_MULTIPLE
) )
1706 if ( !::SelectItem(GetHwnd(), HITEM(item
), select
) )
1708 wxLogLastError(wxT("TreeView_SelectItem"));
1712 else // single selection
1714 // use TreeView_SelectItem() to deselect the previous selection
1715 if ( !TreeView_SelectItem(GetHwnd(), HITEM(item
)) )
1717 wxLogLastError(wxT("TreeView_SelectItem"));
1722 event
.SetEventType(wxEVT_COMMAND_TREE_SEL_CHANGED
);
1723 (void)HandleWindowEvent(event
);
1725 //else: program vetoed the change
1728 void wxTreeCtrl::EnsureVisible(const wxTreeItemId
& item
)
1730 wxCHECK_RET( !IsHiddenRoot(item
), _T("can't show hidden root item") );
1733 TreeView_EnsureVisible(GetHwnd(), HITEM(item
));
1736 void wxTreeCtrl::ScrollTo(const wxTreeItemId
& item
)
1738 if ( !TreeView_SelectSetFirstVisible(GetHwnd(), HITEM(item
)) )
1740 wxLogLastError(wxT("TreeView_SelectSetFirstVisible"));
1744 wxTextCtrl
*wxTreeCtrl::GetEditControl() const
1749 void wxTreeCtrl::DeleteTextCtrl()
1753 // the HWND corresponding to this control is deleted by the tree
1754 // control itself and we don't know when exactly this happens, so check
1755 // if the window still exists before calling UnsubclassWin()
1756 if ( !::IsWindow(GetHwndOf(m_textCtrl
)) )
1758 m_textCtrl
->SetHWND(0);
1761 m_textCtrl
->UnsubclassWin();
1762 m_textCtrl
->SetHWND(0);
1770 wxTextCtrl
*wxTreeCtrl::EditLabel(const wxTreeItemId
& item
,
1771 wxClassInfo
*textControlClass
)
1773 wxASSERT( textControlClass
->IsKindOf(CLASSINFO(wxTextCtrl
)) );
1778 m_textCtrl
= (wxTextCtrl
*)textControlClass
->CreateObject();
1779 HWND hWnd
= (HWND
) TreeView_EditLabel(GetHwnd(), HITEM(item
));
1781 // this is not an error - the TVN_BEGINLABELEDIT handler might have
1790 // textctrl is subclassed in MSWOnNotify
1794 // End label editing, optionally cancelling the edit
1795 void wxTreeCtrl::DoEndEditLabel(bool discardChanges
)
1797 TreeView_EndEditLabelNow(GetHwnd(), discardChanges
);
1802 wxTreeItemId
wxTreeCtrl::DoTreeHitTest(const wxPoint
& point
, int& flags
) const
1804 TV_HITTESTINFO hitTestInfo
;
1805 hitTestInfo
.pt
.x
= (int)point
.x
;
1806 hitTestInfo
.pt
.y
= (int)point
.y
;
1808 (void) TreeView_HitTest(GetHwnd(), &hitTestInfo
);
1813 #define TRANSLATE_FLAG(flag) if ( hitTestInfo.flags & TVHT_##flag ) \
1814 flags |= wxTREE_HITTEST_##flag
1816 TRANSLATE_FLAG(ABOVE
);
1817 TRANSLATE_FLAG(BELOW
);
1818 TRANSLATE_FLAG(NOWHERE
);
1819 TRANSLATE_FLAG(ONITEMBUTTON
);
1820 TRANSLATE_FLAG(ONITEMICON
);
1821 TRANSLATE_FLAG(ONITEMINDENT
);
1822 TRANSLATE_FLAG(ONITEMLABEL
);
1823 TRANSLATE_FLAG(ONITEMRIGHT
);
1824 TRANSLATE_FLAG(ONITEMSTATEICON
);
1825 TRANSLATE_FLAG(TOLEFT
);
1826 TRANSLATE_FLAG(TORIGHT
);
1828 #undef TRANSLATE_FLAG
1830 return wxTreeItemId(hitTestInfo
.hItem
);
1833 bool wxTreeCtrl::GetBoundingRect(const wxTreeItemId
& item
,
1835 bool textOnly
) const
1839 // Virtual root items have no bounding rectangle
1840 if ( IS_VIRTUAL_ROOT(item
) )
1845 if ( TreeView_GetItemRect(GetHwnd(), HITEM(item
),
1848 rect
= wxRect(wxPoint(rc
.left
, rc
.top
), wxPoint(rc
.right
, rc
.bottom
));
1854 // couldn't retrieve rect: for example, item isn't visible
1859 // ----------------------------------------------------------------------------
1861 // ----------------------------------------------------------------------------
1863 // this is just a tiny namespace which is friend to wxTreeCtrl and so can use
1864 // functions such as IsDataIndirect()
1865 class wxTreeSortHelper
1868 static int CALLBACK
Compare(LPARAM data1
, LPARAM data2
, LPARAM tree
);
1871 static wxTreeItemId
GetIdFromData(LPARAM lParam
)
1873 return ((wxTreeItemParam
*)lParam
)->GetItem();
1877 int CALLBACK
wxTreeSortHelper::Compare(LPARAM pItem1
,
1881 wxCHECK_MSG( pItem1
&& pItem2
, 0,
1882 wxT("sorting tree without data doesn't make sense") );
1884 wxTreeCtrl
*tree
= (wxTreeCtrl
*)htree
;
1886 return tree
->OnCompareItems(GetIdFromData(pItem1
),
1887 GetIdFromData(pItem2
));
1890 void wxTreeCtrl::SortChildren(const wxTreeItemId
& item
)
1892 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1894 // rely on the fact that TreeView_SortChildren does the same thing as our
1895 // default behaviour, i.e. sorts items alphabetically and so call it
1896 // directly if we're not in derived class (much more efficient!)
1897 // RN: Note that if you find you're code doesn't sort as expected this
1898 // may be why as if you don't use the DECLARE_CLASS/IMPLEMENT_CLASS
1899 // combo for your derived wxTreeCtrl if will sort without
1901 if ( GetClassInfo() == CLASSINFO(wxTreeCtrl
) )
1903 TreeView_SortChildren(GetHwnd(), HITEM(item
), 0);
1908 tvSort
.hParent
= HITEM(item
);
1909 tvSort
.lpfnCompare
= wxTreeSortHelper::Compare
;
1910 tvSort
.lParam
= (LPARAM
)this;
1911 TreeView_SortChildrenCB(GetHwnd(), &tvSort
, 0 /* reserved */);
1915 // ----------------------------------------------------------------------------
1917 // ----------------------------------------------------------------------------
1919 bool wxTreeCtrl::MSWShouldPreProcessMessage(WXMSG
* msg
)
1921 if ( msg
->message
== WM_KEYDOWN
)
1923 // Only eat VK_RETURN if not being used by the application in
1924 // conjunction with modifiers
1925 if ( (msg
->wParam
== VK_RETURN
) && !wxIsAnyModifierDown() )
1927 // we need VK_RETURN to generate wxEVT_COMMAND_TREE_ITEM_ACTIVATED
1932 return wxTreeCtrlBase::MSWShouldPreProcessMessage(msg
);
1935 bool wxTreeCtrl::MSWCommand(WXUINT cmd
, WXWORD id_
)
1937 const int id
= (signed short)id_
;
1939 if ( cmd
== EN_UPDATE
)
1941 wxCommandEvent
event(wxEVT_COMMAND_TEXT_UPDATED
, id
);
1942 event
.SetEventObject( this );
1943 ProcessCommand(event
);
1945 else if ( cmd
== EN_KILLFOCUS
)
1947 wxCommandEvent
event(wxEVT_KILL_FOCUS
, id
);
1948 event
.SetEventObject( this );
1949 ProcessCommand(event
);
1957 // command processed
1961 // we hook into WndProc to process WM_MOUSEMOVE/WM_BUTTONUP messages - as we
1962 // only do it during dragging, minimize wxWin overhead (this is important for
1963 // WM_MOUSEMOVE as they're a lot of them) by catching Windows messages directly
1964 // instead of passing by wxWin events
1965 WXLRESULT
wxTreeCtrl::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
1967 bool processed
= false;
1969 bool isMultiple
= HasFlag(wxTR_MULTIPLE
);
1971 // This message is sent after a right-click, or when the "menu" key is pressed
1972 if ( nMsg
== WM_CONTEXTMENU
)
1974 int x
= GET_X_LPARAM(lParam
),
1975 y
= GET_Y_LPARAM(lParam
);
1977 // the item for which the menu should be shown
1980 // the position where the menu should be shown in client coordinates
1981 // (so that it can be passed directly to PopupMenu())
1984 if ( x
== -1 || y
== -1 )
1986 // this means that the event was generated from keyboard (e.g. with
1987 // Shift-F10 or special Windows menu key)
1989 // use the Explorer standard of putting the menu at the left edge
1990 // of the text, in the vertical middle of the text
1991 item
= wxTreeItemId(TreeView_GetSelection(GetHwnd()));
1994 // Use the bounding rectangle of only the text part
1996 GetBoundingRect(item
, rect
, true);
1997 pt
= wxPoint(rect
.GetX(), rect
.GetY() + rect
.GetHeight() / 2);
2000 else // event from mouse, use mouse position
2002 pt
= ScreenToClient(wxPoint(x
, y
));
2004 TV_HITTESTINFO tvhti
;
2007 if ( TreeView_HitTest(GetHwnd(), &tvhti
) )
2008 item
= wxTreeItemId(tvhti
.hItem
);
2012 wxTreeEvent
event(wxEVT_COMMAND_TREE_ITEM_MENU
, this, item
);
2014 event
.m_pointDrag
= pt
;
2016 if ( HandleWindowEvent(event
) )
2018 //else: continue with generating wxEVT_CONTEXT_MENU in base class code
2020 else if ( (nMsg
>= WM_MOUSEFIRST
) && (nMsg
<= WM_MOUSELAST
) )
2022 // we only process mouse messages here and these parameters have the
2023 // same meaning for all of them
2024 int x
= GET_X_LPARAM(lParam
),
2025 y
= GET_Y_LPARAM(lParam
);
2027 TV_HITTESTINFO tvht
;
2031 HTREEITEM htItem
= TreeView_HitTest(GetHwnd(), &tvht
);
2035 case WM_LBUTTONDOWN
:
2036 if ( htItem
&& isMultiple
&& (tvht
.flags
& TVHT_ONITEM
) != 0 )
2038 m_htClickedItem
= (WXHTREEITEM
) htItem
;
2039 m_ptClick
= wxPoint(x
, y
);
2041 if ( wParam
& MK_CONTROL
)
2045 // toggle selected state
2046 ToggleItemSelection(htItem
);
2048 ::SetFocus(GetHwnd(), htItem
);
2050 // reset on any click without Shift
2051 m_htSelStart
.Unset();
2055 else if ( wParam
& MK_SHIFT
)
2057 // this selects all items between the starting one and
2060 if ( !m_htSelStart
)
2062 // take the focused item
2063 m_htSelStart
= TreeView_GetSelection(GetHwnd());
2067 SelectRange(GetHwnd(), HITEM(m_htSelStart
), htItem
,
2068 !(wParam
& MK_CONTROL
));
2070 ::SelectItem(GetHwnd(), htItem
);
2072 ::SetFocus(GetHwnd(), htItem
);
2076 else // normal click
2078 // avoid doing anything if we click on the only
2079 // currently selected item
2083 wxArrayTreeItemIds selections
;
2084 size_t count
= GetSelections(selections
);
2087 HITEM(selections
[0]) != htItem
)
2089 // clear the previously selected items, if the
2090 // user clicked outside of the present selection.
2091 // otherwise, perform the deselection on mouse-up.
2092 // this allows multiple drag and drop to work.
2094 if (!IsItemSelected(GetHwnd(), htItem
))
2098 // prevent the click from starting in-place editing
2099 // which should only happen if we click on the
2100 // already selected item (and nothing else is
2103 TreeView_SelectItem(GetHwnd(), 0);
2104 ::SelectItem(GetHwnd(), htItem
);
2106 ::SetFocus(GetHwnd(), htItem
);
2109 else // click on a single selected item
2111 // don't interfere with the default processing in
2112 // WM_MOUSEMOVE handler below as the default window
2113 // proc will start the drag itself if we let have
2115 m_htClickedItem
.Unset();
2118 // reset on any click without Shift
2119 m_htSelStart
.Unset();
2124 case WM_RBUTTONDOWN
:
2125 // default handler removes the highlight from the currently
2126 // focused item when right mouse button is pressed on another
2127 // one but keeps the remaining items highlighted, which is
2128 // confusing, so override this default behaviour for tree with
2129 // multiple selections
2132 if ( !IsItemSelected(GetHwnd(), htItem
) )
2136 ::SetFocus(GetHwnd(), htItem
);
2139 // fire EVT_RIGHT_DOWN
2140 HandleMouseEvent(nMsg
, x
, y
, wParam
);
2144 nmhdr
.hwndFrom
= GetHwnd();
2145 nmhdr
.idFrom
= ::GetWindowLong(GetHwnd(), GWL_ID
);
2146 nmhdr
.code
= NM_RCLICK
;
2147 ::SendMessage(::GetParent(GetHwnd()), WM_NOTIFY
,
2148 nmhdr
.idFrom
, (LPARAM
)&nmhdr
);
2150 // prevent tree control default processing, as we've
2151 // already done everything
2158 if ( m_htClickedItem
)
2160 int cx
= abs(m_ptClick
.x
- x
);
2161 int cy
= abs(m_ptClick
.y
- y
);
2163 if ( cx
> ::GetSystemMetrics(SM_CXDRAG
) ||
2164 cy
> ::GetSystemMetrics(SM_CYDRAG
) )
2169 tv
.hdr
.hwndFrom
= GetHwnd();
2170 tv
.hdr
.idFrom
= ::GetWindowLong(GetHwnd(), GWL_ID
);
2171 tv
.hdr
.code
= TVN_BEGINDRAG
;
2173 tv
.itemNew
.hItem
= HITEM(m_htClickedItem
);
2177 wxZeroMemory(tviAux
);
2179 tviAux
.hItem
= HITEM(m_htClickedItem
);
2180 tviAux
.mask
= TVIF_STATE
| TVIF_PARAM
;
2181 tviAux
.stateMask
= 0xffffffff;
2182 TreeView_GetItem(GetHwnd(), &tviAux
);
2184 tv
.itemNew
.state
= tviAux
.state
;
2185 tv
.itemNew
.lParam
= tviAux
.lParam
;
2190 // do it before SendMessage() call below to avoid
2191 // reentrancies here if there is another WM_MOUSEMOVE
2192 // in the queue already
2193 m_htClickedItem
.Unset();
2195 ::SendMessage(GetHwndOf(GetParent()), WM_NOTIFY
,
2196 tv
.hdr
.idFrom
, (LPARAM
)&tv
);
2198 // don't pass it to the default window proc, it would
2199 // start dragging again
2203 #endif // __WXWINCE__
2208 m_dragImage
->Move(wxPoint(x
, y
));
2211 // highlight the item as target (hiding drag image is
2212 // necessary - otherwise the display will be corrupted)
2213 m_dragImage
->Hide();
2214 TreeView_SelectDropTarget(GetHwnd(), htItem
);
2215 m_dragImage
->Show();
2218 #endif // wxUSE_DRAGIMAGE
2223 // facilitates multiple drag-and-drop
2224 if (htItem
&& isMultiple
)
2226 wxArrayTreeItemIds selections
;
2227 size_t count
= GetSelections(selections
);
2230 !(wParam
& MK_CONTROL
) &&
2231 !(wParam
& MK_SHIFT
))
2234 TreeView_SelectItem(GetHwnd(), htItem
);
2235 ::SelectItem(GetHwnd(), htItem
);
2236 ::SetFocus(GetHwnd(), htItem
);
2238 m_htClickedItem
.Unset();
2247 m_dragImage
->EndDrag();
2251 // generate the drag end event
2252 wxTreeEvent
event(wxEVT_COMMAND_TREE_END_DRAG
, this, htItem
);
2253 event
.m_pointDrag
= wxPoint(x
, y
);
2255 (void)HandleWindowEvent(event
);
2257 // if we don't do it, the tree seems to think that 2 items
2258 // are selected simultaneously which is quite weird
2259 TreeView_SelectDropTarget(GetHwnd(), 0);
2261 #endif // wxUSE_DRAGIMAGE
2265 else if ( (nMsg
== WM_SETFOCUS
|| nMsg
== WM_KILLFOCUS
) && isMultiple
)
2267 // the tree control greys out the selected item when it loses focus and
2268 // paints it as selected again when it regains it, but it won't do it
2269 // for the other items itself - help it
2270 wxArrayTreeItemIds selections
;
2271 size_t count
= GetSelections(selections
);
2273 for ( size_t n
= 0; n
< count
; n
++ )
2275 // TreeView_GetItemRect() will return false if item is not visible,
2276 // which may happen perfectly well
2277 if ( TreeView_GetItemRect(GetHwnd(), HITEM(selections
[n
]),
2280 ::InvalidateRect(GetHwnd(), &rect
, FALSE
);
2284 else if ( nMsg
== WM_KEYDOWN
&& isMultiple
)
2286 bool bCtrl
= wxIsCtrlDown(),
2287 bShift
= wxIsShiftDown();
2289 HTREEITEM htSel
= (HTREEITEM
)TreeView_GetSelection(GetHwnd());
2295 ToggleItemSelection(htSel
);
2301 ::SelectItem(GetHwnd(), htSel
);
2309 if ( !bCtrl
&& !bShift
)
2311 // no modifiers, just clear selection and then let the default
2312 // processing to take place
2317 (void)wxControl::MSWWindowProc(nMsg
, wParam
, lParam
);
2319 HTREEITEM htNext
= (HTREEITEM
)
2320 TreeView_GetNextItem
2324 wParam
== VK_UP
? TVGN_PREVIOUSVISIBLE
2330 // at the top/bottom
2336 if ( !m_htSelStart
)
2337 m_htSelStart
= htSel
;
2339 SelectRange(GetHwnd(), HITEM(m_htSelStart
), htNext
);
2343 // without changing selection
2344 ::SetFocus(GetHwnd(), htNext
);
2355 // TODO: handle Shift/Ctrl with these keys
2356 if ( !bCtrl
&& !bShift
)
2360 m_htSelStart
.Unset();
2364 else if ( nMsg
== WM_COMMAND
)
2366 // if we receive a EN_KILLFOCUS command from the in-place edit control
2367 // used for label editing, make sure to end editing
2370 UnpackCommand(wParam
, lParam
, &id
, &hwnd
, &cmd
);
2372 if ( cmd
== EN_KILLFOCUS
)
2374 if ( m_textCtrl
&& m_textCtrl
->GetHandle() == hwnd
)
2384 rc
= wxControl::MSWWindowProc(nMsg
, wParam
, lParam
);
2390 wxTreeCtrl::MSWDefWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
2392 if ( nMsg
== WM_CHAR
)
2394 // don't let the control process Space and Return keys because it
2395 // doesn't do anything useful with them anyhow but always beeps
2396 // annoyingly when it receives them and there is no way to turn it off
2397 // simply if you just process TREEITEM_ACTIVATED event to which Space
2398 // and Enter presses are mapped in your code
2399 if ( wParam
== VK_SPACE
|| wParam
== VK_RETURN
)
2403 else if ( nMsg
== WM_KEYDOWN
)
2405 if ( wParam
== VK_ESCAPE
)
2409 m_dragImage
->EndDrag();
2413 // if we don't do it, the tree seems to think that 2 items
2414 // are selected simultaneously which is quite weird
2415 TreeView_SelectDropTarget(GetHwnd(), 0);
2419 #endif // wxUSE_DRAGIMAGE
2421 return wxControl::MSWDefWindowProc(nMsg
, wParam
, lParam
);
2424 // process WM_NOTIFY Windows message
2425 bool wxTreeCtrl::MSWOnNotify(int idCtrl
, WXLPARAM lParam
, WXLPARAM
*result
)
2427 wxTreeEvent
event(wxEVT_NULL
, this);
2428 wxEventType eventType
= wxEVT_NULL
;
2429 NMHDR
*hdr
= (NMHDR
*)lParam
;
2431 switch ( hdr
->code
)
2434 eventType
= wxEVT_COMMAND_TREE_BEGIN_DRAG
;
2437 case TVN_BEGINRDRAG
:
2439 if ( eventType
== wxEVT_NULL
)
2440 eventType
= wxEVT_COMMAND_TREE_BEGIN_RDRAG
;
2441 //else: left drag, already set above
2443 NM_TREEVIEW
*tv
= (NM_TREEVIEW
*)lParam
;
2445 event
.m_item
= tv
->itemNew
.hItem
;
2446 event
.m_pointDrag
= wxPoint(tv
->ptDrag
.x
, tv
->ptDrag
.y
);
2448 // don't allow dragging by default: the user code must
2449 // explicitly say that it wants to allow it to avoid breaking
2455 case TVN_BEGINLABELEDIT
:
2457 eventType
= wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT
;
2458 TV_DISPINFO
*info
= (TV_DISPINFO
*)lParam
;
2460 // although the user event handler may still veto it, it is
2461 // important to set it now so that calls to SetItemText() from
2462 // the event handler would change the text controls contents
2464 event
.m_item
= info
->item
.hItem
;
2465 event
.m_label
= info
->item
.pszText
;
2466 event
.m_editCancelled
= false;
2470 case TVN_DELETEITEM
:
2472 eventType
= wxEVT_COMMAND_TREE_DELETE_ITEM
;
2473 NM_TREEVIEW
*tv
= (NM_TREEVIEW
*)lParam
;
2475 event
.m_item
= tv
->itemOld
.hItem
;
2479 wxMapTreeAttr::iterator it
= m_attrs
.find(tv
->itemOld
.hItem
);
2480 if ( it
!= m_attrs
.end() )
2489 case TVN_ENDLABELEDIT
:
2491 eventType
= wxEVT_COMMAND_TREE_END_LABEL_EDIT
;
2492 TV_DISPINFO
*info
= (TV_DISPINFO
*)lParam
;
2494 event
.m_item
= info
->item
.hItem
;
2495 event
.m_label
= info
->item
.pszText
;
2496 event
.m_editCancelled
= info
->item
.pszText
== NULL
;
2501 // These *must* not be removed or TVN_GETINFOTIP will
2502 // not be processed each time the mouse is moved
2503 // and the tooltip will only ever update once.
2512 #ifdef TVN_GETINFOTIP
2513 case TVN_GETINFOTIP
:
2515 eventType
= wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP
;
2516 NMTVGETINFOTIP
*info
= (NMTVGETINFOTIP
*)lParam
;
2518 // Which item are we trying to get a tooltip for?
2519 event
.m_item
= info
->hItem
;
2523 #endif // TVN_GETINFOTIP
2524 #endif // !__WXWINCE__
2526 case TVN_GETDISPINFO
:
2527 eventType
= wxEVT_COMMAND_TREE_GET_INFO
;
2530 case TVN_SETDISPINFO
:
2532 if ( eventType
== wxEVT_NULL
)
2533 eventType
= wxEVT_COMMAND_TREE_SET_INFO
;
2534 //else: get, already set above
2536 TV_DISPINFO
*info
= (TV_DISPINFO
*)lParam
;
2538 event
.m_item
= info
->item
.hItem
;
2542 case TVN_ITEMEXPANDING
:
2543 case TVN_ITEMEXPANDED
:
2545 NM_TREEVIEW
*tv
= (NM_TREEVIEW
*)lParam
;
2548 switch ( tv
->action
)
2551 wxLogDebug(wxT("unexpected code %d in TVN_ITEMEXPAND message"), tv
->action
);
2559 what
= IDX_COLLAPSE
;
2563 int how
= hdr
->code
== TVN_ITEMEXPANDING
? IDX_DOING
2566 eventType
= gs_expandEvents
[what
][how
];
2568 event
.m_item
= tv
->itemNew
.hItem
;
2574 eventType
= wxEVT_COMMAND_TREE_KEY_DOWN
;
2575 TV_KEYDOWN
*info
= (TV_KEYDOWN
*)lParam
;
2577 // fabricate the lParam and wParam parameters sufficiently
2578 // similar to the ones from a "real" WM_KEYDOWN so that
2579 // CreateKeyEvent() works correctly
2580 WXLPARAM lParam
= (wxIsAltDown() ? KF_ALTDOWN
: 0) << 16;
2582 WXWPARAM wParam
= info
->wVKey
;
2584 int keyCode
= wxCharCodeMSWToWX(wParam
);
2587 // wxCharCodeMSWToWX() returns 0 to indicate that this is a
2592 event
.m_evtKey
= CreateKeyEvent(wxEVT_KEY_DOWN
,
2597 // a separate event for Space/Return
2598 if ( !wxIsAnyModifierDown() &&
2599 ((info
->wVKey
== VK_SPACE
) || (info
->wVKey
== VK_RETURN
)) )
2602 if ( !HasFlag(wxTR_MULTIPLE
) )
2603 item
= GetSelection();
2605 wxTreeEvent
event2(wxEVT_COMMAND_TREE_ITEM_ACTIVATED
,
2607 (void)HandleWindowEvent(event2
);
2613 // Vista's tree control has introduced some problems with our
2614 // multi-selection tree. When TreeView_SelectItem() is called,
2615 // the wrong items are deselected.
2617 // Fortunately, Vista provides a new notification, TVN_ITEMCHANGING
2618 // that can be used to regulate this incorrect behavior. The
2619 // following messages will allow only the unlocked item's selection
2622 case TVN_ITEMCHANGINGA
:
2623 case TVN_ITEMCHANGINGW
:
2625 // we only need to handles these in multi-select trees
2626 if ( HasFlag(wxTR_MULTIPLE
) )
2628 // get info about the item about to be changed
2629 NMTVITEMCHANGE
* info
= (NMTVITEMCHANGE
*)lParam
;
2630 if (TreeItemUnlocker::IsLocked(info
->hItem
))
2632 // item's state is locked, don't allow the change
2633 // returning 1 will disallow the change
2639 // allow the state change
2643 // NB: MSLU is broken and sends TVN_SELCHANGEDA instead of
2644 // TVN_SELCHANGEDW in Unicode mode under Win98. Therefore
2645 // we have to handle both messages:
2646 case TVN_SELCHANGEDA
:
2647 case TVN_SELCHANGEDW
:
2648 eventType
= wxEVT_COMMAND_TREE_SEL_CHANGED
;
2651 case TVN_SELCHANGINGA
:
2652 case TVN_SELCHANGINGW
:
2654 if ( eventType
== wxEVT_NULL
)
2655 eventType
= wxEVT_COMMAND_TREE_SEL_CHANGING
;
2656 //else: already set above
2658 if (hdr
->code
== TVN_SELCHANGINGW
||
2659 hdr
->code
== TVN_SELCHANGEDW
)
2661 NM_TREEVIEWW
*tv
= (NM_TREEVIEWW
*)lParam
;
2662 event
.m_item
= tv
->itemNew
.hItem
;
2663 event
.m_itemOld
= tv
->itemOld
.hItem
;
2667 NM_TREEVIEWA
*tv
= (NM_TREEVIEWA
*)lParam
;
2668 event
.m_item
= tv
->itemNew
.hItem
;
2669 event
.m_itemOld
= tv
->itemOld
.hItem
;
2673 // we receive this message from WM_LBUTTONDOWN handler inside
2674 // comctl32.dll and so before the click is passed to
2675 // DefWindowProc() which sets the focus to the window which was
2676 // clicked and this can lead to unexpected event sequences: for
2677 // example, we may get a "selection change" event from the tree
2678 // before getting a "kill focus" event for the text control which
2679 // had the focus previously, thus breaking user code doing input
2682 // to avoid such surprises, we force the generation of focus events
2683 // now, before we generate the selection change ones
2687 // instead of explicitly checking for _WIN32_IE, check if the
2688 // required symbols are available in the headers
2689 #if defined(CDDS_PREPAINT) && !wxUSE_COMCTL32_SAFELY
2692 LPNMTVCUSTOMDRAW lptvcd
= (LPNMTVCUSTOMDRAW
)lParam
;
2693 NMCUSTOMDRAW
& nmcd
= lptvcd
->nmcd
;
2694 switch ( nmcd
.dwDrawStage
)
2697 // if we've got any items with non standard attributes,
2698 // notify us before painting each item
2699 *result
= m_hasAnyAttr
? CDRF_NOTIFYITEMDRAW
2702 // windows in TreeCtrl use one-based index for item state images,
2703 // 0 indexed image is not being used, we're using zero-based index,
2704 // so we have to add temp image (of zero index) to state image list
2705 // before we draw any item, then after items are drawn we have to
2706 // delete it (in POSTPAINT notify)
2707 if (m_imageListState
&& m_imageListState
->GetImageCount() > 0)
2709 typedef BOOL (*ImageList_Copy_t
)
2710 (HIMAGELIST
, int, HIMAGELIST
, int, UINT
);
2711 static ImageList_Copy_t s_pfnImageList_Copy
= NULL
;
2712 static bool loaded
= false;
2716 wxLoadedDLL
dllComCtl32(_T("comctl32.dll"));
2717 if ( dllComCtl32
.IsLoaded() )
2718 wxDL_INIT_FUNC(s_pfn
, ImageList_Copy
, dllComCtl32
);
2721 if ( !s_pfnImageList_Copy
)
2723 // this code is broken with ImageList_Copy()
2724 // but I don't care enough about Win95 support
2725 // to write it now -- if anybody does, please
2727 wxFAIL_MSG("TODO: implement this for Win95");
2732 hImageList
= GetHimagelistOf(m_imageListState
);
2734 // add temporary image
2736 m_imageListState
->GetSize(0, width
, height
);
2738 HBITMAP hbmpTemp
= ::CreateBitmap(width
, height
, 1, 1, NULL
);
2739 int index
= ::ImageList_Add(hImageList
, hbmpTemp
, hbmpTemp
);
2740 ::DeleteObject(hbmpTemp
);
2744 // move images to right
2745 for ( int i
= index
; i
> 0; i
-- )
2747 (*s_pfnImageList_Copy
)(hImageList
, i
,
2752 // we must remove the image in POSTPAINT notify
2753 *result
|= CDRF_NOTIFYPOSTPAINT
;
2758 case CDDS_POSTPAINT
:
2759 // we are deleting temp image of 0 index, which was
2760 // added before items were drawn (in PREPAINT notify)
2761 if (m_imageListState
&& m_imageListState
->GetImageCount() > 0)
2762 m_imageListState
->Remove(0);
2765 case CDDS_ITEMPREPAINT
:
2767 wxMapTreeAttr::iterator
2768 it
= m_attrs
.find((void *)nmcd
.dwItemSpec
);
2770 if ( it
== m_attrs
.end() )
2772 // nothing to do for this item
2773 *result
= CDRF_DODEFAULT
;
2777 wxTreeItemAttr
* const attr
= it
->second
;
2779 wxTreeViewItem
tvItem((void *)nmcd
.dwItemSpec
,
2780 TVIF_STATE
, TVIS_DROPHILITED
);
2782 const UINT tvItemState
= tvItem
.state
;
2784 // selection colours should override ours,
2785 // otherwise it is too confusing to the user
2786 if ( !(nmcd
.uItemState
& CDIS_SELECTED
) &&
2787 !(tvItemState
& TVIS_DROPHILITED
) )
2790 if ( attr
->HasBackgroundColour() )
2792 colBack
= attr
->GetBackgroundColour();
2793 lptvcd
->clrTextBk
= wxColourToRGB(colBack
);
2797 // but we still want to keep the special foreground
2798 // colour when we don't have focus (we can't keep
2799 // it when we do, it would usually be unreadable on
2800 // the almost inverted bg colour...)
2801 if ( ( !(nmcd
.uItemState
& CDIS_SELECTED
) ||
2802 FindFocus() != this ) &&
2803 !(tvItemState
& TVIS_DROPHILITED
) )
2806 if ( attr
->HasTextColour() )
2808 colText
= attr
->GetTextColour();
2809 lptvcd
->clrText
= wxColourToRGB(colText
);
2813 if ( attr
->HasFont() )
2815 HFONT hFont
= GetHfontOf(attr
->GetFont());
2817 ::SelectObject(nmcd
.hdc
, hFont
);
2819 *result
= CDRF_NEWFONT
;
2821 else // no specific font
2823 *result
= CDRF_DODEFAULT
;
2829 *result
= CDRF_DODEFAULT
;
2833 // we always process it
2835 #endif // have owner drawn support in headers
2839 DWORD pos
= GetMessagePos();
2841 point
.x
= LOWORD(pos
);
2842 point
.y
= HIWORD(pos
);
2843 ::MapWindowPoints(HWND_DESKTOP
, GetHwnd(), &point
, 1);
2845 wxTreeItemId item
= HitTest(wxPoint(point
.x
, point
.y
), flags
);
2846 if (flags
& wxTREE_HITTEST_ONITEMSTATEICON
)
2848 event
.m_item
= item
;
2849 eventType
= wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK
;
2857 TV_HITTESTINFO tvhti
;
2858 ::GetCursorPos(&tvhti
.pt
);
2859 ::ScreenToClient(GetHwnd(), &tvhti
.pt
);
2860 if ( TreeView_HitTest(GetHwnd(), &tvhti
) )
2862 if ( tvhti
.flags
& TVHT_ONITEM
)
2864 event
.m_item
= tvhti
.hItem
;
2865 eventType
= (int)hdr
->code
== NM_DBLCLK
2866 ? wxEVT_COMMAND_TREE_ITEM_ACTIVATED
2867 : wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK
;
2869 event
.m_pointDrag
.x
= tvhti
.pt
.x
;
2870 event
.m_pointDrag
.y
= tvhti
.pt
.y
;
2879 return wxControl::MSWOnNotify(idCtrl
, lParam
, result
);
2882 event
.SetEventType(eventType
);
2884 if ( event
.m_item
.IsOk() )
2885 event
.SetClientObject(GetItemData(event
.m_item
));
2887 bool processed
= HandleWindowEvent(event
);
2890 switch ( hdr
->code
)
2893 // we translate NM_DBLCLK into ACTIVATED event and if the user
2894 // handled the activation of the item we shouldn't proceed with
2895 // also using the same double click for toggling the item expanded
2896 // state -- but OTOH do let the user to expand/collapse the item by
2897 // double clicking on it if the activation is not handled specially
2898 *result
= processed
;
2902 // prevent tree control from sending WM_CONTEXTMENU to our parent
2903 // (which it does if NM_RCLICK is not handled) because we want to
2904 // send it to the control itself
2908 ::SendMessage(GetHwnd(), WM_CONTEXTMENU
,
2909 (WPARAM
)GetHwnd(), ::GetMessagePos());
2913 case TVN_BEGINRDRAG
:
2915 if ( event
.IsAllowed() )
2917 // normally this is impossible because the m_dragImage is
2918 // deleted once the drag operation is over
2919 wxASSERT_MSG( !m_dragImage
, _T("starting to drag once again?") );
2921 m_dragImage
= new wxDragImage(*this, event
.m_item
);
2922 m_dragImage
->BeginDrag(wxPoint(0,0), this);
2923 m_dragImage
->Show();
2925 #endif // wxUSE_DRAGIMAGE
2928 case TVN_DELETEITEM
:
2930 // NB: we might process this message using wxWidgets event
2931 // tables, but due to overhead of wxWin event system we
2932 // prefer to do it here ourself (otherwise deleting a tree
2933 // with many items is just too slow)
2934 NM_TREEVIEW
*tv
= (NM_TREEVIEW
*)lParam
;
2936 wxTreeItemParam
*param
=
2937 (wxTreeItemParam
*)tv
->itemOld
.lParam
;
2940 processed
= true; // Make sure we don't get called twice
2944 case TVN_BEGINLABELEDIT
:
2945 // return true to cancel label editing
2946 *result
= !event
.IsAllowed();
2948 // set ES_WANTRETURN ( like we do in BeginLabelEdit )
2949 if ( event
.IsAllowed() )
2951 HWND hText
= TreeView_GetEditControl(GetHwnd());
2954 // MBN: if m_textCtrl already has an HWND, it is a stale
2955 // pointer from a previous edit (because the user
2956 // didn't modify the label before dismissing the control,
2957 // and TVN_ENDLABELEDIT was not sent), so delete it
2958 if ( m_textCtrl
&& m_textCtrl
->GetHWND() )
2961 m_textCtrl
= new wxTextCtrl();
2962 m_textCtrl
->SetParent(this);
2963 m_textCtrl
->SetHWND((WXHWND
)hText
);
2964 m_textCtrl
->SubclassWin((WXHWND
)hText
);
2966 // set wxTE_PROCESS_ENTER style for the text control to
2967 // force it to process the Enter presses itself, otherwise
2968 // they could be stolen from it by the dialog
2970 m_textCtrl
->SetWindowStyle(m_textCtrl
->GetWindowStyle()
2971 | wxTE_PROCESS_ENTER
);
2974 else // we had set m_idEdited before
2980 case TVN_ENDLABELEDIT
:
2981 // return true to set the label to the new string: note that we
2982 // also must pretend that we did process the message or it is going
2983 // to be passed to DefWindowProc() which will happily return false
2984 // cancelling the label change
2985 *result
= event
.IsAllowed();
2988 // ensure that we don't have the text ctrl which is going to be
2994 #ifdef TVN_GETINFOTIP
2995 case TVN_GETINFOTIP
:
2997 // If the user permitted a tooltip change, change it
2998 if (event
.IsAllowed())
3000 SetToolTip(event
.m_label
);
3007 case TVN_SELCHANGING
:
3008 case TVN_ITEMEXPANDING
:
3009 // return true to prevent the action from happening
3010 *result
= !event
.IsAllowed();
3013 case TVN_ITEMEXPANDED
:
3015 NM_TREEVIEW
*tv
= (NM_TREEVIEW
*)lParam
;
3016 const wxTreeItemId
id(tv
->itemNew
.hItem
);
3018 if ( tv
->action
== TVE_COLLAPSE
)
3020 if ( wxApp::GetComCtl32Version() >= 600 )
3022 // for some reason the item selection rectangle depends
3023 // on whether it is expanded or collapsed (at least
3024 // with comctl32.dll v6): it is wider (by 3 pixels) in
3025 // the expanded state, so when the item collapses and
3026 // then is deselected the rightmost 3 pixels of the
3027 // previously drawn selection are left on the screen
3029 // it's not clear if it's a bug in comctl32.dll or in
3030 // our code (because it does not happen in Explorer but
3031 // OTOH we don't do anything which could result in this
3032 // AFAICS) but we do need to work around it to avoid
3039 // the item is also not refreshed properly after expansion when
3040 // it has an image depending on the expanded/collapsed state:
3041 // again, it's not clear if the bug is in comctl32.dll or our
3043 int image
= GetItemImage(id
, wxTreeItemIcon_Expanded
);
3052 case TVN_GETDISPINFO
:
3053 // NB: so far the user can't set the image himself anyhow, so do it
3054 // anyway - but this may change later
3055 //if ( /* !processed && */ )
3057 wxTreeItemId item
= event
.m_item
;
3058 TV_DISPINFO
*info
= (TV_DISPINFO
*)lParam
;
3060 const wxTreeItemParam
* const param
= GetItemParam(item
);
3064 if ( info
->item
.mask
& TVIF_IMAGE
)
3069 IsExpanded(item
) ? wxTreeItemIcon_Expanded
3070 : wxTreeItemIcon_Normal
3073 if ( info
->item
.mask
& TVIF_SELECTEDIMAGE
)
3075 info
->item
.iSelectedImage
=
3078 IsExpanded(item
) ? wxTreeItemIcon_SelectedExpanded
3079 : wxTreeItemIcon_Selected
3086 // for the other messages the return value is ignored and there is
3087 // nothing special to do
3092 // ----------------------------------------------------------------------------
3094 // ----------------------------------------------------------------------------
3096 // why do they define INDEXTOSTATEIMAGEMASK but not the inverse?
3097 #define STATEIMAGEMASKTOINDEX(state) (((state) & TVIS_STATEIMAGEMASK) >> 12)
3099 int wxTreeCtrl::DoGetItemState(const wxTreeItemId
& item
) const
3101 wxCHECK_MSG( item
.IsOk(), wxTREE_ITEMSTATE_NONE
, wxT("invalid tree item") );
3103 // receive the desired information
3104 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_STATEIMAGEMASK
);
3107 // state images are one-based
3108 return STATEIMAGEMASKTOINDEX(tvItem
.state
) - 1;
3111 void wxTreeCtrl::DoSetItemState(const wxTreeItemId
& item
, int state
)
3113 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
3115 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_STATEIMAGEMASK
);
3117 // state images are one-based
3118 // 0 if no state image display (wxTREE_ITEMSTATE_NONE = -1)
3119 tvItem
.state
= INDEXTOSTATEIMAGEMASK(state
+ 1);
3124 #endif // wxUSE_TREECTRL