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/msw/private.h"
42 // Set this to 1 to be _absolutely_ sure that repainting will work for all
43 // comctl32.dll versions
44 #define wxUSE_COMCTL32_SAFELY 0
46 #include "wx/imaglist.h"
47 #include "wx/msw/dragimag.h"
49 // macros to hide the cast ugliness
50 // --------------------------------
52 // get HTREEITEM from wxTreeItemId
53 #define HITEM(item) ((HTREEITEM)(((item).m_pItem)))
56 // older SDKs are missing these
57 #ifndef TVN_ITEMCHANGINGA
59 #define TVN_ITEMCHANGINGA (TVN_FIRST-16)
60 #define TVN_ITEMCHANGINGW (TVN_FIRST-17)
62 typedef struct tagNMTVITEMCHANGE
75 // this helper class is used on vista systems for preventing unwanted
76 // item state changes in the vista tree control. It is only effective in
77 // multi-select mode on vista systems.
79 // The vista tree control includes some new code that originally broke the
80 // multi-selection tree, causing seemingly spurious item selection state changes
81 // during Shift or Ctrl-click item selection. (To witness the original broken
82 // behavior, simply make IsLocked() below always return false). This problem was
83 // solved by using the following class to 'unlock' an item's selection state.
85 class TreeItemUnlocker
88 // unlock a single item
89 TreeItemUnlocker(HTREEITEM item
) { ms_unlockedItem
= item
; }
91 // unlock all items, don't use unless absolutely necessary
92 TreeItemUnlocker() { ms_unlockedItem
= (HTREEITEM
)-1; }
94 // lock everything back
95 ~TreeItemUnlocker() { ms_unlockedItem
= NULL
; }
98 // check if the item state is currently locked
99 static bool IsLocked(HTREEITEM item
)
100 { return ms_unlockedItem
!= (HTREEITEM
)-1 && item
!= ms_unlockedItem
; }
103 static HTREEITEM ms_unlockedItem
;
106 HTREEITEM
TreeItemUnlocker::ms_unlockedItem
= NULL
;
108 // ----------------------------------------------------------------------------
110 // ----------------------------------------------------------------------------
112 // wrappers for TreeView_GetItem/TreeView_SetItem
113 static bool IsItemSelected(HWND hwndTV
, HTREEITEM hItem
)
117 tvi
.mask
= TVIF_STATE
| TVIF_HANDLE
;
118 tvi
.stateMask
= TVIS_SELECTED
;
121 TreeItemUnlocker
unlocker(hItem
);
123 if ( !TreeView_GetItem(hwndTV
, &tvi
) )
125 wxLogLastError(wxT("TreeView_GetItem"));
128 return (tvi
.state
& TVIS_SELECTED
) != 0;
131 static bool SelectItem(HWND hwndTV
, HTREEITEM hItem
, bool select
= true)
134 tvi
.mask
= TVIF_STATE
| TVIF_HANDLE
;
135 tvi
.stateMask
= TVIS_SELECTED
;
136 tvi
.state
= select
? TVIS_SELECTED
: 0;
139 TreeItemUnlocker
unlocker(hItem
);
141 if ( TreeView_SetItem(hwndTV
, &tvi
) == -1 )
143 wxLogLastError(wxT("TreeView_SetItem"));
150 static inline void UnselectItem(HWND hwndTV
, HTREEITEM htItem
)
152 SelectItem(hwndTV
, htItem
, false);
155 // helper function which selects all items in a range and, optionally,
156 // unselects all others
157 static void SelectRange(HWND hwndTV
,
160 bool unselectOthers
= true)
162 // find the first (or last) item and select it
164 HTREEITEM htItem
= (HTREEITEM
)TreeView_GetRoot(hwndTV
);
165 while ( htItem
&& cont
)
167 if ( (htItem
== htFirst
) || (htItem
== htLast
) )
169 if ( !IsItemSelected(hwndTV
, htItem
) )
171 SelectItem(hwndTV
, htItem
);
178 if ( unselectOthers
&& IsItemSelected(hwndTV
, htItem
) )
180 UnselectItem(hwndTV
, htItem
);
184 htItem
= (HTREEITEM
)TreeView_GetNextVisible(hwndTV
, htItem
);
187 // select the items in range
188 cont
= htFirst
!= htLast
;
189 while ( htItem
&& cont
)
191 if ( !IsItemSelected(hwndTV
, htItem
) )
193 SelectItem(hwndTV
, htItem
);
196 cont
= (htItem
!= htFirst
) && (htItem
!= htLast
);
198 htItem
= (HTREEITEM
)TreeView_GetNextVisible(hwndTV
, htItem
);
202 if ( unselectOthers
)
206 if ( IsItemSelected(hwndTV
, htItem
) )
208 UnselectItem(hwndTV
, htItem
);
211 htItem
= (HTREEITEM
)TreeView_GetNextVisible(hwndTV
, htItem
);
215 // seems to be necessary - otherwise the just selected items don't always
216 // appear as selected
217 UpdateWindow(hwndTV
);
220 // helper function which tricks the standard control into changing the focused
221 // item without changing anything else (if someone knows why Microsoft doesn't
222 // allow to do it by just setting TVIS_FOCUSED flag, please tell me!)
224 // returns true if the focus was changed, false if the given item was already
226 static bool SetFocus(HWND hwndTV
, HTREEITEM htItem
)
229 HTREEITEM htFocus
= (HTREEITEM
)TreeView_GetSelection(hwndTV
);
231 if ( htItem
== htFocus
)
236 // remember the selection state of the item
237 bool wasSelected
= IsItemSelected(hwndTV
, htItem
);
239 if ( htFocus
&& IsItemSelected(hwndTV
, htFocus
) )
241 // prevent the tree from unselecting the old focus which it
242 // would do by default (TreeView_SelectItem unselects the
244 TreeView_SelectItem(hwndTV
, 0);
245 SelectItem(hwndTV
, htFocus
);
248 TreeView_SelectItem(hwndTV
, htItem
);
252 // need to clear the selection which TreeView_SelectItem() gave
254 UnselectItem(hwndTV
, htItem
);
256 //else: was selected, still selected - ok
260 bool wasFocusSelected
= IsItemSelected(hwndTV
, htFocus
);
262 // just clear the focus
263 TreeView_SelectItem(hwndTV
, 0);
265 if ( wasFocusSelected
)
267 // restore the selection state
268 SelectItem(hwndTV
, htFocus
);
275 // ----------------------------------------------------------------------------
277 // ----------------------------------------------------------------------------
279 // a convenient wrapper around TV_ITEM struct which adds a ctor
281 #pragma warning( disable : 4097 ) // inheriting from typedef
284 struct wxTreeViewItem
: public TV_ITEM
286 wxTreeViewItem(const wxTreeItemId
& item
, // the item handle
287 UINT mask_
, // fields which are valid
288 UINT stateMask_
= 0) // for TVIF_STATE only
292 // hItem member is always valid
293 mask
= mask_
| TVIF_HANDLE
;
294 stateMask
= stateMask_
;
299 // ----------------------------------------------------------------------------
300 // This class is our userdata/lParam for the TV_ITEMs stored in the treeview.
302 // We need this for a couple of reasons:
304 // 1) This class is needed for support of different images: the Win32 common
305 // control natively supports only 2 images (the normal one and another for the
306 // selected state). We wish to provide support for 2 more of them for folder
307 // items (i.e. those which have children): for expanded state and for expanded
308 // selected state. For this we use this structure to store the additional items
311 // 2) This class is also needed to hold the HITEM so that we can sort
312 // it correctly in the MSW sort callback.
314 // In addition it makes other workarounds such as this easier and helps
315 // simplify the code.
316 // ----------------------------------------------------------------------------
318 class wxTreeItemParam
325 for ( size_t n
= 0; n
< WXSIZEOF(m_images
); n
++ )
331 // dtor deletes the associated data as well
332 virtual ~wxTreeItemParam() { delete m_data
; }
335 // get the real data associated with the item
336 wxTreeItemData
*GetData() const { return m_data
; }
338 void SetData(wxTreeItemData
*data
) { m_data
= data
; }
340 // do we have such image?
341 bool HasImage(wxTreeItemIcon which
) const { return m_images
[which
] != -1; }
342 // get image, falling back to the other images if this one is not
344 int GetImage(wxTreeItemIcon which
) const
346 int image
= m_images
[which
];
351 case wxTreeItemIcon_SelectedExpanded
:
352 image
= GetImage(wxTreeItemIcon_Expanded
);
357 case wxTreeItemIcon_Selected
:
358 case wxTreeItemIcon_Expanded
:
359 image
= GetImage(wxTreeItemIcon_Normal
);
362 case wxTreeItemIcon_Normal
:
367 wxFAIL_MSG( _T("unsupported wxTreeItemIcon value") );
373 // change the given image
374 void SetImage(int image
, wxTreeItemIcon which
) { m_images
[which
] = image
; }
377 const wxTreeItemId
& GetItem() const { return m_item
; }
379 void SetItem(const wxTreeItemId
& item
) { m_item
= item
; }
382 // all the images associated with the item
383 int m_images
[wxTreeItemIcon_Max
];
385 // item for sort callbacks
388 // the real client data
389 wxTreeItemData
*m_data
;
391 DECLARE_NO_COPY_CLASS(wxTreeItemParam
)
394 // wxVirutalNode is used in place of a single root when 'hidden' root is
396 class wxVirtualNode
: public wxTreeViewItem
399 wxVirtualNode(wxTreeItemParam
*param
)
400 : wxTreeViewItem(TVI_ROOT
, 0)
410 wxTreeItemParam
*GetParam() const { return m_param
; }
411 void SetParam(wxTreeItemParam
*param
) { delete m_param
; m_param
= param
; }
414 wxTreeItemParam
*m_param
;
416 DECLARE_NO_COPY_CLASS(wxVirtualNode
)
420 #pragma warning( default : 4097 )
423 // a macro to get the virtual root, returns NULL if none
424 #define GET_VIRTUAL_ROOT() ((wxVirtualNode *)m_pVirtualRoot)
426 // returns true if the item is the virtual root
427 #define IS_VIRTUAL_ROOT(item) (HITEM(item) == TVI_ROOT)
429 // a class which encapsulates the tree traversal logic: it vists all (unless
430 // OnVisit() returns false) items under the given one
431 class wxTreeTraversal
434 wxTreeTraversal(const wxTreeCtrl
*tree
)
439 // give it a virtual dtor: not really needed as the class is never used
440 // polymorphically and not even allocated on heap at all, but this is safer
441 // (in case it ever is) and silences the compiler warnings for now
442 virtual ~wxTreeTraversal() { }
444 // do traverse the tree: visit all items (recursively by default) under the
445 // given one; return true if all items were traversed or false if the
446 // traversal was aborted because OnVisit returned false
447 bool DoTraverse(const wxTreeItemId
& root
, bool recursively
= true);
449 // override this function to do whatever is needed for each item, return
450 // false to stop traversing
451 virtual bool OnVisit(const wxTreeItemId
& item
) = 0;
454 const wxTreeCtrl
*GetTree() const { return m_tree
; }
457 bool Traverse(const wxTreeItemId
& root
, bool recursively
);
459 const wxTreeCtrl
*m_tree
;
461 DECLARE_NO_COPY_CLASS(wxTreeTraversal
)
464 // internal class for getting the selected items
465 class TraverseSelections
: public wxTreeTraversal
468 TraverseSelections(const wxTreeCtrl
*tree
,
469 wxArrayTreeItemIds
& selections
)
470 : wxTreeTraversal(tree
), m_selections(selections
)
472 m_selections
.Empty();
474 if (tree
->GetCount() > 0)
475 DoTraverse(tree
->GetRootItem());
478 virtual bool OnVisit(const wxTreeItemId
& item
)
480 const wxTreeCtrl
* const tree
= GetTree();
482 // can't visit a virtual node.
483 if ( (tree
->GetRootItem() == item
) && tree
->HasFlag(wxTR_HIDE_ROOT
) )
488 if ( ::IsItemSelected(GetHwndOf(tree
), HITEM(item
)) )
490 m_selections
.Add(item
);
496 size_t GetCount() const { return m_selections
.GetCount(); }
499 wxArrayTreeItemIds
& m_selections
;
501 DECLARE_NO_COPY_CLASS(TraverseSelections
)
504 // internal class for counting tree items
505 class TraverseCounter
: public wxTreeTraversal
508 TraverseCounter(const wxTreeCtrl
*tree
,
509 const wxTreeItemId
& root
,
511 : wxTreeTraversal(tree
)
515 DoTraverse(root
, recursively
);
518 virtual bool OnVisit(const wxTreeItemId
& WXUNUSED(item
))
525 size_t GetCount() const { return m_count
; }
530 DECLARE_NO_COPY_CLASS(TraverseCounter
)
533 // ----------------------------------------------------------------------------
535 // ----------------------------------------------------------------------------
537 #if wxUSE_EXTENDED_RTTI
538 WX_DEFINE_FLAGS( wxTreeCtrlStyle
)
540 wxBEGIN_FLAGS( wxTreeCtrlStyle
)
541 // new style border flags, we put them first to
542 // use them for streaming out
543 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
544 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
545 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
546 wxFLAGS_MEMBER(wxBORDER_RAISED
)
547 wxFLAGS_MEMBER(wxBORDER_STATIC
)
548 wxFLAGS_MEMBER(wxBORDER_NONE
)
550 // old style border flags
551 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
552 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
553 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
554 wxFLAGS_MEMBER(wxRAISED_BORDER
)
555 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
556 wxFLAGS_MEMBER(wxBORDER
)
558 // standard window styles
559 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
560 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
561 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
562 wxFLAGS_MEMBER(wxWANTS_CHARS
)
563 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
564 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
565 wxFLAGS_MEMBER(wxVSCROLL
)
566 wxFLAGS_MEMBER(wxHSCROLL
)
568 wxFLAGS_MEMBER(wxTR_EDIT_LABELS
)
569 wxFLAGS_MEMBER(wxTR_NO_BUTTONS
)
570 wxFLAGS_MEMBER(wxTR_HAS_BUTTONS
)
571 wxFLAGS_MEMBER(wxTR_TWIST_BUTTONS
)
572 wxFLAGS_MEMBER(wxTR_NO_LINES
)
573 wxFLAGS_MEMBER(wxTR_FULL_ROW_HIGHLIGHT
)
574 wxFLAGS_MEMBER(wxTR_LINES_AT_ROOT
)
575 wxFLAGS_MEMBER(wxTR_HIDE_ROOT
)
576 wxFLAGS_MEMBER(wxTR_ROW_LINES
)
577 wxFLAGS_MEMBER(wxTR_HAS_VARIABLE_ROW_HEIGHT
)
578 wxFLAGS_MEMBER(wxTR_SINGLE
)
579 wxFLAGS_MEMBER(wxTR_MULTIPLE
)
580 #if WXWIN_COMPATIBILITY_2_8
581 wxFLAGS_MEMBER(wxTR_EXTENDED
)
583 wxFLAGS_MEMBER(wxTR_DEFAULT_STYLE
)
585 wxEND_FLAGS( wxTreeCtrlStyle
)
587 IMPLEMENT_DYNAMIC_CLASS_XTI(wxTreeCtrl
, wxControl
,"wx/treectrl.h")
589 wxBEGIN_PROPERTIES_TABLE(wxTreeCtrl
)
590 wxEVENT_PROPERTY( TextUpdated
, wxEVT_COMMAND_TEXT_UPDATED
, wxCommandEvent
)
591 wxEVENT_RANGE_PROPERTY( TreeEvent
, wxEVT_COMMAND_TREE_BEGIN_DRAG
, wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK
, wxTreeEvent
)
592 wxPROPERTY_FLAGS( WindowStyle
, wxTreeCtrlStyle
, long , SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
593 wxEND_PROPERTIES_TABLE()
595 wxBEGIN_HANDLERS_TABLE(wxTreeCtrl
)
596 wxEND_HANDLERS_TABLE()
598 wxCONSTRUCTOR_5( wxTreeCtrl
, wxWindow
* , Parent
, wxWindowID
, Id
, wxPoint
, Position
, wxSize
, Size
, long , WindowStyle
)
600 IMPLEMENT_DYNAMIC_CLASS(wxTreeCtrl
, wxControl
)
603 // ----------------------------------------------------------------------------
605 // ----------------------------------------------------------------------------
607 // indices in gs_expandEvents table below
622 // handy table for sending events - it has to be initialized during run-time
623 // now so can't be const any more
624 static /* const */ wxEventType gs_expandEvents
[IDX_WHAT_MAX
][IDX_HOW_MAX
];
627 but logically it's a const table with the following entries:
630 { wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxEVT_COMMAND_TREE_ITEM_COLLAPSING },
631 { wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxEVT_COMMAND_TREE_ITEM_EXPANDING }
635 // ============================================================================
637 // ============================================================================
639 // ----------------------------------------------------------------------------
641 // ----------------------------------------------------------------------------
643 bool wxTreeTraversal::DoTraverse(const wxTreeItemId
& root
, bool recursively
)
645 if ( !OnVisit(root
) )
648 return Traverse(root
, recursively
);
651 bool wxTreeTraversal::Traverse(const wxTreeItemId
& root
, bool recursively
)
653 wxTreeItemIdValue cookie
;
654 wxTreeItemId child
= m_tree
->GetFirstChild(root
, cookie
);
655 while ( child
.IsOk() )
657 // depth first traversal
658 if ( recursively
&& !Traverse(child
, true) )
661 if ( !OnVisit(child
) )
664 child
= m_tree
->GetNextChild(root
, cookie
);
670 // ----------------------------------------------------------------------------
671 // construction and destruction
672 // ----------------------------------------------------------------------------
674 void wxTreeCtrl::Init()
677 m_hasAnyAttr
= false;
681 m_pVirtualRoot
= NULL
;
683 // initialize the global array of events now as it can't be done statically
684 // with the wxEVT_XXX values being allocated during run-time only
685 gs_expandEvents
[IDX_COLLAPSE
][IDX_DONE
] = wxEVT_COMMAND_TREE_ITEM_COLLAPSED
;
686 gs_expandEvents
[IDX_COLLAPSE
][IDX_DOING
] = wxEVT_COMMAND_TREE_ITEM_COLLAPSING
;
687 gs_expandEvents
[IDX_EXPAND
][IDX_DONE
] = wxEVT_COMMAND_TREE_ITEM_EXPANDED
;
688 gs_expandEvents
[IDX_EXPAND
][IDX_DOING
] = wxEVT_COMMAND_TREE_ITEM_EXPANDING
;
691 bool wxTreeCtrl::Create(wxWindow
*parent
,
696 const wxValidator
& validator
,
697 const wxString
& name
)
701 if ( (style
& wxBORDER_MASK
) == wxBORDER_DEFAULT
)
702 style
|= wxBORDER_SUNKEN
;
704 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
708 DWORD wstyle
= MSWGetStyle(m_windowStyle
, & exStyle
);
709 wstyle
|= WS_TABSTOP
| TVS_SHOWSELALWAYS
;
711 if ((m_windowStyle
& wxTR_NO_LINES
) == 0)
712 wstyle
|= TVS_HASLINES
;
713 if ( m_windowStyle
& wxTR_HAS_BUTTONS
)
714 wstyle
|= TVS_HASBUTTONS
;
716 if ( m_windowStyle
& wxTR_EDIT_LABELS
)
717 wstyle
|= TVS_EDITLABELS
;
719 if ( m_windowStyle
& wxTR_LINES_AT_ROOT
)
720 wstyle
|= TVS_LINESATROOT
;
722 if ( m_windowStyle
& wxTR_FULL_ROW_HIGHLIGHT
)
724 if ( wxApp::GetComCtl32Version() >= 471 )
725 wstyle
|= TVS_FULLROWSELECT
;
728 #if !defined(__WXWINCE__) && defined(TVS_INFOTIP)
729 // Need so that TVN_GETINFOTIP messages will be sent
730 wstyle
|= TVS_INFOTIP
;
733 // Create the tree control.
734 if ( !MSWCreateControl(WC_TREEVIEW
, wstyle
, pos
, size
) )
737 #if wxUSE_COMCTL32_SAFELY
738 wxWindow::SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
739 wxWindow::SetForegroundColour(wxWindow::GetParent()->GetForegroundColour());
741 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
742 SetForegroundColour(wxWindow::GetParent()->GetForegroundColour());
744 // This works around a bug in the Windows tree control whereby for some versions
745 // of comctrl32, setting any colour actually draws the background in black.
746 // This will initialise the background to the system colour.
747 // THIS FIX NOW REVERTED since it caused problems on _other_ systems.
748 // Assume the user has an updated comctl32.dll.
749 ::SendMessage(GetHwnd(), TVM_SETBKCOLOR
, 0,-1);
750 wxWindow::SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
751 SetForegroundColour(wxWindow::GetParent()->GetForegroundColour());
755 // VZ: this is some experimental code which may be used to get the
756 // TVS_CHECKBOXES style functionality for comctl32.dll < 4.71.
757 // AFAIK, the standard DLL does about the same thing anyhow.
759 if ( m_windowStyle
& wxTR_MULTIPLE
)
763 // create the DC compatible with the current screen
764 HDC hdcMem
= CreateCompatibleDC(NULL
);
766 // create a mono bitmap of the standard size
767 int x
= ::GetSystemMetrics(SM_CXMENUCHECK
);
768 int y
= ::GetSystemMetrics(SM_CYMENUCHECK
);
769 wxImageList
imagelistCheckboxes(x
, y
, false, 2);
770 HBITMAP hbmpCheck
= CreateBitmap(x
, y
, // bitmap size
771 1, // # of color planes
772 1, // # bits needed for one pixel
773 0); // array containing colour data
774 SelectObject(hdcMem
, hbmpCheck
);
776 // then draw a check mark into it
777 RECT rect
= { 0, 0, x
, y
};
778 if ( !::DrawFrameControl(hdcMem
, &rect
,
780 DFCS_BUTTONCHECK
| DFCS_CHECKED
) )
782 wxLogLastError(wxT("DrawFrameControl(check)"));
785 bmp
.SetHBITMAP((WXHBITMAP
)hbmpCheck
);
786 imagelistCheckboxes
.Add(bmp
);
788 if ( !::DrawFrameControl(hdcMem
, &rect
,
792 wxLogLastError(wxT("DrawFrameControl(uncheck)"));
795 bmp
.SetHBITMAP((WXHBITMAP
)hbmpCheck
);
796 imagelistCheckboxes
.Add(bmp
);
802 SetStateImageList(&imagelistCheckboxes
);
806 wxSetCCUnicodeFormat(GetHwnd());
811 wxTreeCtrl::~wxTreeCtrl()
813 // delete any attributes
816 WX_CLEAR_HASH_MAP(wxMapTreeAttr
, m_attrs
);
818 // prevent TVN_DELETEITEM handler from deleting the attributes again!
819 m_hasAnyAttr
= false;
824 // delete user data to prevent memory leaks
825 // also deletes hidden root node storage.
829 // ----------------------------------------------------------------------------
831 // ----------------------------------------------------------------------------
833 /* static */ wxVisualAttributes
834 wxTreeCtrl::GetClassDefaultAttributes(wxWindowVariant variant
)
836 wxVisualAttributes attrs
= GetCompositeControlsDefaultAttributes(variant
);
838 // common controls have their own default font
839 attrs
.font
= wxGetCCDefaultFont();
845 // simple wrappers which add error checking in debug mode
847 bool wxTreeCtrl::DoGetItem(wxTreeViewItem
*tvItem
) const
849 wxCHECK_MSG( tvItem
->hItem
!= TVI_ROOT
, false,
850 _T("can't retrieve virtual root item") );
852 if ( !TreeView_GetItem(GetHwnd(), tvItem
) )
854 wxLogLastError(wxT("TreeView_GetItem"));
862 void wxTreeCtrl::DoSetItem(wxTreeViewItem
*tvItem
)
864 TreeItemUnlocker
unlocker(tvItem
->hItem
);
866 if ( TreeView_SetItem(GetHwnd(), tvItem
) == -1 )
868 wxLogLastError(wxT("TreeView_SetItem"));
872 unsigned int wxTreeCtrl::GetCount() const
874 return (unsigned int)TreeView_GetCount(GetHwnd());
877 unsigned int wxTreeCtrl::GetIndent() const
879 return TreeView_GetIndent(GetHwnd());
882 void wxTreeCtrl::SetIndent(unsigned int indent
)
884 TreeView_SetIndent(GetHwnd(), indent
);
887 void wxTreeCtrl::SetAnyImageList(wxImageList
*imageList
, int which
)
890 (void) TreeView_SetImageList(GetHwnd(),
891 imageList
? imageList
->GetHIMAGELIST() : 0,
895 void wxTreeCtrl::SetImageList(wxImageList
*imageList
)
897 if (m_ownsImageListNormal
)
898 delete m_imageListNormal
;
900 SetAnyImageList(m_imageListNormal
= imageList
, TVSIL_NORMAL
);
901 m_ownsImageListNormal
= false;
904 void wxTreeCtrl::SetStateImageList(wxImageList
*imageList
)
906 if (m_ownsImageListState
) delete m_imageListState
;
907 SetAnyImageList(m_imageListState
= imageList
, TVSIL_STATE
);
908 m_ownsImageListState
= false;
911 size_t wxTreeCtrl::GetChildrenCount(const wxTreeItemId
& item
,
912 bool recursively
) const
914 wxCHECK_MSG( item
.IsOk(), 0u, wxT("invalid tree item") );
916 TraverseCounter
counter(this, item
, recursively
);
917 return counter
.GetCount() - 1;
920 // ----------------------------------------------------------------------------
922 // ----------------------------------------------------------------------------
924 bool wxTreeCtrl::SetBackgroundColour(const wxColour
&colour
)
926 #if !wxUSE_COMCTL32_SAFELY
927 if ( !wxWindowBase::SetBackgroundColour(colour
) )
930 ::SendMessage(GetHwnd(), TVM_SETBKCOLOR
, 0, colour
.GetPixel());
936 bool wxTreeCtrl::SetForegroundColour(const wxColour
&colour
)
938 #if !wxUSE_COMCTL32_SAFELY
939 if ( !wxWindowBase::SetForegroundColour(colour
) )
942 ::SendMessage(GetHwnd(), TVM_SETTEXTCOLOR
, 0, colour
.GetPixel());
948 // ----------------------------------------------------------------------------
950 // ----------------------------------------------------------------------------
952 bool wxTreeCtrl::IsHiddenRoot(const wxTreeItemId
& item
) const
954 return HITEM(item
) == TVI_ROOT
&& HasFlag(wxTR_HIDE_ROOT
);
957 wxString
wxTreeCtrl::GetItemText(const wxTreeItemId
& item
) const
959 wxCHECK_MSG( item
.IsOk(), wxEmptyString
, wxT("invalid tree item") );
961 wxChar buf
[512]; // the size is arbitrary...
963 wxTreeViewItem
tvItem(item
, TVIF_TEXT
);
964 tvItem
.pszText
= buf
;
965 tvItem
.cchTextMax
= WXSIZEOF(buf
);
966 if ( !DoGetItem(&tvItem
) )
968 // don't return some garbage which was on stack, but an empty string
972 return wxString(buf
);
975 void wxTreeCtrl::SetItemText(const wxTreeItemId
& item
, const wxString
& text
)
977 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
979 if ( IS_VIRTUAL_ROOT(item
) )
982 wxTreeViewItem
tvItem(item
, TVIF_TEXT
);
983 tvItem
.pszText
= (wxChar
*)text
.wx_str(); // conversion is ok
986 // when setting the text of the item being edited, the text control should
987 // be updated to reflect the new text as well, otherwise calling
988 // SetItemText() in the OnBeginLabelEdit() handler doesn't have any effect
990 // don't use GetEditControl() here because m_textCtrl is not set yet
991 HWND hwndEdit
= TreeView_GetEditControl(GetHwnd());
994 if ( item
== m_idEdited
)
996 ::SetWindowText(hwndEdit
, text
.wx_str());
1001 int wxTreeCtrl::GetItemImage(const wxTreeItemId
& item
,
1002 wxTreeItemIcon which
) const
1004 wxCHECK_MSG( item
.IsOk(), -1, wxT("invalid tree item") );
1006 if ( IsHiddenRoot(item
) )
1008 // no images for hidden root item
1012 wxTreeItemParam
*param
= GetItemParam(item
);
1014 return param
&& param
->HasImage(which
) ? param
->GetImage(which
) : -1;
1017 void wxTreeCtrl::SetItemImage(const wxTreeItemId
& item
, int image
,
1018 wxTreeItemIcon which
)
1020 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1021 wxCHECK_RET( which
>= 0 &&
1022 which
< wxTreeItemIcon_Max
,
1023 wxT("invalid image index"));
1026 if ( IsHiddenRoot(item
) )
1028 // no images for hidden root item
1032 wxTreeItemParam
*data
= GetItemParam(item
);
1036 data
->SetImage(image
, which
);
1041 wxTreeItemParam
*wxTreeCtrl::GetItemParam(const wxTreeItemId
& item
) const
1043 wxCHECK_MSG( item
.IsOk(), NULL
, wxT("invalid tree item") );
1045 wxTreeViewItem
tvItem(item
, TVIF_PARAM
);
1047 // hidden root may still have data.
1048 if ( IS_VIRTUAL_ROOT(item
) )
1050 return GET_VIRTUAL_ROOT()->GetParam();
1054 if ( !DoGetItem(&tvItem
) )
1059 return (wxTreeItemParam
*)tvItem
.lParam
;
1062 wxTreeItemData
*wxTreeCtrl::GetItemData(const wxTreeItemId
& item
) const
1064 wxTreeItemParam
*data
= GetItemParam(item
);
1066 return data
? data
->GetData() : NULL
;
1069 void wxTreeCtrl::SetItemData(const wxTreeItemId
& item
, wxTreeItemData
*data
)
1071 // first, associate this piece of data with this item
1077 wxTreeItemParam
*param
= GetItemParam(item
);
1079 wxCHECK_RET( param
, wxT("failed to change tree items data") );
1081 param
->SetData(data
);
1084 void wxTreeCtrl::SetItemHasChildren(const wxTreeItemId
& item
, bool has
)
1086 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1088 if ( IS_VIRTUAL_ROOT(item
) )
1091 wxTreeViewItem
tvItem(item
, TVIF_CHILDREN
);
1092 tvItem
.cChildren
= (int)has
;
1096 void wxTreeCtrl::SetItemBold(const wxTreeItemId
& item
, bool bold
)
1098 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1100 if ( IS_VIRTUAL_ROOT(item
) )
1103 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_BOLD
);
1104 tvItem
.state
= bold
? TVIS_BOLD
: 0;
1108 void wxTreeCtrl::SetItemDropHighlight(const wxTreeItemId
& item
, bool highlight
)
1110 if ( IS_VIRTUAL_ROOT(item
) )
1113 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_DROPHILITED
);
1114 tvItem
.state
= highlight
? TVIS_DROPHILITED
: 0;
1118 void wxTreeCtrl::RefreshItem(const wxTreeItemId
& item
)
1120 if ( IS_VIRTUAL_ROOT(item
) )
1124 if ( GetBoundingRect(item
, rect
) )
1130 wxColour
wxTreeCtrl::GetItemTextColour(const wxTreeItemId
& item
) const
1132 wxCHECK_MSG( item
.IsOk(), wxNullColour
, wxT("invalid tree item") );
1134 wxMapTreeAttr::const_iterator it
= m_attrs
.find(item
.m_pItem
);
1135 return it
== m_attrs
.end() ? wxNullColour
: it
->second
->GetTextColour();
1138 wxColour
wxTreeCtrl::GetItemBackgroundColour(const wxTreeItemId
& item
) const
1140 wxCHECK_MSG( item
.IsOk(), wxNullColour
, wxT("invalid tree item") );
1142 wxMapTreeAttr::const_iterator it
= m_attrs
.find(item
.m_pItem
);
1143 return it
== m_attrs
.end() ? wxNullColour
: it
->second
->GetBackgroundColour();
1146 wxFont
wxTreeCtrl::GetItemFont(const wxTreeItemId
& item
) const
1148 wxCHECK_MSG( item
.IsOk(), wxNullFont
, wxT("invalid tree item") );
1150 wxMapTreeAttr::const_iterator it
= m_attrs
.find(item
.m_pItem
);
1151 return it
== m_attrs
.end() ? wxNullFont
: it
->second
->GetFont();
1154 void wxTreeCtrl::SetItemTextColour(const wxTreeItemId
& item
,
1155 const wxColour
& col
)
1157 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1159 wxTreeItemAttr
*attr
;
1160 wxMapTreeAttr::iterator it
= m_attrs
.find(item
.m_pItem
);
1161 if ( it
== m_attrs
.end() )
1163 m_hasAnyAttr
= true;
1165 m_attrs
[item
.m_pItem
] =
1166 attr
= new wxTreeItemAttr
;
1173 attr
->SetTextColour(col
);
1178 void wxTreeCtrl::SetItemBackgroundColour(const wxTreeItemId
& item
,
1179 const wxColour
& col
)
1181 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1183 wxTreeItemAttr
*attr
;
1184 wxMapTreeAttr::iterator it
= m_attrs
.find(item
.m_pItem
);
1185 if ( it
== m_attrs
.end() )
1187 m_hasAnyAttr
= true;
1189 m_attrs
[item
.m_pItem
] =
1190 attr
= new wxTreeItemAttr
;
1192 else // already in the hash
1197 attr
->SetBackgroundColour(col
);
1202 void wxTreeCtrl::SetItemFont(const wxTreeItemId
& item
, const wxFont
& font
)
1204 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1206 wxTreeItemAttr
*attr
;
1207 wxMapTreeAttr::iterator it
= m_attrs
.find(item
.m_pItem
);
1208 if ( it
== m_attrs
.end() )
1210 m_hasAnyAttr
= true;
1212 m_attrs
[item
.m_pItem
] =
1213 attr
= new wxTreeItemAttr
;
1215 else // already in the hash
1220 attr
->SetFont(font
);
1222 // Reset the item's text to ensure that the bounding rect will be adjusted
1223 // for the new font.
1224 SetItemText(item
, GetItemText(item
));
1229 // ----------------------------------------------------------------------------
1231 // ----------------------------------------------------------------------------
1233 bool wxTreeCtrl::IsVisible(const wxTreeItemId
& item
) const
1235 wxCHECK_MSG( item
.IsOk(), false, wxT("invalid tree item") );
1237 if ( item
== wxTreeItemId(TVI_ROOT
) )
1239 // virtual (hidden) root is never visible
1243 // Bug in Gnu-Win32 headers, so don't use the macro TreeView_GetItemRect
1246 // this ugliness comes directly from MSDN - it *is* the correct way to pass
1247 // the HTREEITEM with TVM_GETITEMRECT
1248 *(HTREEITEM
*)&rect
= HITEM(item
);
1250 // true means to get rect for just the text, not the whole line
1251 if ( !::SendMessage(GetHwnd(), TVM_GETITEMRECT
, true, (LPARAM
)&rect
) )
1253 // if TVM_GETITEMRECT returned false, then the item is definitely not
1254 // visible (because its parent is not expanded)
1258 // however if it returned true, the item might still be outside the
1259 // currently visible part of the tree, test for it (notice that partly
1260 // visible means visible here)
1261 return rect
.bottom
> 0 && rect
.top
< GetClientSize().y
;
1264 bool wxTreeCtrl::ItemHasChildren(const wxTreeItemId
& item
) const
1266 wxCHECK_MSG( item
.IsOk(), false, wxT("invalid tree item") );
1268 wxTreeViewItem
tvItem(item
, TVIF_CHILDREN
);
1271 return tvItem
.cChildren
!= 0;
1274 bool wxTreeCtrl::IsExpanded(const wxTreeItemId
& item
) const
1276 wxCHECK_MSG( item
.IsOk(), false, wxT("invalid tree item") );
1278 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_EXPANDED
);
1281 return (tvItem
.state
& TVIS_EXPANDED
) != 0;
1284 bool wxTreeCtrl::IsSelected(const wxTreeItemId
& item
) const
1286 wxCHECK_MSG( item
.IsOk(), false, wxT("invalid tree item") );
1288 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_SELECTED
);
1291 return (tvItem
.state
& TVIS_SELECTED
) != 0;
1294 bool wxTreeCtrl::IsBold(const wxTreeItemId
& item
) const
1296 wxCHECK_MSG( item
.IsOk(), false, wxT("invalid tree item") );
1298 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_BOLD
);
1301 return (tvItem
.state
& TVIS_BOLD
) != 0;
1304 // ----------------------------------------------------------------------------
1306 // ----------------------------------------------------------------------------
1308 wxTreeItemId
wxTreeCtrl::GetRootItem() const
1310 // Root may be real (visible) or virtual (hidden).
1311 if ( GET_VIRTUAL_ROOT() )
1314 return wxTreeItemId(TreeView_GetRoot(GetHwnd()));
1317 wxTreeItemId
wxTreeCtrl::GetSelection() const
1319 wxCHECK_MSG( !(m_windowStyle
& wxTR_MULTIPLE
), wxTreeItemId(),
1320 wxT("this only works with single selection controls") );
1322 return wxTreeItemId(TreeView_GetSelection(GetHwnd()));
1325 wxTreeItemId
wxTreeCtrl::GetItemParent(const wxTreeItemId
& item
) const
1327 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1331 if ( IS_VIRTUAL_ROOT(item
) )
1333 // no parent for the virtual root
1338 hItem
= TreeView_GetParent(GetHwnd(), HITEM(item
));
1339 if ( !hItem
&& HasFlag(wxTR_HIDE_ROOT
) )
1341 // the top level items should have the virtual root as their parent
1346 return wxTreeItemId(hItem
);
1349 wxTreeItemId
wxTreeCtrl::GetFirstChild(const wxTreeItemId
& item
,
1350 wxTreeItemIdValue
& cookie
) const
1352 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1354 // remember the last child returned in 'cookie'
1355 cookie
= TreeView_GetChild(GetHwnd(), HITEM(item
));
1357 return wxTreeItemId(cookie
);
1360 wxTreeItemId
wxTreeCtrl::GetNextChild(const wxTreeItemId
& WXUNUSED(item
),
1361 wxTreeItemIdValue
& cookie
) const
1363 wxTreeItemId
fromCookie(cookie
);
1365 HTREEITEM hitem
= HITEM(fromCookie
);
1367 hitem
= TreeView_GetNextSibling(GetHwnd(), hitem
);
1369 wxTreeItemId
item(hitem
);
1371 cookie
= item
.m_pItem
;
1376 wxTreeItemId
wxTreeCtrl::GetLastChild(const wxTreeItemId
& item
) const
1378 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1380 // can this be done more efficiently?
1381 wxTreeItemIdValue cookie
;
1383 wxTreeItemId childLast
,
1384 child
= GetFirstChild(item
, cookie
);
1385 while ( child
.IsOk() )
1388 child
= GetNextChild(item
, cookie
);
1394 wxTreeItemId
wxTreeCtrl::GetNextSibling(const wxTreeItemId
& item
) const
1396 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1397 return wxTreeItemId(TreeView_GetNextSibling(GetHwnd(), HITEM(item
)));
1400 wxTreeItemId
wxTreeCtrl::GetPrevSibling(const wxTreeItemId
& item
) const
1402 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1403 return wxTreeItemId(TreeView_GetPrevSibling(GetHwnd(), HITEM(item
)));
1406 wxTreeItemId
wxTreeCtrl::GetFirstVisibleItem() const
1408 return wxTreeItemId(TreeView_GetFirstVisible(GetHwnd()));
1411 wxTreeItemId
wxTreeCtrl::GetNextVisible(const wxTreeItemId
& item
) const
1413 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1414 wxASSERT_MSG( IsVisible(item
), wxT("The item you call GetNextVisible() for must be visible itself!"));
1416 wxTreeItemId
next(TreeView_GetNextVisible(GetHwnd(), HITEM(item
)));
1417 if ( next
.IsOk() && !IsVisible(next
) )
1419 // Win32 considers that any non-collapsed item is visible while we want
1420 // to return only really visible items
1427 wxTreeItemId
wxTreeCtrl::GetPrevVisible(const wxTreeItemId
& item
) const
1429 wxCHECK_MSG( item
.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1430 wxASSERT_MSG( IsVisible(item
), wxT("The item you call GetPrevVisible() for must be visible itself!"));
1432 wxTreeItemId
prev(TreeView_GetPrevVisible(GetHwnd(), HITEM(item
)));
1433 if ( prev
.IsOk() && !IsVisible(prev
) )
1435 // just as above, Win32 function will happily return the previous item
1436 // in the tree for the first visible item too
1443 // ----------------------------------------------------------------------------
1444 // multiple selections emulation
1445 // ----------------------------------------------------------------------------
1447 bool wxTreeCtrl::IsItemChecked(const wxTreeItemId
& item
) const
1449 wxCHECK_MSG( item
.IsOk(), false, wxT("invalid tree item") );
1451 // receive the desired information.
1452 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_STATEIMAGEMASK
);
1455 // state image indices are 1 based
1456 return ((tvItem
.state
>> 12) - 1) == 1;
1459 void wxTreeCtrl::SetItemCheck(const wxTreeItemId
& item
, bool check
)
1461 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1463 // receive the desired information.
1464 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_STATEIMAGEMASK
);
1468 // state images are one-based
1469 tvItem
.state
= (check
? 2 : 1) << 12;
1474 size_t wxTreeCtrl::GetSelections(wxArrayTreeItemIds
& selections
) const
1476 TraverseSelections
selector(this, selections
);
1478 return selector
.GetCount();
1481 // ----------------------------------------------------------------------------
1483 // ----------------------------------------------------------------------------
1485 wxTreeItemId
wxTreeCtrl::DoInsertAfter(const wxTreeItemId
& parent
,
1486 const wxTreeItemId
& hInsertAfter
,
1487 const wxString
& text
,
1488 int image
, int selectedImage
,
1489 wxTreeItemData
*data
)
1491 wxCHECK_MSG( parent
.IsOk() || !TreeView_GetRoot(GetHwnd()),
1493 _T("can't have more than one root in the tree") );
1495 TV_INSERTSTRUCT tvIns
;
1496 tvIns
.hParent
= HITEM(parent
);
1497 tvIns
.hInsertAfter
= HITEM(hInsertAfter
);
1499 // this is how we insert the item as the first child: supply a NULL
1501 if ( !tvIns
.hInsertAfter
)
1503 tvIns
.hInsertAfter
= TVI_FIRST
;
1507 if ( !text
.empty() )
1510 tvIns
.item
.pszText
= (wxChar
*)text
.wx_str(); // cast is ok
1514 tvIns
.item
.pszText
= NULL
;
1515 tvIns
.item
.cchTextMax
= 0;
1518 // create the param which will store the other item parameters
1519 wxTreeItemParam
*param
= new wxTreeItemParam
;
1521 // we return the images on demand as they depend on whether the item is
1522 // expanded or collapsed too in our case
1523 mask
|= TVIF_IMAGE
| TVIF_SELECTEDIMAGE
;
1524 tvIns
.item
.iImage
= I_IMAGECALLBACK
;
1525 tvIns
.item
.iSelectedImage
= I_IMAGECALLBACK
;
1527 param
->SetImage(image
, wxTreeItemIcon_Normal
);
1528 param
->SetImage(selectedImage
, wxTreeItemIcon_Selected
);
1531 tvIns
.item
.lParam
= (LPARAM
)param
;
1532 tvIns
.item
.mask
= mask
;
1534 // don't use the hack below for the children of hidden root: this results
1535 // in a crash inside comctl32.dll when we call TreeView_GetItemRect()
1536 const bool firstChild
= !IsHiddenRoot(parent
) &&
1537 !TreeView_GetChild(GetHwnd(), HITEM(parent
));
1539 HTREEITEM id
= TreeView_InsertItem(GetHwnd(), &tvIns
);
1542 wxLogLastError(wxT("TreeView_InsertItem"));
1545 // apparently some Windows versions (2000 and XP are reported to do this)
1546 // sometimes don't refresh the tree after adding the first child and so we
1547 // need this to make the "[+]" appear
1551 TreeView_GetItemRect(GetHwnd(), HITEM(parent
), &rect
, FALSE
);
1552 ::InvalidateRect(GetHwnd(), &rect
, FALSE
);
1555 // associate the application tree item with Win32 tree item handle
1558 // setup wxTreeItemData
1561 param
->SetData(data
);
1565 return wxTreeItemId(id
);
1568 wxTreeItemId
wxTreeCtrl::AddRoot(const wxString
& text
,
1569 int image
, int selectedImage
,
1570 wxTreeItemData
*data
)
1572 if ( HasFlag(wxTR_HIDE_ROOT
) )
1574 wxASSERT_MSG( !m_pVirtualRoot
, _T("tree can have only a single root") );
1576 // create a virtual root item, the parent for all the others
1577 wxTreeItemParam
*param
= new wxTreeItemParam
;
1578 param
->SetData(data
);
1580 m_pVirtualRoot
= new wxVirtualNode(param
);
1585 return DoInsertAfter(wxTreeItemId(), wxTreeItemId(),
1586 text
, image
, selectedImage
, data
);
1589 wxTreeItemId
wxTreeCtrl::DoInsertItem(const wxTreeItemId
& parent
,
1591 const wxString
& text
,
1592 int image
, int selectedImage
,
1593 wxTreeItemData
*data
)
1595 wxTreeItemId idPrev
;
1596 if ( index
== (size_t)-1 )
1598 // special value: append to the end
1601 else // find the item from index
1603 wxTreeItemIdValue cookie
;
1604 wxTreeItemId idCur
= GetFirstChild(parent
, cookie
);
1605 while ( index
!= 0 && idCur
.IsOk() )
1610 idCur
= GetNextChild(parent
, cookie
);
1613 // assert, not check: if the index is invalid, we will append the item
1615 wxASSERT_MSG( index
== 0, _T("bad index in wxTreeCtrl::InsertItem") );
1618 return DoInsertAfter(parent
, idPrev
, text
, image
, selectedImage
, data
);
1621 void wxTreeCtrl::Delete(const wxTreeItemId
& item
)
1623 // unlock tree selections on vista, without this the
1624 // tree ctrl will eventually crash after item deletion
1625 TreeItemUnlocker unlock_all
;
1627 if ( !TreeView_DeleteItem(GetHwnd(), HITEM(item
)) )
1629 wxLogLastError(wxT("TreeView_DeleteItem"));
1633 // delete all children (but don't delete the item itself)
1634 void wxTreeCtrl::DeleteChildren(const wxTreeItemId
& item
)
1636 // unlock tree selections on vista for the duration of this call
1637 TreeItemUnlocker unlock_all
;
1639 wxTreeItemIdValue cookie
;
1641 wxArrayTreeItemIds children
;
1642 wxTreeItemId child
= GetFirstChild(item
, cookie
);
1643 while ( child
.IsOk() )
1645 children
.Add(child
);
1647 child
= GetNextChild(item
, cookie
);
1650 size_t nCount
= children
.Count();
1651 for ( size_t n
= 0; n
< nCount
; n
++ )
1653 if ( !TreeView_DeleteItem(GetHwnd(), HITEM(children
[n
])) )
1655 wxLogLastError(wxT("TreeView_DeleteItem"));
1660 void wxTreeCtrl::DeleteAllItems()
1662 // unlock tree selections on vista for the duration of this call
1663 TreeItemUnlocker unlock_all
;
1665 // delete the "virtual" root item.
1666 if ( GET_VIRTUAL_ROOT() )
1668 delete GET_VIRTUAL_ROOT();
1669 m_pVirtualRoot
= NULL
;
1672 // and all the real items
1674 if ( !TreeView_DeleteAllItems(GetHwnd()) )
1676 wxLogLastError(wxT("TreeView_DeleteAllItems"));
1680 void wxTreeCtrl::DoExpand(const wxTreeItemId
& item
, int flag
)
1682 wxASSERT_MSG( flag
== TVE_COLLAPSE
||
1683 flag
== (TVE_COLLAPSE
| TVE_COLLAPSERESET
) ||
1684 flag
== TVE_EXPAND
||
1686 wxT("Unknown flag in wxTreeCtrl::DoExpand") );
1688 // A hidden root can be neither expanded nor collapsed.
1689 wxCHECK_RET( !IsHiddenRoot(item
),
1690 wxT("Can't expand/collapse hidden root node!") );
1692 // TreeView_Expand doesn't send TVN_ITEMEXPAND(ING) messages, so we must
1693 // emulate them. This behaviour has changed slightly with comctl32.dll
1694 // v 4.70 - now it does send them but only the first time. To maintain
1695 // compatible behaviour and also in order to not have surprises with the
1696 // future versions, don't rely on this and still do everything ourselves.
1697 // To avoid that the messages be sent twice when the item is expanded for
1698 // the first time we must clear TVIS_EXPANDEDONCE style manually.
1700 wxTreeViewItem
tvItem(item
, TVIF_STATE
, TVIS_EXPANDEDONCE
);
1704 if ( TreeView_Expand(GetHwnd(), HITEM(item
), flag
) != 0 )
1706 // note that the {EXPAND|COLLAPS}ING event is sent by TreeView_Expand()
1708 wxTreeEvent
event(gs_expandEvents
[IsExpanded(item
) ? IDX_EXPAND
1712 (void)HandleWindowEvent(event
);
1714 //else: change didn't took place, so do nothing at all
1717 void wxTreeCtrl::Expand(const wxTreeItemId
& item
)
1719 DoExpand(item
, TVE_EXPAND
);
1722 void wxTreeCtrl::Collapse(const wxTreeItemId
& item
)
1724 DoExpand(item
, TVE_COLLAPSE
);
1727 void wxTreeCtrl::CollapseAndReset(const wxTreeItemId
& item
)
1729 DoExpand(item
, TVE_COLLAPSE
| TVE_COLLAPSERESET
);
1732 void wxTreeCtrl::Toggle(const wxTreeItemId
& item
)
1734 DoExpand(item
, TVE_TOGGLE
);
1737 void wxTreeCtrl::Unselect()
1739 wxASSERT_MSG( !(m_windowStyle
& wxTR_MULTIPLE
),
1740 wxT("doesn't make sense, may be you want UnselectAll()?") );
1742 // just remove the selection
1743 SelectItem(wxTreeItemId());
1746 void wxTreeCtrl::UnselectAll()
1748 if ( m_windowStyle
& wxTR_MULTIPLE
)
1750 wxArrayTreeItemIds selections
;
1751 size_t count
= GetSelections(selections
);
1752 for ( size_t n
= 0; n
< count
; n
++ )
1754 ::UnselectItem(GetHwnd(), HITEM(selections
[n
]));
1757 m_htSelStart
.Unset();
1761 // just remove the selection
1766 void wxTreeCtrl::SelectItem(const wxTreeItemId
& item
, bool select
)
1768 wxCHECK_RET( !IsHiddenRoot(item
), _T("can't select hidden root item") );
1770 wxASSERT_MSG( select
|| HasFlag(wxTR_MULTIPLE
),
1771 _T("SelectItem(false) works only for multiselect") );
1773 wxTreeEvent
event(wxEVT_COMMAND_TREE_SEL_CHANGING
, this, item
);
1774 if ( !HandleWindowEvent(event
) || event
.IsAllowed() )
1776 if ( HasFlag(wxTR_MULTIPLE
) )
1778 if ( !::SelectItem(GetHwnd(), HITEM(item
), select
) )
1780 wxLogLastError(wxT("TreeView_SelectItem"));
1784 else // single selection
1786 // use TreeView_SelectItem() to deselect the previous selection
1787 if ( !TreeView_SelectItem(GetHwnd(), HITEM(item
)) )
1789 wxLogLastError(wxT("TreeView_SelectItem"));
1794 event
.SetEventType(wxEVT_COMMAND_TREE_SEL_CHANGED
);
1795 (void)HandleWindowEvent(event
);
1797 //else: program vetoed the change
1800 void wxTreeCtrl::EnsureVisible(const wxTreeItemId
& item
)
1802 wxCHECK_RET( !IsHiddenRoot(item
), _T("can't show hidden root item") );
1805 TreeView_EnsureVisible(GetHwnd(), HITEM(item
));
1808 void wxTreeCtrl::ScrollTo(const wxTreeItemId
& item
)
1810 if ( !TreeView_SelectSetFirstVisible(GetHwnd(), HITEM(item
)) )
1812 wxLogLastError(wxT("TreeView_SelectSetFirstVisible"));
1816 wxTextCtrl
*wxTreeCtrl::GetEditControl() const
1821 void wxTreeCtrl::DeleteTextCtrl()
1825 // the HWND corresponding to this control is deleted by the tree
1826 // control itself and we don't know when exactly this happens, so check
1827 // if the window still exists before calling UnsubclassWin()
1828 if ( !::IsWindow(GetHwndOf(m_textCtrl
)) )
1830 m_textCtrl
->SetHWND(0);
1833 m_textCtrl
->UnsubclassWin();
1834 m_textCtrl
->SetHWND(0);
1842 wxTextCtrl
*wxTreeCtrl::EditLabel(const wxTreeItemId
& item
,
1843 wxClassInfo
*textControlClass
)
1845 wxASSERT( textControlClass
->IsKindOf(CLASSINFO(wxTextCtrl
)) );
1850 m_textCtrl
= (wxTextCtrl
*)textControlClass
->CreateObject();
1851 HWND hWnd
= (HWND
) TreeView_EditLabel(GetHwnd(), HITEM(item
));
1853 // this is not an error - the TVN_BEGINLABELEDIT handler might have
1862 // textctrl is subclassed in MSWOnNotify
1866 // End label editing, optionally cancelling the edit
1867 void wxTreeCtrl::DoEndEditLabel(bool discardChanges
)
1869 TreeView_EndEditLabelNow(GetHwnd(), discardChanges
);
1874 wxTreeItemId
wxTreeCtrl::DoTreeHitTest(const wxPoint
& point
, int& flags
) const
1876 TV_HITTESTINFO hitTestInfo
;
1877 hitTestInfo
.pt
.x
= (int)point
.x
;
1878 hitTestInfo
.pt
.y
= (int)point
.y
;
1880 (void) TreeView_HitTest(GetHwnd(), &hitTestInfo
);
1885 #define TRANSLATE_FLAG(flag) if ( hitTestInfo.flags & TVHT_##flag ) \
1886 flags |= wxTREE_HITTEST_##flag
1888 TRANSLATE_FLAG(ABOVE
);
1889 TRANSLATE_FLAG(BELOW
);
1890 TRANSLATE_FLAG(NOWHERE
);
1891 TRANSLATE_FLAG(ONITEMBUTTON
);
1892 TRANSLATE_FLAG(ONITEMICON
);
1893 TRANSLATE_FLAG(ONITEMINDENT
);
1894 TRANSLATE_FLAG(ONITEMLABEL
);
1895 TRANSLATE_FLAG(ONITEMRIGHT
);
1896 TRANSLATE_FLAG(ONITEMSTATEICON
);
1897 TRANSLATE_FLAG(TOLEFT
);
1898 TRANSLATE_FLAG(TORIGHT
);
1900 #undef TRANSLATE_FLAG
1902 return wxTreeItemId(hitTestInfo
.hItem
);
1905 bool wxTreeCtrl::GetBoundingRect(const wxTreeItemId
& item
,
1907 bool textOnly
) const
1911 // Virtual root items have no bounding rectangle
1912 if ( IS_VIRTUAL_ROOT(item
) )
1917 if ( TreeView_GetItemRect(GetHwnd(), HITEM(item
),
1920 rect
= wxRect(wxPoint(rc
.left
, rc
.top
), wxPoint(rc
.right
, rc
.bottom
));
1926 // couldn't retrieve rect: for example, item isn't visible
1931 // ----------------------------------------------------------------------------
1933 // ----------------------------------------------------------------------------
1935 // this is just a tiny namespace which is friend to wxTreeCtrl and so can use
1936 // functions such as IsDataIndirect()
1937 class wxTreeSortHelper
1940 static int CALLBACK
Compare(LPARAM data1
, LPARAM data2
, LPARAM tree
);
1943 static wxTreeItemId
GetIdFromData(LPARAM lParam
)
1945 return ((wxTreeItemParam
*)lParam
)->GetItem();
1949 int CALLBACK
wxTreeSortHelper::Compare(LPARAM pItem1
,
1953 wxCHECK_MSG( pItem1
&& pItem2
, 0,
1954 wxT("sorting tree without data doesn't make sense") );
1956 wxTreeCtrl
*tree
= (wxTreeCtrl
*)htree
;
1958 return tree
->OnCompareItems(GetIdFromData(pItem1
),
1959 GetIdFromData(pItem2
));
1962 void wxTreeCtrl::SortChildren(const wxTreeItemId
& item
)
1964 wxCHECK_RET( item
.IsOk(), wxT("invalid tree item") );
1966 // rely on the fact that TreeView_SortChildren does the same thing as our
1967 // default behaviour, i.e. sorts items alphabetically and so call it
1968 // directly if we're not in derived class (much more efficient!)
1969 // RN: Note that if you find you're code doesn't sort as expected this
1970 // may be why as if you don't use the DECLARE_CLASS/IMPLEMENT_CLASS
1971 // combo for your derived wxTreeCtrl if will sort without
1973 if ( GetClassInfo() == CLASSINFO(wxTreeCtrl
) )
1975 TreeView_SortChildren(GetHwnd(), HITEM(item
), 0);
1980 tvSort
.hParent
= HITEM(item
);
1981 tvSort
.lpfnCompare
= wxTreeSortHelper::Compare
;
1982 tvSort
.lParam
= (LPARAM
)this;
1983 TreeView_SortChildrenCB(GetHwnd(), &tvSort
, 0 /* reserved */);
1987 // ----------------------------------------------------------------------------
1989 // ----------------------------------------------------------------------------
1991 bool wxTreeCtrl::MSWShouldPreProcessMessage(WXMSG
* msg
)
1993 if ( msg
->message
== WM_KEYDOWN
)
1995 // Only eat VK_RETURN if not being used by the application in
1996 // conjunction with modifiers
1997 if ( (msg
->wParam
== VK_RETURN
) && !wxIsAnyModifierDown() )
1999 // we need VK_RETURN to generate wxEVT_COMMAND_TREE_ITEM_ACTIVATED
2004 return wxTreeCtrlBase::MSWShouldPreProcessMessage(msg
);
2007 bool wxTreeCtrl::MSWCommand(WXUINT cmd
, WXWORD id_
)
2009 const int id
= (signed short)id_
;
2011 if ( cmd
== EN_UPDATE
)
2013 wxCommandEvent
event(wxEVT_COMMAND_TEXT_UPDATED
, id
);
2014 event
.SetEventObject( this );
2015 ProcessCommand(event
);
2017 else if ( cmd
== EN_KILLFOCUS
)
2019 wxCommandEvent
event(wxEVT_KILL_FOCUS
, id
);
2020 event
.SetEventObject( this );
2021 ProcessCommand(event
);
2029 // command processed
2033 // we hook into WndProc to process WM_MOUSEMOVE/WM_BUTTONUP messages - as we
2034 // only do it during dragging, minimize wxWin overhead (this is important for
2035 // WM_MOUSEMOVE as they're a lot of them) by catching Windows messages directly
2036 // instead of passing by wxWin events
2037 WXLRESULT
wxTreeCtrl::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
2039 bool processed
= false;
2041 bool isMultiple
= HasFlag(wxTR_MULTIPLE
);
2043 // This message is sent after a right-click, or when the "menu" key is pressed
2044 if ( nMsg
== WM_CONTEXTMENU
)
2046 int x
= GET_X_LPARAM(lParam
),
2047 y
= GET_Y_LPARAM(lParam
);
2049 // the item for which the menu should be shown
2052 // the position where the menu should be shown in client coordinates
2053 // (so that it can be passed directly to PopupMenu())
2056 if ( x
== -1 || y
== -1 )
2058 // this means that the event was generated from keyboard (e.g. with
2059 // Shift-F10 or special Windows menu key)
2061 // use the Explorer standard of putting the menu at the left edge
2062 // of the text, in the vertical middle of the text
2063 item
= wxTreeItemId(TreeView_GetSelection(GetHwnd()));
2066 // Use the bounding rectangle of only the text part
2068 GetBoundingRect(item
, rect
, true);
2069 pt
= wxPoint(rect
.GetX(), rect
.GetY() + rect
.GetHeight() / 2);
2072 else // event from mouse, use mouse position
2074 pt
= ScreenToClient(wxPoint(x
, y
));
2076 TV_HITTESTINFO tvhti
;
2079 if ( TreeView_HitTest(GetHwnd(), &tvhti
) )
2080 item
= wxTreeItemId(tvhti
.hItem
);
2084 wxTreeEvent
event(wxEVT_COMMAND_TREE_ITEM_MENU
, this, item
);
2086 event
.m_pointDrag
= pt
;
2088 if ( HandleWindowEvent(event
) )
2090 //else: continue with generating wxEVT_CONTEXT_MENU in base class code
2092 else if ( (nMsg
>= WM_MOUSEFIRST
) && (nMsg
<= WM_MOUSELAST
) )
2094 // we only process mouse messages here and these parameters have the
2095 // same meaning for all of them
2096 int x
= GET_X_LPARAM(lParam
),
2097 y
= GET_Y_LPARAM(lParam
);
2099 TV_HITTESTINFO tvht
;
2103 HTREEITEM htItem
= TreeView_HitTest(GetHwnd(), &tvht
);
2107 case WM_LBUTTONDOWN
:
2108 if ( htItem
&& isMultiple
&& (tvht
.flags
& TVHT_ONITEM
) != 0 )
2110 m_htClickedItem
= (WXHTREEITEM
) htItem
;
2111 m_ptClick
= wxPoint(x
, y
);
2113 if ( wParam
& MK_CONTROL
)
2117 // toggle selected state
2118 ToggleItemSelection(htItem
);
2120 ::SetFocus(GetHwnd(), htItem
);
2122 // reset on any click without Shift
2123 m_htSelStart
.Unset();
2127 else if ( wParam
& MK_SHIFT
)
2129 // this selects all items between the starting one and
2132 if ( !m_htSelStart
)
2134 // take the focused item
2135 m_htSelStart
= TreeView_GetSelection(GetHwnd());
2139 SelectRange(GetHwnd(), HITEM(m_htSelStart
), htItem
,
2140 !(wParam
& MK_CONTROL
));
2142 ::SelectItem(GetHwnd(), htItem
);
2144 ::SetFocus(GetHwnd(), htItem
);
2148 else // normal click
2150 // avoid doing anything if we click on the only
2151 // currently selected item
2155 wxArrayTreeItemIds selections
;
2156 size_t count
= GetSelections(selections
);
2159 HITEM(selections
[0]) != htItem
)
2161 // clear the previously selected items, if the
2162 // user clicked outside of the present selection.
2163 // otherwise, perform the deselection on mouse-up.
2164 // this allows multiple drag and drop to work.
2166 if (!IsItemSelected(GetHwnd(), htItem
))
2170 // prevent the click from starting in-place editing
2171 // which should only happen if we click on the
2172 // already selected item (and nothing else is
2175 TreeView_SelectItem(GetHwnd(), 0);
2176 ::SelectItem(GetHwnd(), htItem
);
2178 ::SetFocus(GetHwnd(), htItem
);
2181 else // click on a single selected item
2183 // don't interfere with the default processing in
2184 // WM_MOUSEMOVE handler below as the default window
2185 // proc will start the drag itself if we let have
2187 m_htClickedItem
.Unset();
2190 // reset on any click without Shift
2191 m_htSelStart
.Unset();
2196 case WM_RBUTTONDOWN
:
2197 // default handler removes the highlight from the currently
2198 // focused item when right mouse button is pressed on another
2199 // one but keeps the remaining items highlighted, which is
2200 // confusing, so override this default behaviour for tree with
2201 // multiple selections
2204 if ( !IsItemSelected(GetHwnd(), htItem
) )
2208 ::SetFocus(GetHwnd(), htItem
);
2211 // fire EVT_RIGHT_DOWN
2212 HandleMouseEvent(nMsg
, x
, y
, wParam
);
2216 nmhdr
.hwndFrom
= GetHwnd();
2217 nmhdr
.idFrom
= ::GetWindowLong(GetHwnd(), GWL_ID
);
2218 nmhdr
.code
= NM_RCLICK
;
2219 ::SendMessage(::GetParent(GetHwnd()), WM_NOTIFY
,
2220 nmhdr
.idFrom
, (LPARAM
)&nmhdr
);
2222 // prevent tree control default processing, as we've
2223 // already done everything
2230 if ( m_htClickedItem
)
2232 int cx
= abs(m_ptClick
.x
- x
);
2233 int cy
= abs(m_ptClick
.y
- y
);
2235 if ( cx
> ::GetSystemMetrics(SM_CXDRAG
) ||
2236 cy
> ::GetSystemMetrics(SM_CYDRAG
) )
2241 tv
.hdr
.hwndFrom
= GetHwnd();
2242 tv
.hdr
.idFrom
= ::GetWindowLong(GetHwnd(), GWL_ID
);
2243 tv
.hdr
.code
= TVN_BEGINDRAG
;
2245 tv
.itemNew
.hItem
= HITEM(m_htClickedItem
);
2249 wxZeroMemory(tviAux
);
2251 tviAux
.hItem
= HITEM(m_htClickedItem
);
2252 tviAux
.mask
= TVIF_STATE
| TVIF_PARAM
;
2253 tviAux
.stateMask
= 0xffffffff;
2254 TreeView_GetItem(GetHwnd(), &tviAux
);
2256 tv
.itemNew
.state
= tviAux
.state
;
2257 tv
.itemNew
.lParam
= tviAux
.lParam
;
2262 // do it before SendMessage() call below to avoid
2263 // reentrancies here if there is another WM_MOUSEMOVE
2264 // in the queue already
2265 m_htClickedItem
.Unset();
2267 ::SendMessage(GetHwndOf(GetParent()), WM_NOTIFY
,
2268 tv
.hdr
.idFrom
, (LPARAM
)&tv
);
2270 // don't pass it to the default window proc, it would
2271 // start dragging again
2275 #endif // __WXWINCE__
2280 m_dragImage
->Move(wxPoint(x
, y
));
2283 // highlight the item as target (hiding drag image is
2284 // necessary - otherwise the display will be corrupted)
2285 m_dragImage
->Hide();
2286 TreeView_SelectDropTarget(GetHwnd(), htItem
);
2287 m_dragImage
->Show();
2290 #endif // wxUSE_DRAGIMAGE
2295 // facilitates multiple drag-and-drop
2296 if (htItem
&& isMultiple
)
2298 wxArrayTreeItemIds selections
;
2299 size_t count
= GetSelections(selections
);
2302 !(wParam
& MK_CONTROL
) &&
2303 !(wParam
& MK_SHIFT
))
2306 TreeView_SelectItem(GetHwnd(), htItem
);
2307 ::SelectItem(GetHwnd(), htItem
);
2308 ::SetFocus(GetHwnd(), htItem
);
2310 m_htClickedItem
.Unset();
2319 m_dragImage
->EndDrag();
2323 // generate the drag end event
2324 wxTreeEvent
event(wxEVT_COMMAND_TREE_END_DRAG
, this, htItem
);
2325 event
.m_pointDrag
= wxPoint(x
, y
);
2327 (void)HandleWindowEvent(event
);
2329 // if we don't do it, the tree seems to think that 2 items
2330 // are selected simultaneously which is quite weird
2331 TreeView_SelectDropTarget(GetHwnd(), 0);
2333 #endif // wxUSE_DRAGIMAGE
2337 else if ( (nMsg
== WM_SETFOCUS
|| nMsg
== WM_KILLFOCUS
) && isMultiple
)
2339 // the tree control greys out the selected item when it loses focus and
2340 // paints it as selected again when it regains it, but it won't do it
2341 // for the other items itself - help it
2342 wxArrayTreeItemIds selections
;
2343 size_t count
= GetSelections(selections
);
2345 for ( size_t n
= 0; n
< count
; n
++ )
2347 // TreeView_GetItemRect() will return false if item is not visible,
2348 // which may happen perfectly well
2349 if ( TreeView_GetItemRect(GetHwnd(), HITEM(selections
[n
]),
2352 ::InvalidateRect(GetHwnd(), &rect
, FALSE
);
2356 else if ( nMsg
== WM_KEYDOWN
&& isMultiple
)
2358 bool bCtrl
= wxIsCtrlDown(),
2359 bShift
= wxIsShiftDown();
2361 HTREEITEM htSel
= (HTREEITEM
)TreeView_GetSelection(GetHwnd());
2367 ToggleItemSelection(htSel
);
2373 ::SelectItem(GetHwnd(), htSel
);
2381 if ( !bCtrl
&& !bShift
)
2383 // no modifiers, just clear selection and then let the default
2384 // processing to take place
2389 (void)wxControl::MSWWindowProc(nMsg
, wParam
, lParam
);
2391 HTREEITEM htNext
= (HTREEITEM
)
2392 TreeView_GetNextItem
2396 wParam
== VK_UP
? TVGN_PREVIOUSVISIBLE
2402 // at the top/bottom
2408 if ( !m_htSelStart
)
2409 m_htSelStart
= htSel
;
2411 SelectRange(GetHwnd(), HITEM(m_htSelStart
), htNext
);
2415 // without changing selection
2416 ::SetFocus(GetHwnd(), htNext
);
2427 // TODO: handle Shift/Ctrl with these keys
2428 if ( !bCtrl
&& !bShift
)
2432 m_htSelStart
.Unset();
2436 else if ( nMsg
== WM_COMMAND
)
2438 // if we receive a EN_KILLFOCUS command from the in-place edit control
2439 // used for label editing, make sure to end editing
2442 UnpackCommand(wParam
, lParam
, &id
, &hwnd
, &cmd
);
2444 if ( cmd
== EN_KILLFOCUS
)
2446 if ( m_textCtrl
&& m_textCtrl
->GetHandle() == hwnd
)
2456 rc
= wxControl::MSWWindowProc(nMsg
, wParam
, lParam
);
2462 wxTreeCtrl::MSWDefWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
2464 if ( nMsg
== WM_CHAR
)
2466 // don't let the control process Space and Return keys because it
2467 // doesn't do anything useful with them anyhow but always beeps
2468 // annoyingly when it receives them and there is no way to turn it off
2469 // simply if you just process TREEITEM_ACTIVATED event to which Space
2470 // and Enter presses are mapped in your code
2471 if ( wParam
== VK_SPACE
|| wParam
== VK_RETURN
)
2475 else if ( nMsg
== WM_KEYDOWN
)
2477 if ( wParam
== VK_ESCAPE
)
2481 m_dragImage
->EndDrag();
2485 // if we don't do it, the tree seems to think that 2 items
2486 // are selected simultaneously which is quite weird
2487 TreeView_SelectDropTarget(GetHwnd(), 0);
2491 #endif // wxUSE_DRAGIMAGE
2493 return wxControl::MSWDefWindowProc(nMsg
, wParam
, lParam
);
2496 // process WM_NOTIFY Windows message
2497 bool wxTreeCtrl::MSWOnNotify(int idCtrl
, WXLPARAM lParam
, WXLPARAM
*result
)
2499 wxTreeEvent
event(wxEVT_NULL
, this);
2500 wxEventType eventType
= wxEVT_NULL
;
2501 NMHDR
*hdr
= (NMHDR
*)lParam
;
2503 switch ( hdr
->code
)
2506 eventType
= wxEVT_COMMAND_TREE_BEGIN_DRAG
;
2509 case TVN_BEGINRDRAG
:
2511 if ( eventType
== wxEVT_NULL
)
2512 eventType
= wxEVT_COMMAND_TREE_BEGIN_RDRAG
;
2513 //else: left drag, already set above
2515 NM_TREEVIEW
*tv
= (NM_TREEVIEW
*)lParam
;
2517 event
.m_item
= tv
->itemNew
.hItem
;
2518 event
.m_pointDrag
= wxPoint(tv
->ptDrag
.x
, tv
->ptDrag
.y
);
2520 // don't allow dragging by default: the user code must
2521 // explicitly say that it wants to allow it to avoid breaking
2527 case TVN_BEGINLABELEDIT
:
2529 eventType
= wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT
;
2530 TV_DISPINFO
*info
= (TV_DISPINFO
*)lParam
;
2532 // although the user event handler may still veto it, it is
2533 // important to set it now so that calls to SetItemText() from
2534 // the event handler would change the text controls contents
2536 event
.m_item
= info
->item
.hItem
;
2537 event
.m_label
= info
->item
.pszText
;
2538 event
.m_editCancelled
= false;
2542 case TVN_DELETEITEM
:
2544 eventType
= wxEVT_COMMAND_TREE_DELETE_ITEM
;
2545 NM_TREEVIEW
*tv
= (NM_TREEVIEW
*)lParam
;
2547 event
.m_item
= tv
->itemOld
.hItem
;
2551 wxMapTreeAttr::iterator it
= m_attrs
.find(tv
->itemOld
.hItem
);
2552 if ( it
!= m_attrs
.end() )
2561 case TVN_ENDLABELEDIT
:
2563 eventType
= wxEVT_COMMAND_TREE_END_LABEL_EDIT
;
2564 TV_DISPINFO
*info
= (TV_DISPINFO
*)lParam
;
2566 event
.m_item
= info
->item
.hItem
;
2567 event
.m_label
= info
->item
.pszText
;
2568 event
.m_editCancelled
= info
->item
.pszText
== NULL
;
2573 // These *must* not be removed or TVN_GETINFOTIP will
2574 // not be processed each time the mouse is moved
2575 // and the tooltip will only ever update once.
2584 #ifdef TVN_GETINFOTIP
2585 case TVN_GETINFOTIP
:
2587 eventType
= wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP
;
2588 NMTVGETINFOTIP
*info
= (NMTVGETINFOTIP
*)lParam
;
2590 // Which item are we trying to get a tooltip for?
2591 event
.m_item
= info
->hItem
;
2595 #endif // TVN_GETINFOTIP
2596 #endif // !__WXWINCE__
2598 case TVN_GETDISPINFO
:
2599 eventType
= wxEVT_COMMAND_TREE_GET_INFO
;
2602 case TVN_SETDISPINFO
:
2604 if ( eventType
== wxEVT_NULL
)
2605 eventType
= wxEVT_COMMAND_TREE_SET_INFO
;
2606 //else: get, already set above
2608 TV_DISPINFO
*info
= (TV_DISPINFO
*)lParam
;
2610 event
.m_item
= info
->item
.hItem
;
2614 case TVN_ITEMEXPANDING
:
2615 case TVN_ITEMEXPANDED
:
2617 NM_TREEVIEW
*tv
= (NM_TREEVIEW
*)lParam
;
2620 switch ( tv
->action
)
2623 wxLogDebug(wxT("unexpected code %d in TVN_ITEMEXPAND message"), tv
->action
);
2631 what
= IDX_COLLAPSE
;
2635 int how
= hdr
->code
== TVN_ITEMEXPANDING
? IDX_DOING
2638 eventType
= gs_expandEvents
[what
][how
];
2640 event
.m_item
= tv
->itemNew
.hItem
;
2646 eventType
= wxEVT_COMMAND_TREE_KEY_DOWN
;
2647 TV_KEYDOWN
*info
= (TV_KEYDOWN
*)lParam
;
2649 // fabricate the lParam and wParam parameters sufficiently
2650 // similar to the ones from a "real" WM_KEYDOWN so that
2651 // CreateKeyEvent() works correctly
2652 WXLPARAM lParam
= (wxIsAltDown() ? KF_ALTDOWN
: 0) << 16;
2654 WXWPARAM wParam
= info
->wVKey
;
2656 int keyCode
= wxCharCodeMSWToWX(wParam
);
2659 // wxCharCodeMSWToWX() returns 0 to indicate that this is a
2664 event
.m_evtKey
= CreateKeyEvent(wxEVT_KEY_DOWN
,
2669 // a separate event for Space/Return
2670 if ( !wxIsAnyModifierDown() &&
2671 ((info
->wVKey
== VK_SPACE
) || (info
->wVKey
== VK_RETURN
)) )
2674 if ( !HasFlag(wxTR_MULTIPLE
) )
2675 item
= GetSelection();
2677 wxTreeEvent
event2(wxEVT_COMMAND_TREE_ITEM_ACTIVATED
,
2679 (void)HandleWindowEvent(event2
);
2685 // Vista's tree control has introduced some problems with our
2686 // multi-selection tree. When TreeView_SelectItem() is called,
2687 // the wrong items are deselected.
2689 // Fortunately, Vista provides a new notification, TVN_ITEMCHANGING
2690 // that can be used to regulate this incorrect behavior. The
2691 // following messages will allow only the unlocked item's selection
2694 case TVN_ITEMCHANGINGA
:
2695 case TVN_ITEMCHANGINGW
:
2697 // we only need to handles these in multi-select trees
2698 if ( HasFlag(wxTR_MULTIPLE
) )
2700 // get info about the item about to be changed
2701 NMTVITEMCHANGE
* info
= (NMTVITEMCHANGE
*)lParam
;
2702 if (TreeItemUnlocker::IsLocked(info
->hItem
))
2704 // item's state is locked, don't allow the change
2705 // returning 1 will disallow the change
2711 // allow the state change
2715 // NB: MSLU is broken and sends TVN_SELCHANGEDA instead of
2716 // TVN_SELCHANGEDW in Unicode mode under Win98. Therefore
2717 // we have to handle both messages:
2718 case TVN_SELCHANGEDA
:
2719 case TVN_SELCHANGEDW
:
2720 eventType
= wxEVT_COMMAND_TREE_SEL_CHANGED
;
2723 case TVN_SELCHANGINGA
:
2724 case TVN_SELCHANGINGW
:
2726 if ( eventType
== wxEVT_NULL
)
2727 eventType
= wxEVT_COMMAND_TREE_SEL_CHANGING
;
2728 //else: already set above
2730 if (hdr
->code
== TVN_SELCHANGINGW
||
2731 hdr
->code
== TVN_SELCHANGEDW
)
2733 NM_TREEVIEWW
*tv
= (NM_TREEVIEWW
*)lParam
;
2734 event
.m_item
= tv
->itemNew
.hItem
;
2735 event
.m_itemOld
= tv
->itemOld
.hItem
;
2739 NM_TREEVIEWA
*tv
= (NM_TREEVIEWA
*)lParam
;
2740 event
.m_item
= tv
->itemNew
.hItem
;
2741 event
.m_itemOld
= tv
->itemOld
.hItem
;
2745 // we receive this message from WM_LBUTTONDOWN handler inside
2746 // comctl32.dll and so before the click is passed to
2747 // DefWindowProc() which sets the focus to the window which was
2748 // clicked and this can lead to unexpected event sequences: for
2749 // example, we may get a "selection change" event from the tree
2750 // before getting a "kill focus" event for the text control which
2751 // had the focus previously, thus breaking user code doing input
2754 // to avoid such surprises, we force the generation of focus events
2755 // now, before we generate the selection change ones
2759 // instead of explicitly checking for _WIN32_IE, check if the
2760 // required symbols are available in the headers
2761 #if defined(CDDS_PREPAINT) && !wxUSE_COMCTL32_SAFELY
2764 LPNMTVCUSTOMDRAW lptvcd
= (LPNMTVCUSTOMDRAW
)lParam
;
2765 NMCUSTOMDRAW
& nmcd
= lptvcd
->nmcd
;
2766 switch ( nmcd
.dwDrawStage
)
2769 // if we've got any items with non standard attributes,
2770 // notify us before painting each item
2771 *result
= m_hasAnyAttr
? CDRF_NOTIFYITEMDRAW
2775 case CDDS_ITEMPREPAINT
:
2777 wxMapTreeAttr::iterator
2778 it
= m_attrs
.find((void *)nmcd
.dwItemSpec
);
2780 if ( it
== m_attrs
.end() )
2782 // nothing to do for this item
2783 *result
= CDRF_DODEFAULT
;
2787 wxTreeItemAttr
* const attr
= it
->second
;
2789 wxTreeViewItem
tvItem((void *)nmcd
.dwItemSpec
,
2790 TVIF_STATE
, TVIS_DROPHILITED
);
2792 const UINT tvItemState
= tvItem
.state
;
2794 // selection colours should override ours,
2795 // otherwise it is too confusing to the user
2796 if ( !(nmcd
.uItemState
& CDIS_SELECTED
) &&
2797 !(tvItemState
& TVIS_DROPHILITED
) )
2800 if ( attr
->HasBackgroundColour() )
2802 colBack
= attr
->GetBackgroundColour();
2803 lptvcd
->clrTextBk
= wxColourToRGB(colBack
);
2807 // but we still want to keep the special foreground
2808 // colour when we don't have focus (we can't keep
2809 // it when we do, it would usually be unreadable on
2810 // the almost inverted bg colour...)
2811 if ( ( !(nmcd
.uItemState
& CDIS_SELECTED
) ||
2812 FindFocus() != this ) &&
2813 !(tvItemState
& TVIS_DROPHILITED
) )
2816 if ( attr
->HasTextColour() )
2818 colText
= attr
->GetTextColour();
2819 lptvcd
->clrText
= wxColourToRGB(colText
);
2823 if ( attr
->HasFont() )
2825 HFONT hFont
= GetHfontOf(attr
->GetFont());
2827 ::SelectObject(nmcd
.hdc
, hFont
);
2829 *result
= CDRF_NEWFONT
;
2831 else // no specific font
2833 *result
= CDRF_DODEFAULT
;
2839 *result
= CDRF_DODEFAULT
;
2843 // we always process it
2845 #endif // have owner drawn support in headers
2849 DWORD pos
= GetMessagePos();
2851 point
.x
= LOWORD(pos
);
2852 point
.y
= HIWORD(pos
);
2853 ::MapWindowPoints(HWND_DESKTOP
, GetHwnd(), &point
, 1);
2855 wxTreeItemId item
= HitTest(wxPoint(point
.x
, point
.y
), flags
);
2856 if (flags
& wxTREE_HITTEST_ONITEMSTATEICON
)
2858 event
.m_item
= item
;
2859 eventType
= wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK
;
2867 TV_HITTESTINFO tvhti
;
2868 ::GetCursorPos(&tvhti
.pt
);
2869 ::ScreenToClient(GetHwnd(), &tvhti
.pt
);
2870 if ( TreeView_HitTest(GetHwnd(), &tvhti
) )
2872 if ( tvhti
.flags
& TVHT_ONITEM
)
2874 event
.m_item
= tvhti
.hItem
;
2875 eventType
= (int)hdr
->code
== NM_DBLCLK
2876 ? wxEVT_COMMAND_TREE_ITEM_ACTIVATED
2877 : wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK
;
2879 event
.m_pointDrag
.x
= tvhti
.pt
.x
;
2880 event
.m_pointDrag
.y
= tvhti
.pt
.y
;
2889 return wxControl::MSWOnNotify(idCtrl
, lParam
, result
);
2892 event
.SetEventType(eventType
);
2894 if ( event
.m_item
.IsOk() )
2895 event
.SetClientObject(GetItemData(event
.m_item
));
2897 bool processed
= HandleWindowEvent(event
);
2900 switch ( hdr
->code
)
2903 // we translate NM_DBLCLK into ACTIVATED event, so don't interpret
2904 // the return code of this event handler as the return value for
2905 // NM_DBLCLK - otherwise, double clicking the item to toggle its
2906 // expanded status would never work
2911 // prevent tree control from sending WM_CONTEXTMENU to our parent
2912 // (which it does if NM_RCLICK is not handled) because we want to
2913 // send it to the control itself
2917 ::SendMessage(GetHwnd(), WM_CONTEXTMENU
,
2918 (WPARAM
)GetHwnd(), ::GetMessagePos());
2922 case TVN_BEGINRDRAG
:
2924 if ( event
.IsAllowed() )
2926 // normally this is impossible because the m_dragImage is
2927 // deleted once the drag operation is over
2928 wxASSERT_MSG( !m_dragImage
, _T("starting to drag once again?") );
2930 m_dragImage
= new wxDragImage(*this, event
.m_item
);
2931 m_dragImage
->BeginDrag(wxPoint(0,0), this);
2932 m_dragImage
->Show();
2934 #endif // wxUSE_DRAGIMAGE
2937 case TVN_DELETEITEM
:
2939 // NB: we might process this message using wxWidgets event
2940 // tables, but due to overhead of wxWin event system we
2941 // prefer to do it here ourself (otherwise deleting a tree
2942 // with many items is just too slow)
2943 NM_TREEVIEW
*tv
= (NM_TREEVIEW
*)lParam
;
2945 wxTreeItemParam
*param
=
2946 (wxTreeItemParam
*)tv
->itemOld
.lParam
;
2949 processed
= true; // Make sure we don't get called twice
2953 case TVN_BEGINLABELEDIT
:
2954 // return true to cancel label editing
2955 *result
= !event
.IsAllowed();
2957 // set ES_WANTRETURN ( like we do in BeginLabelEdit )
2958 if ( event
.IsAllowed() )
2960 HWND hText
= TreeView_GetEditControl(GetHwnd());
2963 // MBN: if m_textCtrl already has an HWND, it is a stale
2964 // pointer from a previous edit (because the user
2965 // didn't modify the label before dismissing the control,
2966 // and TVN_ENDLABELEDIT was not sent), so delete it
2967 if ( m_textCtrl
&& m_textCtrl
->GetHWND() )
2970 m_textCtrl
= new wxTextCtrl();
2971 m_textCtrl
->SetParent(this);
2972 m_textCtrl
->SetHWND((WXHWND
)hText
);
2973 m_textCtrl
->SubclassWin((WXHWND
)hText
);
2975 // set wxTE_PROCESS_ENTER style for the text control to
2976 // force it to process the Enter presses itself, otherwise
2977 // they could be stolen from it by the dialog
2979 m_textCtrl
->SetWindowStyle(m_textCtrl
->GetWindowStyle()
2980 | wxTE_PROCESS_ENTER
);
2983 else // we had set m_idEdited before
2989 case TVN_ENDLABELEDIT
:
2990 // return true to set the label to the new string: note that we
2991 // also must pretend that we did process the message or it is going
2992 // to be passed to DefWindowProc() which will happily return false
2993 // cancelling the label change
2994 *result
= event
.IsAllowed();
2997 // ensure that we don't have the text ctrl which is going to be
3003 #ifdef TVN_GETINFOTIP
3004 case TVN_GETINFOTIP
:
3006 // If the user permitted a tooltip change, change it
3007 if (event
.IsAllowed())
3009 SetToolTip(event
.m_label
);
3016 case TVN_SELCHANGING
:
3017 case TVN_ITEMEXPANDING
:
3018 // return true to prevent the action from happening
3019 *result
= !event
.IsAllowed();
3022 case TVN_ITEMEXPANDED
:
3024 NM_TREEVIEW
*tv
= (NM_TREEVIEW
*)lParam
;
3025 const wxTreeItemId
id(tv
->itemNew
.hItem
);
3027 if ( tv
->action
== TVE_COLLAPSE
)
3029 if ( wxApp::GetComCtl32Version() >= 600 )
3031 // for some reason the item selection rectangle depends
3032 // on whether it is expanded or collapsed (at least
3033 // with comctl32.dll v6): it is wider (by 3 pixels) in
3034 // the expanded state, so when the item collapses and
3035 // then is deselected the rightmost 3 pixels of the
3036 // previously drawn selection are left on the screen
3038 // it's not clear if it's a bug in comctl32.dll or in
3039 // our code (because it does not happen in Explorer but
3040 // OTOH we don't do anything which could result in this
3041 // AFAICS) but we do need to work around it to avoid
3048 // the item is also not refreshed properly after expansion when
3049 // it has an image depending on the expanded/collapsed state:
3050 // again, it's not clear if the bug is in comctl32.dll or our
3052 int image
= GetItemImage(id
, wxTreeItemIcon_Expanded
);
3061 case TVN_GETDISPINFO
:
3062 // NB: so far the user can't set the image himself anyhow, so do it
3063 // anyway - but this may change later
3064 //if ( /* !processed && */ )
3066 wxTreeItemId item
= event
.m_item
;
3067 TV_DISPINFO
*info
= (TV_DISPINFO
*)lParam
;
3069 const wxTreeItemParam
* const param
= GetItemParam(item
);
3073 if ( info
->item
.mask
& TVIF_IMAGE
)
3078 IsExpanded(item
) ? wxTreeItemIcon_Expanded
3079 : wxTreeItemIcon_Normal
3082 if ( info
->item
.mask
& TVIF_SELECTEDIMAGE
)
3084 info
->item
.iSelectedImage
=
3087 IsExpanded(item
) ? wxTreeItemIcon_SelectedExpanded
3088 : wxTreeItemIcon_Selected
3095 // for the other messages the return value is ignored and there is
3096 // nothing special to do
3101 // ----------------------------------------------------------------------------
3103 // ----------------------------------------------------------------------------
3105 // why do they define INDEXTOSTATEIMAGEMASK but not the inverse?
3106 #define STATEIMAGEMASKTOINDEX(state) (((state) & TVIS_STATEIMAGEMASK) >> 12)
3108 void wxTreeCtrl::SetState(const wxTreeItemId
& node
, int state
)
3111 tvi
.hItem
= (HTREEITEM
)node
.m_pItem
;
3112 tvi
.mask
= TVIF_STATE
;
3113 tvi
.stateMask
= TVIS_STATEIMAGEMASK
;
3115 // Select the specified state, or -1 == cycle to the next one.
3118 TreeView_GetItem(GetHwnd(), &tvi
);
3120 state
= STATEIMAGEMASKTOINDEX(tvi
.state
) + 1;
3121 if ( state
== m_imageListState
->GetImageCount() )
3125 wxCHECK_RET( state
< m_imageListState
->GetImageCount(),
3126 _T("wxTreeCtrl::SetState(): item index out of bounds") );
3128 tvi
.state
= INDEXTOSTATEIMAGEMASK(state
);
3130 TreeView_SetItem(GetHwnd(), &tvi
);
3133 int wxTreeCtrl::GetState(const wxTreeItemId
& node
)
3136 tvi
.hItem
= (HTREEITEM
)node
.m_pItem
;
3137 tvi
.mask
= TVIF_STATE
;
3138 tvi
.stateMask
= TVIS_STATEIMAGEMASK
;
3139 TreeView_GetItem(GetHwnd(), &tvi
);
3141 return STATEIMAGEMASKTOINDEX(tvi
.state
);
3144 #endif // wxUSE_TREECTRL