implement wxTreeCtrl::ItemHasChildren() properly for virtual root item; added unit...
[wxWidgets.git] / src / msw / treectrl.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/treectrl.cpp
3 // Purpose: wxTreeCtrl
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin to be less MSW-specific on 10.10.98
6 // Created: 1997
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_TREECTRL
28
29 #include "wx/treectrl.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
33 #include "wx/msw/missing.h"
34 #include "wx/dynarray.h"
35 #include "wx/log.h"
36 #include "wx/app.h"
37 #include "wx/settings.h"
38 #endif
39
40 #include "wx/msw/private.h"
41
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
45
46 #include "wx/imaglist.h"
47 #include "wx/msw/dragimag.h"
48
49 // macros to hide the cast ugliness
50 // --------------------------------
51
52 // get HTREEITEM from wxTreeItemId
53 #define HITEM(item) ((HTREEITEM)(((item).m_pItem)))
54
55
56 // older SDKs are missing these
57 #ifndef TVN_ITEMCHANGINGA
58
59 #define TVN_ITEMCHANGINGA (TVN_FIRST-16)
60 #define TVN_ITEMCHANGINGW (TVN_FIRST-17)
61
62 typedef struct tagNMTVITEMCHANGE
63 {
64 NMHDR hdr;
65 UINT uChanged;
66 HTREEITEM hItem;
67 UINT uStateNew;
68 UINT uStateOld;
69 LPARAM lParam;
70 } NMTVITEMCHANGE;
71
72 #endif
73
74
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.
78
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.
84
85 class TreeItemUnlocker
86 {
87 public:
88 // unlock a single item
89 TreeItemUnlocker(HTREEITEM item) { ms_unlockedItem = item; }
90
91 // unlock all items, don't use unless absolutely necessary
92 TreeItemUnlocker() { ms_unlockedItem = (HTREEITEM)-1; }
93
94 // lock everything back
95 ~TreeItemUnlocker() { ms_unlockedItem = NULL; }
96
97
98 // check if the item state is currently locked
99 static bool IsLocked(HTREEITEM item)
100 { return ms_unlockedItem != (HTREEITEM)-1 && item != ms_unlockedItem; }
101
102 private:
103 static HTREEITEM ms_unlockedItem;
104 };
105
106 HTREEITEM TreeItemUnlocker::ms_unlockedItem = NULL;
107
108 // ----------------------------------------------------------------------------
109 // private functions
110 // ----------------------------------------------------------------------------
111
112 // wrappers for TreeView_GetItem/TreeView_SetItem
113 static bool IsItemSelected(HWND hwndTV, HTREEITEM hItem)
114 {
115
116 TV_ITEM tvi;
117 tvi.mask = TVIF_STATE | TVIF_HANDLE;
118 tvi.stateMask = TVIS_SELECTED;
119 tvi.hItem = hItem;
120
121 TreeItemUnlocker unlocker(hItem);
122
123 if ( !TreeView_GetItem(hwndTV, &tvi) )
124 {
125 wxLogLastError(wxT("TreeView_GetItem"));
126 }
127
128 return (tvi.state & TVIS_SELECTED) != 0;
129 }
130
131 static bool SelectItem(HWND hwndTV, HTREEITEM hItem, bool select = true)
132 {
133 TV_ITEM tvi;
134 tvi.mask = TVIF_STATE | TVIF_HANDLE;
135 tvi.stateMask = TVIS_SELECTED;
136 tvi.state = select ? TVIS_SELECTED : 0;
137 tvi.hItem = hItem;
138
139 TreeItemUnlocker unlocker(hItem);
140
141 if ( TreeView_SetItem(hwndTV, &tvi) == -1 )
142 {
143 wxLogLastError(wxT("TreeView_SetItem"));
144 return false;
145 }
146
147 return true;
148 }
149
150 static inline void UnselectItem(HWND hwndTV, HTREEITEM htItem)
151 {
152 SelectItem(hwndTV, htItem, false);
153 }
154
155 // helper function which selects all items in a range and, optionally,
156 // unselects all others
157 static void SelectRange(HWND hwndTV,
158 HTREEITEM htFirst,
159 HTREEITEM htLast,
160 bool unselectOthers = true)
161 {
162 // find the first (or last) item and select it
163 bool cont = true;
164 HTREEITEM htItem = (HTREEITEM)TreeView_GetRoot(hwndTV);
165 while ( htItem && cont )
166 {
167 if ( (htItem == htFirst) || (htItem == htLast) )
168 {
169 if ( !IsItemSelected(hwndTV, htItem) )
170 {
171 SelectItem(hwndTV, htItem);
172 }
173
174 cont = false;
175 }
176 else
177 {
178 if ( unselectOthers && IsItemSelected(hwndTV, htItem) )
179 {
180 UnselectItem(hwndTV, htItem);
181 }
182 }
183
184 htItem = (HTREEITEM)TreeView_GetNextVisible(hwndTV, htItem);
185 }
186
187 // select the items in range
188 cont = htFirst != htLast;
189 while ( htItem && cont )
190 {
191 if ( !IsItemSelected(hwndTV, htItem) )
192 {
193 SelectItem(hwndTV, htItem);
194 }
195
196 cont = (htItem != htFirst) && (htItem != htLast);
197
198 htItem = (HTREEITEM)TreeView_GetNextVisible(hwndTV, htItem);
199 }
200
201 // unselect the rest
202 if ( unselectOthers )
203 {
204 while ( htItem )
205 {
206 if ( IsItemSelected(hwndTV, htItem) )
207 {
208 UnselectItem(hwndTV, htItem);
209 }
210
211 htItem = (HTREEITEM)TreeView_GetNextVisible(hwndTV, htItem);
212 }
213 }
214
215 // seems to be necessary - otherwise the just selected items don't always
216 // appear as selected
217 UpdateWindow(hwndTV);
218 }
219
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!)
223 //
224 // returns true if the focus was changed, false if the given item was already
225 // the focused one
226 static bool SetFocus(HWND hwndTV, HTREEITEM htItem)
227 {
228 // the current focus
229 HTREEITEM htFocus = (HTREEITEM)TreeView_GetSelection(hwndTV);
230
231 if ( htItem == htFocus )
232 return false;
233
234 if ( htItem )
235 {
236 // remember the selection state of the item
237 bool wasSelected = IsItemSelected(hwndTV, htItem);
238
239 if ( htFocus && IsItemSelected(hwndTV, htFocus) )
240 {
241 // prevent the tree from unselecting the old focus which it
242 // would do by default (TreeView_SelectItem unselects the
243 // focused item)
244 TreeView_SelectItem(hwndTV, 0);
245 SelectItem(hwndTV, htFocus);
246 }
247
248 TreeView_SelectItem(hwndTV, htItem);
249
250 if ( !wasSelected )
251 {
252 // need to clear the selection which TreeView_SelectItem() gave
253 // us
254 UnselectItem(hwndTV, htItem);
255 }
256 //else: was selected, still selected - ok
257 }
258 else // reset focus
259 {
260 bool wasFocusSelected = IsItemSelected(hwndTV, htFocus);
261
262 // just clear the focus
263 TreeView_SelectItem(hwndTV, 0);
264
265 if ( wasFocusSelected )
266 {
267 // restore the selection state
268 SelectItem(hwndTV, htFocus);
269 }
270 }
271
272 return true;
273 }
274
275 // ----------------------------------------------------------------------------
276 // private classes
277 // ----------------------------------------------------------------------------
278
279 // a convenient wrapper around TV_ITEM struct which adds a ctor
280 #ifdef __VISUALC__
281 #pragma warning( disable : 4097 ) // inheriting from typedef
282 #endif
283
284 struct wxTreeViewItem : public TV_ITEM
285 {
286 wxTreeViewItem(const wxTreeItemId& item, // the item handle
287 UINT mask_, // fields which are valid
288 UINT stateMask_ = 0) // for TVIF_STATE only
289 {
290 wxZeroMemory(*this);
291
292 // hItem member is always valid
293 mask = mask_ | TVIF_HANDLE;
294 stateMask = stateMask_;
295 hItem = HITEM(item);
296 }
297 };
298
299 // ----------------------------------------------------------------------------
300 // This class is our userdata/lParam for the TV_ITEMs stored in the treeview.
301 //
302 // We need this for a couple of reasons:
303 //
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
309 // images.
310 //
311 // 2) This class is also needed to hold the HITEM so that we can sort
312 // it correctly in the MSW sort callback.
313 //
314 // In addition it makes other workarounds such as this easier and helps
315 // simplify the code.
316 // ----------------------------------------------------------------------------
317
318 class wxTreeItemParam
319 {
320 public:
321 wxTreeItemParam()
322 {
323 m_data = NULL;
324
325 for ( size_t n = 0; n < WXSIZEOF(m_images); n++ )
326 {
327 m_images[n] = -1;
328 }
329 }
330
331 // dtor deletes the associated data as well
332 virtual ~wxTreeItemParam() { delete m_data; }
333
334 // accessors
335 // get the real data associated with the item
336 wxTreeItemData *GetData() const { return m_data; }
337 // change it
338 void SetData(wxTreeItemData *data) { m_data = data; }
339
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
343 // specified
344 int GetImage(wxTreeItemIcon which) const
345 {
346 int image = m_images[which];
347 if ( image == -1 )
348 {
349 switch ( which )
350 {
351 case wxTreeItemIcon_SelectedExpanded:
352 image = GetImage(wxTreeItemIcon_Expanded);
353 if ( image != -1 )
354 break;
355 //else: fall through
356
357 case wxTreeItemIcon_Selected:
358 case wxTreeItemIcon_Expanded:
359 image = GetImage(wxTreeItemIcon_Normal);
360 break;
361
362 case wxTreeItemIcon_Normal:
363 // no fallback
364 break;
365
366 default:
367 wxFAIL_MSG( _T("unsupported wxTreeItemIcon value") );
368 }
369 }
370
371 return image;
372 }
373 // change the given image
374 void SetImage(int image, wxTreeItemIcon which) { m_images[which] = image; }
375
376 // get item
377 const wxTreeItemId& GetItem() const { return m_item; }
378 // set item
379 void SetItem(const wxTreeItemId& item) { m_item = item; }
380
381 protected:
382 // all the images associated with the item
383 int m_images[wxTreeItemIcon_Max];
384
385 // item for sort callbacks
386 wxTreeItemId m_item;
387
388 // the real client data
389 wxTreeItemData *m_data;
390
391 DECLARE_NO_COPY_CLASS(wxTreeItemParam)
392 };
393
394 // wxVirutalNode is used in place of a single root when 'hidden' root is
395 // specified.
396 class wxVirtualNode : public wxTreeViewItem
397 {
398 public:
399 wxVirtualNode(wxTreeItemParam *param)
400 : wxTreeViewItem(TVI_ROOT, 0)
401 {
402 m_param = param;
403 }
404
405 ~wxVirtualNode()
406 {
407 delete m_param;
408 }
409
410 wxTreeItemParam *GetParam() const { return m_param; }
411 void SetParam(wxTreeItemParam *param) { delete m_param; m_param = param; }
412
413 private:
414 wxTreeItemParam *m_param;
415
416 DECLARE_NO_COPY_CLASS(wxVirtualNode)
417 };
418
419 #ifdef __VISUALC__
420 #pragma warning( default : 4097 )
421 #endif
422
423 // a macro to get the virtual root, returns NULL if none
424 #define GET_VIRTUAL_ROOT() ((wxVirtualNode *)m_pVirtualRoot)
425
426 // returns true if the item is the virtual root
427 #define IS_VIRTUAL_ROOT(item) (HITEM(item) == TVI_ROOT)
428
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
432 {
433 public:
434 wxTreeTraversal(const wxTreeCtrl *tree)
435 {
436 m_tree = tree;
437 }
438
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() { }
443
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);
448
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;
452
453 protected:
454 const wxTreeCtrl *GetTree() const { return m_tree; }
455
456 private:
457 bool Traverse(const wxTreeItemId& root, bool recursively);
458
459 const wxTreeCtrl *m_tree;
460
461 DECLARE_NO_COPY_CLASS(wxTreeTraversal)
462 };
463
464 // internal class for getting the selected items
465 class TraverseSelections : public wxTreeTraversal
466 {
467 public:
468 TraverseSelections(const wxTreeCtrl *tree,
469 wxArrayTreeItemIds& selections)
470 : wxTreeTraversal(tree), m_selections(selections)
471 {
472 m_selections.Empty();
473
474 if (tree->GetCount() > 0)
475 DoTraverse(tree->GetRootItem());
476 }
477
478 virtual bool OnVisit(const wxTreeItemId& item)
479 {
480 const wxTreeCtrl * const tree = GetTree();
481
482 // can't visit a virtual node.
483 if ( (tree->GetRootItem() == item) && tree->HasFlag(wxTR_HIDE_ROOT) )
484 {
485 return true;
486 }
487
488 if ( ::IsItemSelected(GetHwndOf(tree), HITEM(item)) )
489 {
490 m_selections.Add(item);
491 }
492
493 return true;
494 }
495
496 size_t GetCount() const { return m_selections.GetCount(); }
497
498 private:
499 wxArrayTreeItemIds& m_selections;
500
501 DECLARE_NO_COPY_CLASS(TraverseSelections)
502 };
503
504 // internal class for counting tree items
505 class TraverseCounter : public wxTreeTraversal
506 {
507 public:
508 TraverseCounter(const wxTreeCtrl *tree,
509 const wxTreeItemId& root,
510 bool recursively)
511 : wxTreeTraversal(tree)
512 {
513 m_count = 0;
514
515 DoTraverse(root, recursively);
516 }
517
518 virtual bool OnVisit(const wxTreeItemId& WXUNUSED(item))
519 {
520 m_count++;
521
522 return true;
523 }
524
525 size_t GetCount() const { return m_count; }
526
527 private:
528 size_t m_count;
529
530 DECLARE_NO_COPY_CLASS(TraverseCounter)
531 };
532
533 // ----------------------------------------------------------------------------
534 // wxWin macros
535 // ----------------------------------------------------------------------------
536
537 #if wxUSE_EXTENDED_RTTI
538 WX_DEFINE_FLAGS( wxTreeCtrlStyle )
539
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)
549
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)
557
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)
567
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)
582 #endif
583 wxFLAGS_MEMBER(wxTR_DEFAULT_STYLE)
584
585 wxEND_FLAGS( wxTreeCtrlStyle )
586
587 IMPLEMENT_DYNAMIC_CLASS_XTI(wxTreeCtrl, wxControl,"wx/treectrl.h")
588
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()
594
595 wxBEGIN_HANDLERS_TABLE(wxTreeCtrl)
596 wxEND_HANDLERS_TABLE()
597
598 wxCONSTRUCTOR_5( wxTreeCtrl , wxWindow* , Parent , wxWindowID , Id , wxPoint , Position , wxSize , Size , long , WindowStyle )
599 #else
600 IMPLEMENT_DYNAMIC_CLASS(wxTreeCtrl, wxControl)
601 #endif
602
603 // ----------------------------------------------------------------------------
604 // constants
605 // ----------------------------------------------------------------------------
606
607 // indices in gs_expandEvents table below
608 enum
609 {
610 IDX_COLLAPSE,
611 IDX_EXPAND,
612 IDX_WHAT_MAX
613 };
614
615 enum
616 {
617 IDX_DONE,
618 IDX_DOING,
619 IDX_HOW_MAX
620 };
621
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];
625
626 /*
627 but logically it's a const table with the following entries:
628 =
629 {
630 { wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxEVT_COMMAND_TREE_ITEM_COLLAPSING },
631 { wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxEVT_COMMAND_TREE_ITEM_EXPANDING }
632 };
633 */
634
635 // ============================================================================
636 // implementation
637 // ============================================================================
638
639 // ----------------------------------------------------------------------------
640 // tree traversal
641 // ----------------------------------------------------------------------------
642
643 bool wxTreeTraversal::DoTraverse(const wxTreeItemId& root, bool recursively)
644 {
645 if ( !OnVisit(root) )
646 return false;
647
648 return Traverse(root, recursively);
649 }
650
651 bool wxTreeTraversal::Traverse(const wxTreeItemId& root, bool recursively)
652 {
653 wxTreeItemIdValue cookie;
654 wxTreeItemId child = m_tree->GetFirstChild(root, cookie);
655 while ( child.IsOk() )
656 {
657 // depth first traversal
658 if ( recursively && !Traverse(child, true) )
659 return false;
660
661 if ( !OnVisit(child) )
662 return false;
663
664 child = m_tree->GetNextChild(root, cookie);
665 }
666
667 return true;
668 }
669
670 // ----------------------------------------------------------------------------
671 // construction and destruction
672 // ----------------------------------------------------------------------------
673
674 void wxTreeCtrl::Init()
675 {
676 m_textCtrl = NULL;
677 m_hasAnyAttr = false;
678 #if wxUSE_DRAGIMAGE
679 m_dragImage = NULL;
680 #endif
681 m_pVirtualRoot = NULL;
682
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;
689 }
690
691 bool wxTreeCtrl::Create(wxWindow *parent,
692 wxWindowID id,
693 const wxPoint& pos,
694 const wxSize& size,
695 long style,
696 const wxValidator& validator,
697 const wxString& name)
698 {
699 Init();
700
701 if ( (style & wxBORDER_MASK) == wxBORDER_DEFAULT )
702 style |= wxBORDER_SUNKEN;
703
704 if ( !CreateControl(parent, id, pos, size, style, validator, name) )
705 return false;
706
707 WXDWORD exStyle = 0;
708 DWORD wstyle = MSWGetStyle(m_windowStyle, & exStyle);
709 wstyle |= WS_TABSTOP | TVS_SHOWSELALWAYS;
710
711 if ((m_windowStyle & wxTR_NO_LINES) == 0)
712 wstyle |= TVS_HASLINES;
713 if ( m_windowStyle & wxTR_HAS_BUTTONS )
714 wstyle |= TVS_HASBUTTONS;
715
716 if ( m_windowStyle & wxTR_EDIT_LABELS )
717 wstyle |= TVS_EDITLABELS;
718
719 if ( m_windowStyle & wxTR_LINES_AT_ROOT )
720 wstyle |= TVS_LINESATROOT;
721
722 if ( m_windowStyle & wxTR_FULL_ROW_HIGHLIGHT )
723 {
724 if ( wxApp::GetComCtl32Version() >= 471 )
725 wstyle |= TVS_FULLROWSELECT;
726 }
727
728 #if !defined(__WXWINCE__) && defined(TVS_INFOTIP)
729 // Need so that TVN_GETINFOTIP messages will be sent
730 wstyle |= TVS_INFOTIP;
731 #endif
732
733 // Create the tree control.
734 if ( !MSWCreateControl(WC_TREEVIEW, wstyle, pos, size) )
735 return false;
736
737 #if wxUSE_COMCTL32_SAFELY
738 wxWindow::SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
739 wxWindow::SetForegroundColour(wxWindow::GetParent()->GetForegroundColour());
740 #elif 1
741 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
742 SetForegroundColour(wxWindow::GetParent()->GetForegroundColour());
743 #else
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());
752 #endif
753
754 wxSetCCUnicodeFormat(GetHwnd());
755
756 return true;
757 }
758
759 wxTreeCtrl::~wxTreeCtrl()
760 {
761 // delete any attributes
762 if ( m_hasAnyAttr )
763 {
764 WX_CLEAR_HASH_MAP(wxMapTreeAttr, m_attrs);
765
766 // prevent TVN_DELETEITEM handler from deleting the attributes again!
767 m_hasAnyAttr = false;
768 }
769
770 DeleteTextCtrl();
771
772 // delete user data to prevent memory leaks
773 // also deletes hidden root node storage.
774 DeleteAllItems();
775 }
776
777 // ----------------------------------------------------------------------------
778 // accessors
779 // ----------------------------------------------------------------------------
780
781 /* static */ wxVisualAttributes
782 wxTreeCtrl::GetClassDefaultAttributes(wxWindowVariant variant)
783 {
784 wxVisualAttributes attrs = GetCompositeControlsDefaultAttributes(variant);
785
786 // common controls have their own default font
787 attrs.font = wxGetCCDefaultFont();
788
789 return attrs;
790 }
791
792
793 // simple wrappers which add error checking in debug mode
794
795 bool wxTreeCtrl::DoGetItem(wxTreeViewItem *tvItem) const
796 {
797 wxCHECK_MSG( tvItem->hItem != TVI_ROOT, false,
798 _T("can't retrieve virtual root item") );
799
800 if ( !TreeView_GetItem(GetHwnd(), tvItem) )
801 {
802 wxLogLastError(wxT("TreeView_GetItem"));
803
804 return false;
805 }
806
807 return true;
808 }
809
810 void wxTreeCtrl::DoSetItem(wxTreeViewItem *tvItem)
811 {
812 TreeItemUnlocker unlocker(tvItem->hItem);
813
814 if ( TreeView_SetItem(GetHwnd(), tvItem) == -1 )
815 {
816 wxLogLastError(wxT("TreeView_SetItem"));
817 }
818 }
819
820 unsigned int wxTreeCtrl::GetCount() const
821 {
822 return (unsigned int)TreeView_GetCount(GetHwnd());
823 }
824
825 unsigned int wxTreeCtrl::GetIndent() const
826 {
827 return TreeView_GetIndent(GetHwnd());
828 }
829
830 void wxTreeCtrl::SetIndent(unsigned int indent)
831 {
832 TreeView_SetIndent(GetHwnd(), indent);
833 }
834
835 void wxTreeCtrl::SetAnyImageList(wxImageList *imageList, int which)
836 {
837 // no error return
838 (void) TreeView_SetImageList(GetHwnd(),
839 imageList ? imageList->GetHIMAGELIST() : 0,
840 which);
841 }
842
843 void wxTreeCtrl::SetImageList(wxImageList *imageList)
844 {
845 if (m_ownsImageListNormal)
846 delete m_imageListNormal;
847
848 SetAnyImageList(m_imageListNormal = imageList, TVSIL_NORMAL);
849 m_ownsImageListNormal = false;
850 }
851
852 void wxTreeCtrl::SetStateImageList(wxImageList *imageList)
853 {
854 if (m_ownsImageListState) delete m_imageListState;
855 SetAnyImageList(m_imageListState = imageList, TVSIL_STATE);
856 m_ownsImageListState = false;
857 }
858
859 size_t wxTreeCtrl::GetChildrenCount(const wxTreeItemId& item,
860 bool recursively) const
861 {
862 wxCHECK_MSG( item.IsOk(), 0u, wxT("invalid tree item") );
863
864 TraverseCounter counter(this, item, recursively);
865 return counter.GetCount() - 1;
866 }
867
868 // ----------------------------------------------------------------------------
869 // control colours
870 // ----------------------------------------------------------------------------
871
872 bool wxTreeCtrl::SetBackgroundColour(const wxColour &colour)
873 {
874 #if !wxUSE_COMCTL32_SAFELY
875 if ( !wxWindowBase::SetBackgroundColour(colour) )
876 return false;
877
878 ::SendMessage(GetHwnd(), TVM_SETBKCOLOR, 0, colour.GetPixel());
879 #endif
880
881 return true;
882 }
883
884 bool wxTreeCtrl::SetForegroundColour(const wxColour &colour)
885 {
886 #if !wxUSE_COMCTL32_SAFELY
887 if ( !wxWindowBase::SetForegroundColour(colour) )
888 return false;
889
890 ::SendMessage(GetHwnd(), TVM_SETTEXTCOLOR, 0, colour.GetPixel());
891 #endif
892
893 return true;
894 }
895
896 // ----------------------------------------------------------------------------
897 // Item access
898 // ----------------------------------------------------------------------------
899
900 bool wxTreeCtrl::IsHiddenRoot(const wxTreeItemId& item) const
901 {
902 return HITEM(item) == TVI_ROOT && HasFlag(wxTR_HIDE_ROOT);
903 }
904
905 wxString wxTreeCtrl::GetItemText(const wxTreeItemId& item) const
906 {
907 wxCHECK_MSG( item.IsOk(), wxEmptyString, wxT("invalid tree item") );
908
909 wxChar buf[512]; // the size is arbitrary...
910
911 wxTreeViewItem tvItem(item, TVIF_TEXT);
912 tvItem.pszText = buf;
913 tvItem.cchTextMax = WXSIZEOF(buf);
914 if ( !DoGetItem(&tvItem) )
915 {
916 // don't return some garbage which was on stack, but an empty string
917 buf[0] = wxT('\0');
918 }
919
920 return wxString(buf);
921 }
922
923 void wxTreeCtrl::SetItemText(const wxTreeItemId& item, const wxString& text)
924 {
925 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
926
927 if ( IS_VIRTUAL_ROOT(item) )
928 return;
929
930 wxTreeViewItem tvItem(item, TVIF_TEXT);
931 tvItem.pszText = (wxChar *)text.wx_str(); // conversion is ok
932 DoSetItem(&tvItem);
933
934 // when setting the text of the item being edited, the text control should
935 // be updated to reflect the new text as well, otherwise calling
936 // SetItemText() in the OnBeginLabelEdit() handler doesn't have any effect
937 //
938 // don't use GetEditControl() here because m_textCtrl is not set yet
939 HWND hwndEdit = TreeView_GetEditControl(GetHwnd());
940 if ( hwndEdit )
941 {
942 if ( item == m_idEdited )
943 {
944 ::SetWindowText(hwndEdit, text.wx_str());
945 }
946 }
947 }
948
949 int wxTreeCtrl::GetItemImage(const wxTreeItemId& item,
950 wxTreeItemIcon which) const
951 {
952 wxCHECK_MSG( item.IsOk(), -1, wxT("invalid tree item") );
953
954 if ( IsHiddenRoot(item) )
955 {
956 // no images for hidden root item
957 return -1;
958 }
959
960 wxTreeItemParam *param = GetItemParam(item);
961
962 return param && param->HasImage(which) ? param->GetImage(which) : -1;
963 }
964
965 void wxTreeCtrl::SetItemImage(const wxTreeItemId& item, int image,
966 wxTreeItemIcon which)
967 {
968 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
969 wxCHECK_RET( which >= 0 &&
970 which < wxTreeItemIcon_Max,
971 wxT("invalid image index"));
972
973
974 if ( IsHiddenRoot(item) )
975 {
976 // no images for hidden root item
977 return;
978 }
979
980 wxTreeItemParam *data = GetItemParam(item);
981 if ( !data )
982 return;
983
984 data->SetImage(image, which);
985
986 RefreshItem(item);
987 }
988
989 wxTreeItemParam *wxTreeCtrl::GetItemParam(const wxTreeItemId& item) const
990 {
991 wxCHECK_MSG( item.IsOk(), NULL, wxT("invalid tree item") );
992
993 wxTreeViewItem tvItem(item, TVIF_PARAM);
994
995 // hidden root may still have data.
996 if ( IS_VIRTUAL_ROOT(item) )
997 {
998 return GET_VIRTUAL_ROOT()->GetParam();
999 }
1000
1001 // visible node.
1002 if ( !DoGetItem(&tvItem) )
1003 {
1004 return NULL;
1005 }
1006
1007 return (wxTreeItemParam *)tvItem.lParam;
1008 }
1009
1010 wxTreeItemData *wxTreeCtrl::GetItemData(const wxTreeItemId& item) const
1011 {
1012 wxTreeItemParam *data = GetItemParam(item);
1013
1014 return data ? data->GetData() : NULL;
1015 }
1016
1017 void wxTreeCtrl::SetItemData(const wxTreeItemId& item, wxTreeItemData *data)
1018 {
1019 // first, associate this piece of data with this item
1020 if ( data )
1021 {
1022 data->SetId(item);
1023 }
1024
1025 wxTreeItemParam *param = GetItemParam(item);
1026
1027 wxCHECK_RET( param, wxT("failed to change tree items data") );
1028
1029 param->SetData(data);
1030 }
1031
1032 void wxTreeCtrl::SetItemHasChildren(const wxTreeItemId& item, bool has)
1033 {
1034 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1035
1036 if ( IS_VIRTUAL_ROOT(item) )
1037 return;
1038
1039 wxTreeViewItem tvItem(item, TVIF_CHILDREN);
1040 tvItem.cChildren = (int)has;
1041 DoSetItem(&tvItem);
1042 }
1043
1044 void wxTreeCtrl::SetItemBold(const wxTreeItemId& item, bool bold)
1045 {
1046 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1047
1048 if ( IS_VIRTUAL_ROOT(item) )
1049 return;
1050
1051 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_BOLD);
1052 tvItem.state = bold ? TVIS_BOLD : 0;
1053 DoSetItem(&tvItem);
1054 }
1055
1056 void wxTreeCtrl::SetItemDropHighlight(const wxTreeItemId& item, bool highlight)
1057 {
1058 if ( IS_VIRTUAL_ROOT(item) )
1059 return;
1060
1061 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_DROPHILITED);
1062 tvItem.state = highlight ? TVIS_DROPHILITED : 0;
1063 DoSetItem(&tvItem);
1064 }
1065
1066 void wxTreeCtrl::RefreshItem(const wxTreeItemId& item)
1067 {
1068 if ( IS_VIRTUAL_ROOT(item) )
1069 return;
1070
1071 wxRect rect;
1072 if ( GetBoundingRect(item, rect) )
1073 {
1074 RefreshRect(rect);
1075 }
1076 }
1077
1078 wxColour wxTreeCtrl::GetItemTextColour(const wxTreeItemId& item) const
1079 {
1080 wxCHECK_MSG( item.IsOk(), wxNullColour, wxT("invalid tree item") );
1081
1082 wxMapTreeAttr::const_iterator it = m_attrs.find(item.m_pItem);
1083 return it == m_attrs.end() ? wxNullColour : it->second->GetTextColour();
1084 }
1085
1086 wxColour wxTreeCtrl::GetItemBackgroundColour(const wxTreeItemId& item) const
1087 {
1088 wxCHECK_MSG( item.IsOk(), wxNullColour, wxT("invalid tree item") );
1089
1090 wxMapTreeAttr::const_iterator it = m_attrs.find(item.m_pItem);
1091 return it == m_attrs.end() ? wxNullColour : it->second->GetBackgroundColour();
1092 }
1093
1094 wxFont wxTreeCtrl::GetItemFont(const wxTreeItemId& item) const
1095 {
1096 wxCHECK_MSG( item.IsOk(), wxNullFont, wxT("invalid tree item") );
1097
1098 wxMapTreeAttr::const_iterator it = m_attrs.find(item.m_pItem);
1099 return it == m_attrs.end() ? wxNullFont : it->second->GetFont();
1100 }
1101
1102 void wxTreeCtrl::SetItemTextColour(const wxTreeItemId& item,
1103 const wxColour& col)
1104 {
1105 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1106
1107 wxTreeItemAttr *attr;
1108 wxMapTreeAttr::iterator it = m_attrs.find(item.m_pItem);
1109 if ( it == m_attrs.end() )
1110 {
1111 m_hasAnyAttr = true;
1112
1113 m_attrs[item.m_pItem] =
1114 attr = new wxTreeItemAttr;
1115 }
1116 else
1117 {
1118 attr = it->second;
1119 }
1120
1121 attr->SetTextColour(col);
1122
1123 RefreshItem(item);
1124 }
1125
1126 void wxTreeCtrl::SetItemBackgroundColour(const wxTreeItemId& item,
1127 const wxColour& col)
1128 {
1129 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1130
1131 wxTreeItemAttr *attr;
1132 wxMapTreeAttr::iterator it = m_attrs.find(item.m_pItem);
1133 if ( it == m_attrs.end() )
1134 {
1135 m_hasAnyAttr = true;
1136
1137 m_attrs[item.m_pItem] =
1138 attr = new wxTreeItemAttr;
1139 }
1140 else // already in the hash
1141 {
1142 attr = it->second;
1143 }
1144
1145 attr->SetBackgroundColour(col);
1146
1147 RefreshItem(item);
1148 }
1149
1150 void wxTreeCtrl::SetItemFont(const wxTreeItemId& item, const wxFont& font)
1151 {
1152 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1153
1154 wxTreeItemAttr *attr;
1155 wxMapTreeAttr::iterator it = m_attrs.find(item.m_pItem);
1156 if ( it == m_attrs.end() )
1157 {
1158 m_hasAnyAttr = true;
1159
1160 m_attrs[item.m_pItem] =
1161 attr = new wxTreeItemAttr;
1162 }
1163 else // already in the hash
1164 {
1165 attr = it->second;
1166 }
1167
1168 attr->SetFont(font);
1169
1170 // Reset the item's text to ensure that the bounding rect will be adjusted
1171 // for the new font.
1172 SetItemText(item, GetItemText(item));
1173
1174 RefreshItem(item);
1175 }
1176
1177 // ----------------------------------------------------------------------------
1178 // Item status
1179 // ----------------------------------------------------------------------------
1180
1181 bool wxTreeCtrl::IsVisible(const wxTreeItemId& item) const
1182 {
1183 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1184
1185 if ( item == wxTreeItemId(TVI_ROOT) )
1186 {
1187 // virtual (hidden) root is never visible
1188 return false;
1189 }
1190
1191 // Bug in Gnu-Win32 headers, so don't use the macro TreeView_GetItemRect
1192 RECT rect;
1193
1194 // this ugliness comes directly from MSDN - it *is* the correct way to pass
1195 // the HTREEITEM with TVM_GETITEMRECT
1196 *(HTREEITEM *)&rect = HITEM(item);
1197
1198 // true means to get rect for just the text, not the whole line
1199 if ( !::SendMessage(GetHwnd(), TVM_GETITEMRECT, true, (LPARAM)&rect) )
1200 {
1201 // if TVM_GETITEMRECT returned false, then the item is definitely not
1202 // visible (because its parent is not expanded)
1203 return false;
1204 }
1205
1206 // however if it returned true, the item might still be outside the
1207 // currently visible part of the tree, test for it (notice that partly
1208 // visible means visible here)
1209 return rect.bottom > 0 && rect.top < GetClientSize().y;
1210 }
1211
1212 bool wxTreeCtrl::ItemHasChildren(const wxTreeItemId& item) const
1213 {
1214 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1215
1216 if ( IS_VIRTUAL_ROOT(item) )
1217 {
1218 wxTreeItemIdValue cookie;
1219 return GetFirstChild(item, cookie).IsOk();
1220 }
1221
1222 wxTreeViewItem tvItem(item, TVIF_CHILDREN);
1223 DoGetItem(&tvItem);
1224
1225 return tvItem.cChildren != 0;
1226 }
1227
1228 bool wxTreeCtrl::IsExpanded(const wxTreeItemId& item) const
1229 {
1230 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1231
1232 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_EXPANDED);
1233 DoGetItem(&tvItem);
1234
1235 return (tvItem.state & TVIS_EXPANDED) != 0;
1236 }
1237
1238 bool wxTreeCtrl::IsSelected(const wxTreeItemId& item) const
1239 {
1240 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1241
1242 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_SELECTED);
1243 DoGetItem(&tvItem);
1244
1245 return (tvItem.state & TVIS_SELECTED) != 0;
1246 }
1247
1248 bool wxTreeCtrl::IsBold(const wxTreeItemId& item) const
1249 {
1250 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1251
1252 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_BOLD);
1253 DoGetItem(&tvItem);
1254
1255 return (tvItem.state & TVIS_BOLD) != 0;
1256 }
1257
1258 // ----------------------------------------------------------------------------
1259 // navigation
1260 // ----------------------------------------------------------------------------
1261
1262 wxTreeItemId wxTreeCtrl::GetRootItem() const
1263 {
1264 // Root may be real (visible) or virtual (hidden).
1265 if ( GET_VIRTUAL_ROOT() )
1266 return TVI_ROOT;
1267
1268 return wxTreeItemId(TreeView_GetRoot(GetHwnd()));
1269 }
1270
1271 wxTreeItemId wxTreeCtrl::GetSelection() const
1272 {
1273 wxCHECK_MSG( !(m_windowStyle & wxTR_MULTIPLE), wxTreeItemId(),
1274 wxT("this only works with single selection controls") );
1275
1276 return wxTreeItemId(TreeView_GetSelection(GetHwnd()));
1277 }
1278
1279 wxTreeItemId wxTreeCtrl::GetItemParent(const wxTreeItemId& item) const
1280 {
1281 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1282
1283 HTREEITEM hItem;
1284
1285 if ( IS_VIRTUAL_ROOT(item) )
1286 {
1287 // no parent for the virtual root
1288 hItem = 0;
1289 }
1290 else // normal item
1291 {
1292 hItem = TreeView_GetParent(GetHwnd(), HITEM(item));
1293 if ( !hItem && HasFlag(wxTR_HIDE_ROOT) )
1294 {
1295 // the top level items should have the virtual root as their parent
1296 hItem = TVI_ROOT;
1297 }
1298 }
1299
1300 return wxTreeItemId(hItem);
1301 }
1302
1303 wxTreeItemId wxTreeCtrl::GetFirstChild(const wxTreeItemId& item,
1304 wxTreeItemIdValue& cookie) const
1305 {
1306 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1307
1308 // remember the last child returned in 'cookie'
1309 cookie = TreeView_GetChild(GetHwnd(), HITEM(item));
1310
1311 return wxTreeItemId(cookie);
1312 }
1313
1314 wxTreeItemId wxTreeCtrl::GetNextChild(const wxTreeItemId& WXUNUSED(item),
1315 wxTreeItemIdValue& cookie) const
1316 {
1317 wxTreeItemId fromCookie(cookie);
1318
1319 HTREEITEM hitem = HITEM(fromCookie);
1320
1321 hitem = TreeView_GetNextSibling(GetHwnd(), hitem);
1322
1323 wxTreeItemId item(hitem);
1324
1325 cookie = item.m_pItem;
1326
1327 return item;
1328 }
1329
1330 wxTreeItemId wxTreeCtrl::GetLastChild(const wxTreeItemId& item) const
1331 {
1332 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1333
1334 // can this be done more efficiently?
1335 wxTreeItemIdValue cookie;
1336
1337 wxTreeItemId childLast,
1338 child = GetFirstChild(item, cookie);
1339 while ( child.IsOk() )
1340 {
1341 childLast = child;
1342 child = GetNextChild(item, cookie);
1343 }
1344
1345 return childLast;
1346 }
1347
1348 wxTreeItemId wxTreeCtrl::GetNextSibling(const wxTreeItemId& item) const
1349 {
1350 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1351 return wxTreeItemId(TreeView_GetNextSibling(GetHwnd(), HITEM(item)));
1352 }
1353
1354 wxTreeItemId wxTreeCtrl::GetPrevSibling(const wxTreeItemId& item) const
1355 {
1356 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1357 return wxTreeItemId(TreeView_GetPrevSibling(GetHwnd(), HITEM(item)));
1358 }
1359
1360 wxTreeItemId wxTreeCtrl::GetFirstVisibleItem() const
1361 {
1362 return wxTreeItemId(TreeView_GetFirstVisible(GetHwnd()));
1363 }
1364
1365 wxTreeItemId wxTreeCtrl::GetNextVisible(const wxTreeItemId& item) const
1366 {
1367 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1368 wxASSERT_MSG( IsVisible(item), wxT("The item you call GetNextVisible() for must be visible itself!"));
1369
1370 wxTreeItemId next(TreeView_GetNextVisible(GetHwnd(), HITEM(item)));
1371 if ( next.IsOk() && !IsVisible(next) )
1372 {
1373 // Win32 considers that any non-collapsed item is visible while we want
1374 // to return only really visible items
1375 next.Unset();
1376 }
1377
1378 return next;
1379 }
1380
1381 wxTreeItemId wxTreeCtrl::GetPrevVisible(const wxTreeItemId& item) const
1382 {
1383 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1384 wxASSERT_MSG( IsVisible(item), wxT("The item you call GetPrevVisible() for must be visible itself!"));
1385
1386 wxTreeItemId prev(TreeView_GetPrevVisible(GetHwnd(), HITEM(item)));
1387 if ( prev.IsOk() && !IsVisible(prev) )
1388 {
1389 // just as above, Win32 function will happily return the previous item
1390 // in the tree for the first visible item too
1391 prev.Unset();
1392 }
1393
1394 return prev;
1395 }
1396
1397 // ----------------------------------------------------------------------------
1398 // multiple selections emulation
1399 // ----------------------------------------------------------------------------
1400
1401 size_t wxTreeCtrl::GetSelections(wxArrayTreeItemIds& selections) const
1402 {
1403 TraverseSelections selector(this, selections);
1404
1405 return selector.GetCount();
1406 }
1407
1408 // ----------------------------------------------------------------------------
1409 // Usual operations
1410 // ----------------------------------------------------------------------------
1411
1412 wxTreeItemId wxTreeCtrl::DoInsertAfter(const wxTreeItemId& parent,
1413 const wxTreeItemId& hInsertAfter,
1414 const wxString& text,
1415 int image, int selectedImage,
1416 wxTreeItemData *data)
1417 {
1418 wxCHECK_MSG( parent.IsOk() || !TreeView_GetRoot(GetHwnd()),
1419 wxTreeItemId(),
1420 _T("can't have more than one root in the tree") );
1421
1422 TV_INSERTSTRUCT tvIns;
1423 tvIns.hParent = HITEM(parent);
1424 tvIns.hInsertAfter = HITEM(hInsertAfter);
1425
1426 // this is how we insert the item as the first child: supply a NULL
1427 // hInsertAfter
1428 if ( !tvIns.hInsertAfter )
1429 {
1430 tvIns.hInsertAfter = TVI_FIRST;
1431 }
1432
1433 UINT mask = 0;
1434 if ( !text.empty() )
1435 {
1436 mask |= TVIF_TEXT;
1437 tvIns.item.pszText = (wxChar *)text.wx_str(); // cast is ok
1438 }
1439 else
1440 {
1441 tvIns.item.pszText = NULL;
1442 tvIns.item.cchTextMax = 0;
1443 }
1444
1445 // create the param which will store the other item parameters
1446 wxTreeItemParam *param = new wxTreeItemParam;
1447
1448 // we return the images on demand as they depend on whether the item is
1449 // expanded or collapsed too in our case
1450 mask |= TVIF_IMAGE | TVIF_SELECTEDIMAGE;
1451 tvIns.item.iImage = I_IMAGECALLBACK;
1452 tvIns.item.iSelectedImage = I_IMAGECALLBACK;
1453
1454 param->SetImage(image, wxTreeItemIcon_Normal);
1455 param->SetImage(selectedImage, wxTreeItemIcon_Selected);
1456
1457 mask |= TVIF_PARAM;
1458 tvIns.item.lParam = (LPARAM)param;
1459 tvIns.item.mask = mask;
1460
1461 // don't use the hack below for the children of hidden root: this results
1462 // in a crash inside comctl32.dll when we call TreeView_GetItemRect()
1463 const bool firstChild = !IsHiddenRoot(parent) &&
1464 !TreeView_GetChild(GetHwnd(), HITEM(parent));
1465
1466 HTREEITEM id = TreeView_InsertItem(GetHwnd(), &tvIns);
1467 if ( id == 0 )
1468 {
1469 wxLogLastError(wxT("TreeView_InsertItem"));
1470 }
1471
1472 // apparently some Windows versions (2000 and XP are reported to do this)
1473 // sometimes don't refresh the tree after adding the first child and so we
1474 // need this to make the "[+]" appear
1475 if ( firstChild )
1476 {
1477 RECT rect;
1478 TreeView_GetItemRect(GetHwnd(), HITEM(parent), &rect, FALSE);
1479 ::InvalidateRect(GetHwnd(), &rect, FALSE);
1480 }
1481
1482 // associate the application tree item with Win32 tree item handle
1483 param->SetItem(id);
1484
1485 // setup wxTreeItemData
1486 if ( data != NULL )
1487 {
1488 param->SetData(data);
1489 data->SetId(id);
1490 }
1491
1492 return wxTreeItemId(id);
1493 }
1494
1495 wxTreeItemId wxTreeCtrl::AddRoot(const wxString& text,
1496 int image, int selectedImage,
1497 wxTreeItemData *data)
1498 {
1499 if ( HasFlag(wxTR_HIDE_ROOT) )
1500 {
1501 wxASSERT_MSG( !m_pVirtualRoot, _T("tree can have only a single root") );
1502
1503 // create a virtual root item, the parent for all the others
1504 wxTreeItemParam *param = new wxTreeItemParam;
1505 param->SetData(data);
1506
1507 m_pVirtualRoot = new wxVirtualNode(param);
1508
1509 return TVI_ROOT;
1510 }
1511
1512 return DoInsertAfter(wxTreeItemId(), wxTreeItemId(),
1513 text, image, selectedImage, data);
1514 }
1515
1516 wxTreeItemId wxTreeCtrl::DoInsertItem(const wxTreeItemId& parent,
1517 size_t index,
1518 const wxString& text,
1519 int image, int selectedImage,
1520 wxTreeItemData *data)
1521 {
1522 wxTreeItemId idPrev;
1523 if ( index == (size_t)-1 )
1524 {
1525 // special value: append to the end
1526 idPrev = TVI_LAST;
1527 }
1528 else // find the item from index
1529 {
1530 wxTreeItemIdValue cookie;
1531 wxTreeItemId idCur = GetFirstChild(parent, cookie);
1532 while ( index != 0 && idCur.IsOk() )
1533 {
1534 index--;
1535
1536 idPrev = idCur;
1537 idCur = GetNextChild(parent, cookie);
1538 }
1539
1540 // assert, not check: if the index is invalid, we will append the item
1541 // to the end
1542 wxASSERT_MSG( index == 0, _T("bad index in wxTreeCtrl::InsertItem") );
1543 }
1544
1545 return DoInsertAfter(parent, idPrev, text, image, selectedImage, data);
1546 }
1547
1548 void wxTreeCtrl::Delete(const wxTreeItemId& item)
1549 {
1550 // unlock tree selections on vista, without this the
1551 // tree ctrl will eventually crash after item deletion
1552 TreeItemUnlocker unlock_all;
1553
1554 if ( !TreeView_DeleteItem(GetHwnd(), HITEM(item)) )
1555 {
1556 wxLogLastError(wxT("TreeView_DeleteItem"));
1557 }
1558 }
1559
1560 // delete all children (but don't delete the item itself)
1561 void wxTreeCtrl::DeleteChildren(const wxTreeItemId& item)
1562 {
1563 // unlock tree selections on vista for the duration of this call
1564 TreeItemUnlocker unlock_all;
1565
1566 wxTreeItemIdValue cookie;
1567
1568 wxArrayTreeItemIds children;
1569 wxTreeItemId child = GetFirstChild(item, cookie);
1570 while ( child.IsOk() )
1571 {
1572 children.Add(child);
1573
1574 child = GetNextChild(item, cookie);
1575 }
1576
1577 size_t nCount = children.Count();
1578 for ( size_t n = 0; n < nCount; n++ )
1579 {
1580 if ( !TreeView_DeleteItem(GetHwnd(), HITEM(children[n])) )
1581 {
1582 wxLogLastError(wxT("TreeView_DeleteItem"));
1583 }
1584 }
1585 }
1586
1587 void wxTreeCtrl::DeleteAllItems()
1588 {
1589 // unlock tree selections on vista for the duration of this call
1590 TreeItemUnlocker unlock_all;
1591
1592 // delete the "virtual" root item.
1593 if ( GET_VIRTUAL_ROOT() )
1594 {
1595 delete GET_VIRTUAL_ROOT();
1596 m_pVirtualRoot = NULL;
1597 }
1598
1599 // and all the real items
1600
1601 if ( !TreeView_DeleteAllItems(GetHwnd()) )
1602 {
1603 wxLogLastError(wxT("TreeView_DeleteAllItems"));
1604 }
1605 }
1606
1607 void wxTreeCtrl::DoExpand(const wxTreeItemId& item, int flag)
1608 {
1609 wxASSERT_MSG( flag == TVE_COLLAPSE ||
1610 flag == (TVE_COLLAPSE | TVE_COLLAPSERESET) ||
1611 flag == TVE_EXPAND ||
1612 flag == TVE_TOGGLE,
1613 wxT("Unknown flag in wxTreeCtrl::DoExpand") );
1614
1615 // A hidden root can be neither expanded nor collapsed.
1616 wxCHECK_RET( !IsHiddenRoot(item),
1617 wxT("Can't expand/collapse hidden root node!") );
1618
1619 // TreeView_Expand doesn't send TVN_ITEMEXPAND(ING) messages, so we must
1620 // emulate them. This behaviour has changed slightly with comctl32.dll
1621 // v 4.70 - now it does send them but only the first time. To maintain
1622 // compatible behaviour and also in order to not have surprises with the
1623 // future versions, don't rely on this and still do everything ourselves.
1624 // To avoid that the messages be sent twice when the item is expanded for
1625 // the first time we must clear TVIS_EXPANDEDONCE style manually.
1626
1627 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_EXPANDEDONCE);
1628 tvItem.state = 0;
1629 DoSetItem(&tvItem);
1630
1631 if ( TreeView_Expand(GetHwnd(), HITEM(item), flag) != 0 )
1632 {
1633 // note that the {EXPAND|COLLAPS}ING event is sent by TreeView_Expand()
1634 // itself
1635 wxTreeEvent event(gs_expandEvents[IsExpanded(item) ? IDX_EXPAND
1636 : IDX_COLLAPSE]
1637 [IDX_DONE],
1638 this, item);
1639 (void)HandleWindowEvent(event);
1640 }
1641 //else: change didn't took place, so do nothing at all
1642 }
1643
1644 void wxTreeCtrl::Expand(const wxTreeItemId& item)
1645 {
1646 DoExpand(item, TVE_EXPAND);
1647 }
1648
1649 void wxTreeCtrl::Collapse(const wxTreeItemId& item)
1650 {
1651 DoExpand(item, TVE_COLLAPSE);
1652 }
1653
1654 void wxTreeCtrl::CollapseAndReset(const wxTreeItemId& item)
1655 {
1656 DoExpand(item, TVE_COLLAPSE | TVE_COLLAPSERESET);
1657 }
1658
1659 void wxTreeCtrl::Toggle(const wxTreeItemId& item)
1660 {
1661 DoExpand(item, TVE_TOGGLE);
1662 }
1663
1664 void wxTreeCtrl::Unselect()
1665 {
1666 wxASSERT_MSG( !(m_windowStyle & wxTR_MULTIPLE),
1667 wxT("doesn't make sense, may be you want UnselectAll()?") );
1668
1669 // just remove the selection
1670 SelectItem(wxTreeItemId());
1671 }
1672
1673 void wxTreeCtrl::UnselectAll()
1674 {
1675 if ( m_windowStyle & wxTR_MULTIPLE )
1676 {
1677 wxArrayTreeItemIds selections;
1678 size_t count = GetSelections(selections);
1679 for ( size_t n = 0; n < count; n++ )
1680 {
1681 ::UnselectItem(GetHwnd(), HITEM(selections[n]));
1682 }
1683
1684 m_htSelStart.Unset();
1685 }
1686 else
1687 {
1688 // just remove the selection
1689 Unselect();
1690 }
1691 }
1692
1693 void wxTreeCtrl::SelectItem(const wxTreeItemId& item, bool select)
1694 {
1695 wxCHECK_RET( !IsHiddenRoot(item), _T("can't select hidden root item") );
1696
1697 wxASSERT_MSG( select || HasFlag(wxTR_MULTIPLE),
1698 _T("SelectItem(false) works only for multiselect") );
1699
1700 wxTreeEvent event(wxEVT_COMMAND_TREE_SEL_CHANGING, this, item);
1701 if ( !HandleWindowEvent(event) || event.IsAllowed() )
1702 {
1703 if ( HasFlag(wxTR_MULTIPLE) )
1704 {
1705 if ( !::SelectItem(GetHwnd(), HITEM(item), select) )
1706 {
1707 wxLogLastError(wxT("TreeView_SelectItem"));
1708 return;
1709 }
1710 }
1711 else // single selection
1712 {
1713 // use TreeView_SelectItem() to deselect the previous selection
1714 if ( !TreeView_SelectItem(GetHwnd(), HITEM(item)) )
1715 {
1716 wxLogLastError(wxT("TreeView_SelectItem"));
1717 return;
1718 }
1719 }
1720
1721 event.SetEventType(wxEVT_COMMAND_TREE_SEL_CHANGED);
1722 (void)HandleWindowEvent(event);
1723 }
1724 //else: program vetoed the change
1725 }
1726
1727 void wxTreeCtrl::EnsureVisible(const wxTreeItemId& item)
1728 {
1729 wxCHECK_RET( !IsHiddenRoot(item), _T("can't show hidden root item") );
1730
1731 // no error return
1732 TreeView_EnsureVisible(GetHwnd(), HITEM(item));
1733 }
1734
1735 void wxTreeCtrl::ScrollTo(const wxTreeItemId& item)
1736 {
1737 if ( !TreeView_SelectSetFirstVisible(GetHwnd(), HITEM(item)) )
1738 {
1739 wxLogLastError(wxT("TreeView_SelectSetFirstVisible"));
1740 }
1741 }
1742
1743 wxTextCtrl *wxTreeCtrl::GetEditControl() const
1744 {
1745 return m_textCtrl;
1746 }
1747
1748 void wxTreeCtrl::DeleteTextCtrl()
1749 {
1750 if ( m_textCtrl )
1751 {
1752 // the HWND corresponding to this control is deleted by the tree
1753 // control itself and we don't know when exactly this happens, so check
1754 // if the window still exists before calling UnsubclassWin()
1755 if ( !::IsWindow(GetHwndOf(m_textCtrl)) )
1756 {
1757 m_textCtrl->SetHWND(0);
1758 }
1759
1760 m_textCtrl->UnsubclassWin();
1761 m_textCtrl->SetHWND(0);
1762 delete m_textCtrl;
1763 m_textCtrl = NULL;
1764
1765 m_idEdited.Unset();
1766 }
1767 }
1768
1769 wxTextCtrl *wxTreeCtrl::EditLabel(const wxTreeItemId& item,
1770 wxClassInfo *textControlClass)
1771 {
1772 wxASSERT( textControlClass->IsKindOf(CLASSINFO(wxTextCtrl)) );
1773
1774 DeleteTextCtrl();
1775
1776 m_idEdited = item;
1777 m_textCtrl = (wxTextCtrl *)textControlClass->CreateObject();
1778 HWND hWnd = (HWND) TreeView_EditLabel(GetHwnd(), HITEM(item));
1779
1780 // this is not an error - the TVN_BEGINLABELEDIT handler might have
1781 // returned false
1782 if ( !hWnd )
1783 {
1784 delete m_textCtrl;
1785 m_textCtrl = NULL;
1786 return NULL;
1787 }
1788
1789 // textctrl is subclassed in MSWOnNotify
1790 return m_textCtrl;
1791 }
1792
1793 // End label editing, optionally cancelling the edit
1794 void wxTreeCtrl::DoEndEditLabel(bool discardChanges)
1795 {
1796 TreeView_EndEditLabelNow(GetHwnd(), discardChanges);
1797
1798 DeleteTextCtrl();
1799 }
1800
1801 wxTreeItemId wxTreeCtrl::DoTreeHitTest(const wxPoint& point, int& flags) const
1802 {
1803 TV_HITTESTINFO hitTestInfo;
1804 hitTestInfo.pt.x = (int)point.x;
1805 hitTestInfo.pt.y = (int)point.y;
1806
1807 (void) TreeView_HitTest(GetHwnd(), &hitTestInfo);
1808
1809 flags = 0;
1810
1811 // avoid repetition
1812 #define TRANSLATE_FLAG(flag) if ( hitTestInfo.flags & TVHT_##flag ) \
1813 flags |= wxTREE_HITTEST_##flag
1814
1815 TRANSLATE_FLAG(ABOVE);
1816 TRANSLATE_FLAG(BELOW);
1817 TRANSLATE_FLAG(NOWHERE);
1818 TRANSLATE_FLAG(ONITEMBUTTON);
1819 TRANSLATE_FLAG(ONITEMICON);
1820 TRANSLATE_FLAG(ONITEMINDENT);
1821 TRANSLATE_FLAG(ONITEMLABEL);
1822 TRANSLATE_FLAG(ONITEMRIGHT);
1823 TRANSLATE_FLAG(ONITEMSTATEICON);
1824 TRANSLATE_FLAG(TOLEFT);
1825 TRANSLATE_FLAG(TORIGHT);
1826
1827 #undef TRANSLATE_FLAG
1828
1829 return wxTreeItemId(hitTestInfo.hItem);
1830 }
1831
1832 bool wxTreeCtrl::GetBoundingRect(const wxTreeItemId& item,
1833 wxRect& rect,
1834 bool textOnly) const
1835 {
1836 RECT rc;
1837
1838 // Virtual root items have no bounding rectangle
1839 if ( IS_VIRTUAL_ROOT(item) )
1840 {
1841 return false;
1842 }
1843
1844 if ( TreeView_GetItemRect(GetHwnd(), HITEM(item),
1845 &rc, textOnly) )
1846 {
1847 rect = wxRect(wxPoint(rc.left, rc.top), wxPoint(rc.right, rc.bottom));
1848
1849 return true;
1850 }
1851 else
1852 {
1853 // couldn't retrieve rect: for example, item isn't visible
1854 return false;
1855 }
1856 }
1857
1858 // ----------------------------------------------------------------------------
1859 // sorting stuff
1860 // ----------------------------------------------------------------------------
1861
1862 // this is just a tiny namespace which is friend to wxTreeCtrl and so can use
1863 // functions such as IsDataIndirect()
1864 class wxTreeSortHelper
1865 {
1866 public:
1867 static int CALLBACK Compare(LPARAM data1, LPARAM data2, LPARAM tree);
1868
1869 private:
1870 static wxTreeItemId GetIdFromData(LPARAM lParam)
1871 {
1872 return ((wxTreeItemParam*)lParam)->GetItem();
1873 }
1874 };
1875
1876 int CALLBACK wxTreeSortHelper::Compare(LPARAM pItem1,
1877 LPARAM pItem2,
1878 LPARAM htree)
1879 {
1880 wxCHECK_MSG( pItem1 && pItem2, 0,
1881 wxT("sorting tree without data doesn't make sense") );
1882
1883 wxTreeCtrl *tree = (wxTreeCtrl *)htree;
1884
1885 return tree->OnCompareItems(GetIdFromData(pItem1),
1886 GetIdFromData(pItem2));
1887 }
1888
1889 void wxTreeCtrl::SortChildren(const wxTreeItemId& item)
1890 {
1891 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1892
1893 // rely on the fact that TreeView_SortChildren does the same thing as our
1894 // default behaviour, i.e. sorts items alphabetically and so call it
1895 // directly if we're not in derived class (much more efficient!)
1896 // RN: Note that if you find you're code doesn't sort as expected this
1897 // may be why as if you don't use the DECLARE_CLASS/IMPLEMENT_CLASS
1898 // combo for your derived wxTreeCtrl if will sort without
1899 // OnCompareItems
1900 if ( GetClassInfo() == CLASSINFO(wxTreeCtrl) )
1901 {
1902 TreeView_SortChildren(GetHwnd(), HITEM(item), 0);
1903 }
1904 else
1905 {
1906 TV_SORTCB tvSort;
1907 tvSort.hParent = HITEM(item);
1908 tvSort.lpfnCompare = wxTreeSortHelper::Compare;
1909 tvSort.lParam = (LPARAM)this;
1910 TreeView_SortChildrenCB(GetHwnd(), &tvSort, 0 /* reserved */);
1911 }
1912 }
1913
1914 // ----------------------------------------------------------------------------
1915 // implementation
1916 // ----------------------------------------------------------------------------
1917
1918 bool wxTreeCtrl::MSWShouldPreProcessMessage(WXMSG* msg)
1919 {
1920 if ( msg->message == WM_KEYDOWN )
1921 {
1922 // Only eat VK_RETURN if not being used by the application in
1923 // conjunction with modifiers
1924 if ( (msg->wParam == VK_RETURN) && !wxIsAnyModifierDown() )
1925 {
1926 // we need VK_RETURN to generate wxEVT_COMMAND_TREE_ITEM_ACTIVATED
1927 return false;
1928 }
1929 }
1930
1931 return wxTreeCtrlBase::MSWShouldPreProcessMessage(msg);
1932 }
1933
1934 bool wxTreeCtrl::MSWCommand(WXUINT cmd, WXWORD id_)
1935 {
1936 const int id = (signed short)id_;
1937
1938 if ( cmd == EN_UPDATE )
1939 {
1940 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, id);
1941 event.SetEventObject( this );
1942 ProcessCommand(event);
1943 }
1944 else if ( cmd == EN_KILLFOCUS )
1945 {
1946 wxCommandEvent event(wxEVT_KILL_FOCUS, id);
1947 event.SetEventObject( this );
1948 ProcessCommand(event);
1949 }
1950 else
1951 {
1952 // nothing done
1953 return false;
1954 }
1955
1956 // command processed
1957 return true;
1958 }
1959
1960 // we hook into WndProc to process WM_MOUSEMOVE/WM_BUTTONUP messages - as we
1961 // only do it during dragging, minimize wxWin overhead (this is important for
1962 // WM_MOUSEMOVE as they're a lot of them) by catching Windows messages directly
1963 // instead of passing by wxWin events
1964 WXLRESULT wxTreeCtrl::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
1965 {
1966 bool processed = false;
1967 WXLRESULT rc = 0;
1968 bool isMultiple = HasFlag(wxTR_MULTIPLE);
1969
1970 // This message is sent after a right-click, or when the "menu" key is pressed
1971 if ( nMsg == WM_CONTEXTMENU )
1972 {
1973 int x = GET_X_LPARAM(lParam),
1974 y = GET_Y_LPARAM(lParam);
1975
1976 // the item for which the menu should be shown
1977 wxTreeItemId item;
1978
1979 // the position where the menu should be shown in client coordinates
1980 // (so that it can be passed directly to PopupMenu())
1981 wxPoint pt;
1982
1983 if ( x == -1 || y == -1 )
1984 {
1985 // this means that the event was generated from keyboard (e.g. with
1986 // Shift-F10 or special Windows menu key)
1987 //
1988 // use the Explorer standard of putting the menu at the left edge
1989 // of the text, in the vertical middle of the text
1990 item = wxTreeItemId(TreeView_GetSelection(GetHwnd()));
1991 if ( item.IsOk() )
1992 {
1993 // Use the bounding rectangle of only the text part
1994 wxRect rect;
1995 GetBoundingRect(item, rect, true);
1996 pt = wxPoint(rect.GetX(), rect.GetY() + rect.GetHeight() / 2);
1997 }
1998 }
1999 else // event from mouse, use mouse position
2000 {
2001 pt = ScreenToClient(wxPoint(x, y));
2002
2003 TV_HITTESTINFO tvhti;
2004 tvhti.pt.x = pt.x;
2005 tvhti.pt.y = pt.y;
2006 if ( TreeView_HitTest(GetHwnd(), &tvhti) )
2007 item = wxTreeItemId(tvhti.hItem);
2008 }
2009
2010 // create the event
2011 wxTreeEvent event(wxEVT_COMMAND_TREE_ITEM_MENU, this, item);
2012
2013 event.m_pointDrag = pt;
2014
2015 if ( HandleWindowEvent(event) )
2016 processed = true;
2017 //else: continue with generating wxEVT_CONTEXT_MENU in base class code
2018 }
2019 else if ( (nMsg >= WM_MOUSEFIRST) && (nMsg <= WM_MOUSELAST) )
2020 {
2021 // we only process mouse messages here and these parameters have the
2022 // same meaning for all of them
2023 int x = GET_X_LPARAM(lParam),
2024 y = GET_Y_LPARAM(lParam);
2025
2026 TV_HITTESTINFO tvht;
2027 tvht.pt.x = x;
2028 tvht.pt.y = y;
2029
2030 HTREEITEM htItem = TreeView_HitTest(GetHwnd(), &tvht);
2031
2032 switch ( nMsg )
2033 {
2034 case WM_LBUTTONDOWN:
2035 if ( htItem && isMultiple && (tvht.flags & TVHT_ONITEM) != 0 )
2036 {
2037 m_htClickedItem = (WXHTREEITEM) htItem;
2038 m_ptClick = wxPoint(x, y);
2039
2040 if ( wParam & MK_CONTROL )
2041 {
2042 SetFocus();
2043
2044 // toggle selected state
2045 ToggleItemSelection(htItem);
2046
2047 ::SetFocus(GetHwnd(), htItem);
2048
2049 // reset on any click without Shift
2050 m_htSelStart.Unset();
2051
2052 processed = true;
2053 }
2054 else if ( wParam & MK_SHIFT )
2055 {
2056 // this selects all items between the starting one and
2057 // the current
2058
2059 if ( !m_htSelStart )
2060 {
2061 // take the focused item
2062 m_htSelStart = TreeView_GetSelection(GetHwnd());
2063 }
2064
2065 if ( m_htSelStart )
2066 SelectRange(GetHwnd(), HITEM(m_htSelStart), htItem,
2067 !(wParam & MK_CONTROL));
2068 else
2069 ::SelectItem(GetHwnd(), htItem);
2070
2071 ::SetFocus(GetHwnd(), htItem);
2072
2073 processed = true;
2074 }
2075 else // normal click
2076 {
2077 // avoid doing anything if we click on the only
2078 // currently selected item
2079
2080 SetFocus();
2081
2082 wxArrayTreeItemIds selections;
2083 size_t count = GetSelections(selections);
2084 if ( count == 0 ||
2085 count > 1 ||
2086 HITEM(selections[0]) != htItem )
2087 {
2088 // clear the previously selected items, if the
2089 // user clicked outside of the present selection.
2090 // otherwise, perform the deselection on mouse-up.
2091 // this allows multiple drag and drop to work.
2092
2093 if (!IsItemSelected(GetHwnd(), htItem))
2094 {
2095 UnselectAll();
2096
2097 // prevent the click from starting in-place editing
2098 // which should only happen if we click on the
2099 // already selected item (and nothing else is
2100 // selected)
2101
2102 TreeView_SelectItem(GetHwnd(), 0);
2103 ::SelectItem(GetHwnd(), htItem);
2104 }
2105 ::SetFocus(GetHwnd(), htItem);
2106 processed = true;
2107 }
2108 else // click on a single selected item
2109 {
2110 // don't interfere with the default processing in
2111 // WM_MOUSEMOVE handler below as the default window
2112 // proc will start the drag itself if we let have
2113 // WM_LBUTTONDOWN
2114 m_htClickedItem.Unset();
2115 }
2116
2117 // reset on any click without Shift
2118 m_htSelStart.Unset();
2119 }
2120 }
2121 break;
2122
2123 case WM_RBUTTONDOWN:
2124 // default handler removes the highlight from the currently
2125 // focused item when right mouse button is pressed on another
2126 // one but keeps the remaining items highlighted, which is
2127 // confusing, so override this default behaviour for tree with
2128 // multiple selections
2129 if ( isMultiple )
2130 {
2131 if ( !IsItemSelected(GetHwnd(), htItem) )
2132 {
2133 UnselectAll();
2134 SelectItem(htItem);
2135 ::SetFocus(GetHwnd(), htItem);
2136 }
2137
2138 // fire EVT_RIGHT_DOWN
2139 HandleMouseEvent(nMsg, x, y, wParam);
2140
2141 // send NM_RCLICK
2142 NMHDR nmhdr;
2143 nmhdr.hwndFrom = GetHwnd();
2144 nmhdr.idFrom = ::GetWindowLong(GetHwnd(), GWL_ID);
2145 nmhdr.code = NM_RCLICK;
2146 ::SendMessage(::GetParent(GetHwnd()), WM_NOTIFY,
2147 nmhdr.idFrom, (LPARAM)&nmhdr);
2148
2149 // prevent tree control default processing, as we've
2150 // already done everything
2151 processed = true;
2152 }
2153 break;
2154
2155 case WM_MOUSEMOVE:
2156 #ifndef __WXWINCE__
2157 if ( m_htClickedItem )
2158 {
2159 int cx = abs(m_ptClick.x - x);
2160 int cy = abs(m_ptClick.y - y);
2161
2162 if ( cx > ::GetSystemMetrics(SM_CXDRAG) ||
2163 cy > ::GetSystemMetrics(SM_CYDRAG) )
2164 {
2165 NM_TREEVIEW tv;
2166 wxZeroMemory(tv);
2167
2168 tv.hdr.hwndFrom = GetHwnd();
2169 tv.hdr.idFrom = ::GetWindowLong(GetHwnd(), GWL_ID);
2170 tv.hdr.code = TVN_BEGINDRAG;
2171
2172 tv.itemNew.hItem = HITEM(m_htClickedItem);
2173
2174
2175 TVITEM tviAux;
2176 wxZeroMemory(tviAux);
2177
2178 tviAux.hItem = HITEM(m_htClickedItem);
2179 tviAux.mask = TVIF_STATE | TVIF_PARAM;
2180 tviAux.stateMask = 0xffffffff;
2181 TreeView_GetItem(GetHwnd(), &tviAux);
2182
2183 tv.itemNew.state = tviAux.state;
2184 tv.itemNew.lParam = tviAux.lParam;
2185
2186 tv.ptDrag.x = x;
2187 tv.ptDrag.y = y;
2188
2189 // do it before SendMessage() call below to avoid
2190 // reentrancies here if there is another WM_MOUSEMOVE
2191 // in the queue already
2192 m_htClickedItem.Unset();
2193
2194 ::SendMessage(GetHwndOf(GetParent()), WM_NOTIFY,
2195 tv.hdr.idFrom, (LPARAM)&tv );
2196
2197 // don't pass it to the default window proc, it would
2198 // start dragging again
2199 processed = true;
2200 }
2201 }
2202 #endif // __WXWINCE__
2203
2204 #if wxUSE_DRAGIMAGE
2205 if ( m_dragImage )
2206 {
2207 m_dragImage->Move(wxPoint(x, y));
2208 if ( htItem )
2209 {
2210 // highlight the item as target (hiding drag image is
2211 // necessary - otherwise the display will be corrupted)
2212 m_dragImage->Hide();
2213 TreeView_SelectDropTarget(GetHwnd(), htItem);
2214 m_dragImage->Show();
2215 }
2216 }
2217 #endif // wxUSE_DRAGIMAGE
2218 break;
2219
2220 case WM_LBUTTONUP:
2221
2222 // facilitates multiple drag-and-drop
2223 if (htItem && isMultiple)
2224 {
2225 wxArrayTreeItemIds selections;
2226 size_t count = GetSelections(selections);
2227
2228 if (count > 1 &&
2229 !(wParam & MK_CONTROL) &&
2230 !(wParam & MK_SHIFT))
2231 {
2232 UnselectAll();
2233 TreeView_SelectItem(GetHwnd(), htItem);
2234 ::SelectItem(GetHwnd(), htItem);
2235 ::SetFocus(GetHwnd(), htItem);
2236 }
2237 m_htClickedItem.Unset();
2238 }
2239
2240 // fall through
2241
2242 case WM_RBUTTONUP:
2243 #if wxUSE_DRAGIMAGE
2244 if ( m_dragImage )
2245 {
2246 m_dragImage->EndDrag();
2247 delete m_dragImage;
2248 m_dragImage = NULL;
2249
2250 // generate the drag end event
2251 wxTreeEvent event(wxEVT_COMMAND_TREE_END_DRAG, this, htItem);
2252 event.m_pointDrag = wxPoint(x, y);
2253
2254 (void)HandleWindowEvent(event);
2255
2256 // if we don't do it, the tree seems to think that 2 items
2257 // are selected simultaneously which is quite weird
2258 TreeView_SelectDropTarget(GetHwnd(), 0);
2259 }
2260 #endif // wxUSE_DRAGIMAGE
2261 break;
2262 }
2263 }
2264 else if ( (nMsg == WM_SETFOCUS || nMsg == WM_KILLFOCUS) && isMultiple )
2265 {
2266 // the tree control greys out the selected item when it loses focus and
2267 // paints it as selected again when it regains it, but it won't do it
2268 // for the other items itself - help it
2269 wxArrayTreeItemIds selections;
2270 size_t count = GetSelections(selections);
2271 RECT rect;
2272 for ( size_t n = 0; n < count; n++ )
2273 {
2274 // TreeView_GetItemRect() will return false if item is not visible,
2275 // which may happen perfectly well
2276 if ( TreeView_GetItemRect(GetHwnd(), HITEM(selections[n]),
2277 &rect, TRUE) )
2278 {
2279 ::InvalidateRect(GetHwnd(), &rect, FALSE);
2280 }
2281 }
2282 }
2283 else if ( nMsg == WM_KEYDOWN && isMultiple )
2284 {
2285 bool bCtrl = wxIsCtrlDown(),
2286 bShift = wxIsShiftDown();
2287
2288 HTREEITEM htSel = (HTREEITEM)TreeView_GetSelection(GetHwnd());
2289 switch ( wParam )
2290 {
2291 case VK_SPACE:
2292 if ( bCtrl )
2293 {
2294 ToggleItemSelection(htSel);
2295 }
2296 else
2297 {
2298 UnselectAll();
2299
2300 ::SelectItem(GetHwnd(), htSel);
2301 }
2302
2303 processed = true;
2304 break;
2305
2306 case VK_UP:
2307 case VK_DOWN:
2308 if ( !bCtrl && !bShift )
2309 {
2310 // no modifiers, just clear selection and then let the default
2311 // processing to take place
2312 UnselectAll();
2313 }
2314 else if ( htSel )
2315 {
2316 (void)wxControl::MSWWindowProc(nMsg, wParam, lParam);
2317
2318 HTREEITEM htNext = (HTREEITEM)
2319 TreeView_GetNextItem
2320 (
2321 GetHwnd(),
2322 htSel,
2323 wParam == VK_UP ? TVGN_PREVIOUSVISIBLE
2324 : TVGN_NEXTVISIBLE
2325 );
2326
2327 if ( !htNext )
2328 {
2329 // at the top/bottom
2330 htNext = htSel;
2331 }
2332
2333 if ( bShift )
2334 {
2335 if ( !m_htSelStart )
2336 m_htSelStart = htSel;
2337
2338 SelectRange(GetHwnd(), HITEM(m_htSelStart), htNext);
2339 }
2340 else // bCtrl
2341 {
2342 // without changing selection
2343 ::SetFocus(GetHwnd(), htNext);
2344 }
2345
2346 processed = true;
2347 }
2348 break;
2349
2350 case VK_HOME:
2351 case VK_END:
2352 case VK_PRIOR:
2353 case VK_NEXT:
2354 // TODO: handle Shift/Ctrl with these keys
2355 if ( !bCtrl && !bShift )
2356 {
2357 UnselectAll();
2358
2359 m_htSelStart.Unset();
2360 }
2361 }
2362 }
2363 else if ( nMsg == WM_COMMAND )
2364 {
2365 // if we receive a EN_KILLFOCUS command from the in-place edit control
2366 // used for label editing, make sure to end editing
2367 WORD id, cmd;
2368 WXHWND hwnd;
2369 UnpackCommand(wParam, lParam, &id, &hwnd, &cmd);
2370
2371 if ( cmd == EN_KILLFOCUS )
2372 {
2373 if ( m_textCtrl && m_textCtrl->GetHandle() == hwnd )
2374 {
2375 DoEndEditLabel();
2376
2377 processed = true;
2378 }
2379 }
2380 }
2381
2382 if ( !processed )
2383 rc = wxControl::MSWWindowProc(nMsg, wParam, lParam);
2384
2385 return rc;
2386 }
2387
2388 WXLRESULT
2389 wxTreeCtrl::MSWDefWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
2390 {
2391 if ( nMsg == WM_CHAR )
2392 {
2393 // don't let the control process Space and Return keys because it
2394 // doesn't do anything useful with them anyhow but always beeps
2395 // annoyingly when it receives them and there is no way to turn it off
2396 // simply if you just process TREEITEM_ACTIVATED event to which Space
2397 // and Enter presses are mapped in your code
2398 if ( wParam == VK_SPACE || wParam == VK_RETURN )
2399 return 0;
2400 }
2401 #if wxUSE_DRAGIMAGE
2402 else if ( nMsg == WM_KEYDOWN )
2403 {
2404 if ( wParam == VK_ESCAPE )
2405 {
2406 if ( m_dragImage )
2407 {
2408 m_dragImage->EndDrag();
2409 delete m_dragImage;
2410 m_dragImage = NULL;
2411
2412 // if we don't do it, the tree seems to think that 2 items
2413 // are selected simultaneously which is quite weird
2414 TreeView_SelectDropTarget(GetHwnd(), 0);
2415 }
2416 }
2417 }
2418 #endif // wxUSE_DRAGIMAGE
2419
2420 return wxControl::MSWDefWindowProc(nMsg, wParam, lParam);
2421 }
2422
2423 // process WM_NOTIFY Windows message
2424 bool wxTreeCtrl::MSWOnNotify(int idCtrl, WXLPARAM lParam, WXLPARAM *result)
2425 {
2426 wxTreeEvent event(wxEVT_NULL, this);
2427 wxEventType eventType = wxEVT_NULL;
2428 NMHDR *hdr = (NMHDR *)lParam;
2429
2430 switch ( hdr->code )
2431 {
2432 case TVN_BEGINDRAG:
2433 eventType = wxEVT_COMMAND_TREE_BEGIN_DRAG;
2434 // fall through
2435
2436 case TVN_BEGINRDRAG:
2437 {
2438 if ( eventType == wxEVT_NULL )
2439 eventType = wxEVT_COMMAND_TREE_BEGIN_RDRAG;
2440 //else: left drag, already set above
2441
2442 NM_TREEVIEW *tv = (NM_TREEVIEW *)lParam;
2443
2444 event.m_item = tv->itemNew.hItem;
2445 event.m_pointDrag = wxPoint(tv->ptDrag.x, tv->ptDrag.y);
2446
2447 // don't allow dragging by default: the user code must
2448 // explicitly say that it wants to allow it to avoid breaking
2449 // the old apps
2450 event.Veto();
2451 }
2452 break;
2453
2454 case TVN_BEGINLABELEDIT:
2455 {
2456 eventType = wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT;
2457 TV_DISPINFO *info = (TV_DISPINFO *)lParam;
2458
2459 // although the user event handler may still veto it, it is
2460 // important to set it now so that calls to SetItemText() from
2461 // the event handler would change the text controls contents
2462 m_idEdited =
2463 event.m_item = info->item.hItem;
2464 event.m_label = info->item.pszText;
2465 event.m_editCancelled = false;
2466 }
2467 break;
2468
2469 case TVN_DELETEITEM:
2470 {
2471 eventType = wxEVT_COMMAND_TREE_DELETE_ITEM;
2472 NM_TREEVIEW *tv = (NM_TREEVIEW *)lParam;
2473
2474 event.m_item = tv->itemOld.hItem;
2475
2476 if ( m_hasAnyAttr )
2477 {
2478 wxMapTreeAttr::iterator it = m_attrs.find(tv->itemOld.hItem);
2479 if ( it != m_attrs.end() )
2480 {
2481 delete it->second;
2482 m_attrs.erase(it);
2483 }
2484 }
2485 }
2486 break;
2487
2488 case TVN_ENDLABELEDIT:
2489 {
2490 eventType = wxEVT_COMMAND_TREE_END_LABEL_EDIT;
2491 TV_DISPINFO *info = (TV_DISPINFO *)lParam;
2492
2493 event.m_item = info->item.hItem;
2494 event.m_label = info->item.pszText;
2495 event.m_editCancelled = info->item.pszText == NULL;
2496 break;
2497 }
2498
2499 #ifndef __WXWINCE__
2500 // These *must* not be removed or TVN_GETINFOTIP will
2501 // not be processed each time the mouse is moved
2502 // and the tooltip will only ever update once.
2503 case TTN_NEEDTEXTA:
2504 case TTN_NEEDTEXTW:
2505 {
2506 *result = 0;
2507
2508 break;
2509 }
2510
2511 #ifdef TVN_GETINFOTIP
2512 case TVN_GETINFOTIP:
2513 {
2514 eventType = wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP;
2515 NMTVGETINFOTIP *info = (NMTVGETINFOTIP*)lParam;
2516
2517 // Which item are we trying to get a tooltip for?
2518 event.m_item = info->hItem;
2519
2520 break;
2521 }
2522 #endif // TVN_GETINFOTIP
2523 #endif // !__WXWINCE__
2524
2525 case TVN_GETDISPINFO:
2526 eventType = wxEVT_COMMAND_TREE_GET_INFO;
2527 // fall through
2528
2529 case TVN_SETDISPINFO:
2530 {
2531 if ( eventType == wxEVT_NULL )
2532 eventType = wxEVT_COMMAND_TREE_SET_INFO;
2533 //else: get, already set above
2534
2535 TV_DISPINFO *info = (TV_DISPINFO *)lParam;
2536
2537 event.m_item = info->item.hItem;
2538 break;
2539 }
2540
2541 case TVN_ITEMEXPANDING:
2542 case TVN_ITEMEXPANDED:
2543 {
2544 NM_TREEVIEW *tv = (NM_TREEVIEW*)lParam;
2545
2546 int what;
2547 switch ( tv->action )
2548 {
2549 default:
2550 wxLogDebug(wxT("unexpected code %d in TVN_ITEMEXPAND message"), tv->action);
2551 // fall through
2552
2553 case TVE_EXPAND:
2554 what = IDX_EXPAND;
2555 break;
2556
2557 case TVE_COLLAPSE:
2558 what = IDX_COLLAPSE;
2559 break;
2560 }
2561
2562 int how = hdr->code == TVN_ITEMEXPANDING ? IDX_DOING
2563 : IDX_DONE;
2564
2565 eventType = gs_expandEvents[what][how];
2566
2567 event.m_item = tv->itemNew.hItem;
2568 }
2569 break;
2570
2571 case TVN_KEYDOWN:
2572 {
2573 eventType = wxEVT_COMMAND_TREE_KEY_DOWN;
2574 TV_KEYDOWN *info = (TV_KEYDOWN *)lParam;
2575
2576 // fabricate the lParam and wParam parameters sufficiently
2577 // similar to the ones from a "real" WM_KEYDOWN so that
2578 // CreateKeyEvent() works correctly
2579 WXLPARAM lParam = (wxIsAltDown() ? KF_ALTDOWN : 0) << 16;
2580
2581 WXWPARAM wParam = info->wVKey;
2582
2583 int keyCode = wxCharCodeMSWToWX(wParam);
2584 if ( !keyCode )
2585 {
2586 // wxCharCodeMSWToWX() returns 0 to indicate that this is a
2587 // simple ASCII key
2588 keyCode = wParam;
2589 }
2590
2591 event.m_evtKey = CreateKeyEvent(wxEVT_KEY_DOWN,
2592 keyCode,
2593 lParam,
2594 wParam);
2595
2596 // a separate event for Space/Return
2597 if ( !wxIsAnyModifierDown() &&
2598 ((info->wVKey == VK_SPACE) || (info->wVKey == VK_RETURN)) )
2599 {
2600 wxTreeItemId item;
2601 if ( !HasFlag(wxTR_MULTIPLE) )
2602 item = GetSelection();
2603
2604 wxTreeEvent event2(wxEVT_COMMAND_TREE_ITEM_ACTIVATED,
2605 this, item);
2606 (void)HandleWindowEvent(event2);
2607 }
2608 }
2609 break;
2610
2611
2612 // Vista's tree control has introduced some problems with our
2613 // multi-selection tree. When TreeView_SelectItem() is called,
2614 // the wrong items are deselected.
2615
2616 // Fortunately, Vista provides a new notification, TVN_ITEMCHANGING
2617 // that can be used to regulate this incorrect behavior. The
2618 // following messages will allow only the unlocked item's selection
2619 // state to change
2620
2621 case TVN_ITEMCHANGINGA:
2622 case TVN_ITEMCHANGINGW:
2623 {
2624 // we only need to handles these in multi-select trees
2625 if ( HasFlag(wxTR_MULTIPLE) )
2626 {
2627 // get info about the item about to be changed
2628 NMTVITEMCHANGE* info = (NMTVITEMCHANGE*)lParam;
2629 if (TreeItemUnlocker::IsLocked(info->hItem))
2630 {
2631 // item's state is locked, don't allow the change
2632 // returning 1 will disallow the change
2633 *result = 1;
2634 return true;
2635 }
2636 }
2637
2638 // allow the state change
2639 }
2640 return false;
2641
2642 // NB: MSLU is broken and sends TVN_SELCHANGEDA instead of
2643 // TVN_SELCHANGEDW in Unicode mode under Win98. Therefore
2644 // we have to handle both messages:
2645 case TVN_SELCHANGEDA:
2646 case TVN_SELCHANGEDW:
2647 eventType = wxEVT_COMMAND_TREE_SEL_CHANGED;
2648 // fall through
2649
2650 case TVN_SELCHANGINGA:
2651 case TVN_SELCHANGINGW:
2652 {
2653 if ( eventType == wxEVT_NULL )
2654 eventType = wxEVT_COMMAND_TREE_SEL_CHANGING;
2655 //else: already set above
2656
2657 if (hdr->code == TVN_SELCHANGINGW ||
2658 hdr->code == TVN_SELCHANGEDW)
2659 {
2660 NM_TREEVIEWW *tv = (NM_TREEVIEWW *)lParam;
2661 event.m_item = tv->itemNew.hItem;
2662 event.m_itemOld = tv->itemOld.hItem;
2663 }
2664 else
2665 {
2666 NM_TREEVIEWA *tv = (NM_TREEVIEWA *)lParam;
2667 event.m_item = tv->itemNew.hItem;
2668 event.m_itemOld = tv->itemOld.hItem;
2669 }
2670 }
2671
2672 // we receive this message from WM_LBUTTONDOWN handler inside
2673 // comctl32.dll and so before the click is passed to
2674 // DefWindowProc() which sets the focus to the window which was
2675 // clicked and this can lead to unexpected event sequences: for
2676 // example, we may get a "selection change" event from the tree
2677 // before getting a "kill focus" event for the text control which
2678 // had the focus previously, thus breaking user code doing input
2679 // validation
2680 //
2681 // to avoid such surprises, we force the generation of focus events
2682 // now, before we generate the selection change ones
2683 SetFocus();
2684 break;
2685
2686 // instead of explicitly checking for _WIN32_IE, check if the
2687 // required symbols are available in the headers
2688 #if defined(CDDS_PREPAINT) && !wxUSE_COMCTL32_SAFELY
2689 case NM_CUSTOMDRAW:
2690 {
2691 LPNMTVCUSTOMDRAW lptvcd = (LPNMTVCUSTOMDRAW)lParam;
2692 NMCUSTOMDRAW& nmcd = lptvcd->nmcd;
2693 switch ( nmcd.dwDrawStage )
2694 {
2695 case CDDS_PREPAINT:
2696 // if we've got any items with non standard attributes,
2697 // notify us before painting each item
2698 *result = m_hasAnyAttr ? CDRF_NOTIFYITEMDRAW
2699 : CDRF_DODEFAULT;
2700
2701 // windows in TreeCtrl use one-based index for item state images,
2702 // 0 indexed image is not being used, we're using zero-based index,
2703 // so we have to add temp image (of zero index) to state image list
2704 // before we draw any item, then after items are drawn we have to
2705 // delete it (in POSTPAINT notify)
2706 if (m_imageListState && m_imageListState->GetImageCount() > 0)
2707 {
2708 #define hImageList (HIMAGELIST)m_imageListState->GetHIMAGELIST()
2709
2710 // add temporary image
2711 int width, height;
2712 m_imageListState->GetSize(0, width, height);
2713
2714 HBITMAP hbmpTemp = ::CreateBitmap(width, height, 1, 1, NULL);
2715 int index = ::ImageList_Add(hImageList, hbmpTemp, hbmpTemp);
2716 ::DeleteObject(hbmpTemp);
2717
2718 if ( index != -1 )
2719 {
2720 // move images to right
2721 for ( int i = index; i > 0; i-- )
2722 ::ImageList_Copy(hImageList, i, hImageList, i-1, 0);
2723
2724 // we must remove the image in POSTPAINT notify
2725 *result |= CDRF_NOTIFYPOSTPAINT;
2726 }
2727
2728 #undef hImageList
2729 }
2730 break;
2731
2732 case CDDS_POSTPAINT:
2733 // we are deleting temp image of 0 index, which was
2734 // added before items were drawn (in PREPAINT notify)
2735 if (m_imageListState && m_imageListState->GetImageCount() > 0)
2736 m_imageListState->Remove(0);
2737 break;
2738
2739 case CDDS_ITEMPREPAINT:
2740 {
2741 wxMapTreeAttr::iterator
2742 it = m_attrs.find((void *)nmcd.dwItemSpec);
2743
2744 if ( it == m_attrs.end() )
2745 {
2746 // nothing to do for this item
2747 *result = CDRF_DODEFAULT;
2748 break;
2749 }
2750
2751 wxTreeItemAttr * const attr = it->second;
2752
2753 wxTreeViewItem tvItem((void *)nmcd.dwItemSpec,
2754 TVIF_STATE, TVIS_DROPHILITED);
2755 DoGetItem(&tvItem);
2756 const UINT tvItemState = tvItem.state;
2757
2758 // selection colours should override ours,
2759 // otherwise it is too confusing to the user
2760 if ( !(nmcd.uItemState & CDIS_SELECTED) &&
2761 !(tvItemState & TVIS_DROPHILITED) )
2762 {
2763 wxColour colBack;
2764 if ( attr->HasBackgroundColour() )
2765 {
2766 colBack = attr->GetBackgroundColour();
2767 lptvcd->clrTextBk = wxColourToRGB(colBack);
2768 }
2769 }
2770
2771 // but we still want to keep the special foreground
2772 // colour when we don't have focus (we can't keep
2773 // it when we do, it would usually be unreadable on
2774 // the almost inverted bg colour...)
2775 if ( ( !(nmcd.uItemState & CDIS_SELECTED) ||
2776 FindFocus() != this ) &&
2777 !(tvItemState & TVIS_DROPHILITED) )
2778 {
2779 wxColour colText;
2780 if ( attr->HasTextColour() )
2781 {
2782 colText = attr->GetTextColour();
2783 lptvcd->clrText = wxColourToRGB(colText);
2784 }
2785 }
2786
2787 if ( attr->HasFont() )
2788 {
2789 HFONT hFont = GetHfontOf(attr->GetFont());
2790
2791 ::SelectObject(nmcd.hdc, hFont);
2792
2793 *result = CDRF_NEWFONT;
2794 }
2795 else // no specific font
2796 {
2797 *result = CDRF_DODEFAULT;
2798 }
2799 }
2800 break;
2801
2802 default:
2803 *result = CDRF_DODEFAULT;
2804 }
2805 }
2806
2807 // we always process it
2808 return true;
2809 #endif // have owner drawn support in headers
2810
2811 case NM_CLICK:
2812 {
2813 DWORD pos = GetMessagePos();
2814 POINT point;
2815 point.x = LOWORD(pos);
2816 point.y = HIWORD(pos);
2817 ::MapWindowPoints(HWND_DESKTOP, GetHwnd(), &point, 1);
2818 int flags = 0;
2819 wxTreeItemId item = HitTest(wxPoint(point.x, point.y), flags);
2820 if (flags & wxTREE_HITTEST_ONITEMSTATEICON)
2821 {
2822 event.m_item = item;
2823 eventType = wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK;
2824 }
2825 break;
2826 }
2827
2828 case NM_DBLCLK:
2829 case NM_RCLICK:
2830 {
2831 TV_HITTESTINFO tvhti;
2832 ::GetCursorPos(&tvhti.pt);
2833 ::ScreenToClient(GetHwnd(), &tvhti.pt);
2834 if ( TreeView_HitTest(GetHwnd(), &tvhti) )
2835 {
2836 if ( tvhti.flags & TVHT_ONITEM )
2837 {
2838 event.m_item = tvhti.hItem;
2839 eventType = (int)hdr->code == NM_DBLCLK
2840 ? wxEVT_COMMAND_TREE_ITEM_ACTIVATED
2841 : wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK;
2842
2843 event.m_pointDrag.x = tvhti.pt.x;
2844 event.m_pointDrag.y = tvhti.pt.y;
2845 }
2846
2847 break;
2848 }
2849 }
2850 // fall through
2851
2852 default:
2853 return wxControl::MSWOnNotify(idCtrl, lParam, result);
2854 }
2855
2856 event.SetEventType(eventType);
2857
2858 if ( event.m_item.IsOk() )
2859 event.SetClientObject(GetItemData(event.m_item));
2860
2861 bool processed = HandleWindowEvent(event);
2862
2863 // post processing
2864 switch ( hdr->code )
2865 {
2866 case NM_DBLCLK:
2867 // we translate NM_DBLCLK into ACTIVATED event and if the user
2868 // handled the activation of the item we shouldn't proceed with
2869 // also using the same double click for toggling the item expanded
2870 // state -- but OTOH do let the user to expand/collapse the item by
2871 // double clicking on it if the activation is not handled specially
2872 *result = processed;
2873 break;
2874
2875 case NM_RCLICK:
2876 // prevent tree control from sending WM_CONTEXTMENU to our parent
2877 // (which it does if NM_RCLICK is not handled) because we want to
2878 // send it to the control itself
2879 *result =
2880 processed = true;
2881
2882 ::SendMessage(GetHwnd(), WM_CONTEXTMENU,
2883 (WPARAM)GetHwnd(), ::GetMessagePos());
2884 break;
2885
2886 case TVN_BEGINDRAG:
2887 case TVN_BEGINRDRAG:
2888 #if wxUSE_DRAGIMAGE
2889 if ( event.IsAllowed() )
2890 {
2891 // normally this is impossible because the m_dragImage is
2892 // deleted once the drag operation is over
2893 wxASSERT_MSG( !m_dragImage, _T("starting to drag once again?") );
2894
2895 m_dragImage = new wxDragImage(*this, event.m_item);
2896 m_dragImage->BeginDrag(wxPoint(0,0), this);
2897 m_dragImage->Show();
2898 }
2899 #endif // wxUSE_DRAGIMAGE
2900 break;
2901
2902 case TVN_DELETEITEM:
2903 {
2904 // NB: we might process this message using wxWidgets event
2905 // tables, but due to overhead of wxWin event system we
2906 // prefer to do it here ourself (otherwise deleting a tree
2907 // with many items is just too slow)
2908 NM_TREEVIEW *tv = (NM_TREEVIEW *)lParam;
2909
2910 wxTreeItemParam *param =
2911 (wxTreeItemParam *)tv->itemOld.lParam;
2912 delete param;
2913
2914 processed = true; // Make sure we don't get called twice
2915 }
2916 break;
2917
2918 case TVN_BEGINLABELEDIT:
2919 // return true to cancel label editing
2920 *result = !event.IsAllowed();
2921
2922 // set ES_WANTRETURN ( like we do in BeginLabelEdit )
2923 if ( event.IsAllowed() )
2924 {
2925 HWND hText = TreeView_GetEditControl(GetHwnd());
2926 if ( hText )
2927 {
2928 // MBN: if m_textCtrl already has an HWND, it is a stale
2929 // pointer from a previous edit (because the user
2930 // didn't modify the label before dismissing the control,
2931 // and TVN_ENDLABELEDIT was not sent), so delete it
2932 if ( m_textCtrl && m_textCtrl->GetHWND() )
2933 DeleteTextCtrl();
2934 if ( !m_textCtrl )
2935 m_textCtrl = new wxTextCtrl();
2936 m_textCtrl->SetParent(this);
2937 m_textCtrl->SetHWND((WXHWND)hText);
2938 m_textCtrl->SubclassWin((WXHWND)hText);
2939
2940 // set wxTE_PROCESS_ENTER style for the text control to
2941 // force it to process the Enter presses itself, otherwise
2942 // they could be stolen from it by the dialog
2943 // navigation code
2944 m_textCtrl->SetWindowStyle(m_textCtrl->GetWindowStyle()
2945 | wxTE_PROCESS_ENTER);
2946 }
2947 }
2948 else // we had set m_idEdited before
2949 {
2950 m_idEdited.Unset();
2951 }
2952 break;
2953
2954 case TVN_ENDLABELEDIT:
2955 // return true to set the label to the new string: note that we
2956 // also must pretend that we did process the message or it is going
2957 // to be passed to DefWindowProc() which will happily return false
2958 // cancelling the label change
2959 *result = event.IsAllowed();
2960 processed = true;
2961
2962 // ensure that we don't have the text ctrl which is going to be
2963 // deleted any more
2964 DeleteTextCtrl();
2965 break;
2966
2967 #ifndef __WXWINCE__
2968 #ifdef TVN_GETINFOTIP
2969 case TVN_GETINFOTIP:
2970 {
2971 // If the user permitted a tooltip change, change it
2972 if (event.IsAllowed())
2973 {
2974 SetToolTip(event.m_label);
2975 }
2976 }
2977 break;
2978 #endif
2979 #endif
2980
2981 case TVN_SELCHANGING:
2982 case TVN_ITEMEXPANDING:
2983 // return true to prevent the action from happening
2984 *result = !event.IsAllowed();
2985 break;
2986
2987 case TVN_ITEMEXPANDED:
2988 {
2989 NM_TREEVIEW *tv = (NM_TREEVIEW *)lParam;
2990 const wxTreeItemId id(tv->itemNew.hItem);
2991
2992 if ( tv->action == TVE_COLLAPSE )
2993 {
2994 if ( wxApp::GetComCtl32Version() >= 600 )
2995 {
2996 // for some reason the item selection rectangle depends
2997 // on whether it is expanded or collapsed (at least
2998 // with comctl32.dll v6): it is wider (by 3 pixels) in
2999 // the expanded state, so when the item collapses and
3000 // then is deselected the rightmost 3 pixels of the
3001 // previously drawn selection are left on the screen
3002 //
3003 // it's not clear if it's a bug in comctl32.dll or in
3004 // our code (because it does not happen in Explorer but
3005 // OTOH we don't do anything which could result in this
3006 // AFAICS) but we do need to work around it to avoid
3007 // ugly artifacts
3008 RefreshItem(id);
3009 }
3010 }
3011 else // expand
3012 {
3013 // the item is also not refreshed properly after expansion when
3014 // it has an image depending on the expanded/collapsed state:
3015 // again, it's not clear if the bug is in comctl32.dll or our
3016 // code...
3017 int image = GetItemImage(id, wxTreeItemIcon_Expanded);
3018 if ( image != -1 )
3019 {
3020 RefreshItem(id);
3021 }
3022 }
3023 }
3024 break;
3025
3026 case TVN_GETDISPINFO:
3027 // NB: so far the user can't set the image himself anyhow, so do it
3028 // anyway - but this may change later
3029 //if ( /* !processed && */ )
3030 {
3031 wxTreeItemId item = event.m_item;
3032 TV_DISPINFO *info = (TV_DISPINFO *)lParam;
3033
3034 const wxTreeItemParam * const param = GetItemParam(item);
3035 if ( !param )
3036 break;
3037
3038 if ( info->item.mask & TVIF_IMAGE )
3039 {
3040 info->item.iImage =
3041 param->GetImage
3042 (
3043 IsExpanded(item) ? wxTreeItemIcon_Expanded
3044 : wxTreeItemIcon_Normal
3045 );
3046 }
3047 if ( info->item.mask & TVIF_SELECTEDIMAGE )
3048 {
3049 info->item.iSelectedImage =
3050 param->GetImage
3051 (
3052 IsExpanded(item) ? wxTreeItemIcon_SelectedExpanded
3053 : wxTreeItemIcon_Selected
3054 );
3055 }
3056 }
3057 break;
3058
3059 //default:
3060 // for the other messages the return value is ignored and there is
3061 // nothing special to do
3062 }
3063 return processed;
3064 }
3065
3066 // ----------------------------------------------------------------------------
3067 // State control.
3068 // ----------------------------------------------------------------------------
3069
3070 // why do they define INDEXTOSTATEIMAGEMASK but not the inverse?
3071 #define STATEIMAGEMASKTOINDEX(state) (((state) & TVIS_STATEIMAGEMASK) >> 12)
3072
3073 int wxTreeCtrl::DoGetItemState(const wxTreeItemId& item) const
3074 {
3075 wxCHECK_MSG( item.IsOk(), wxTREE_ITEMSTATE_NONE, wxT("invalid tree item") );
3076
3077 // receive the desired information
3078 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_STATEIMAGEMASK);
3079 DoGetItem(&tvItem);
3080
3081 // state images are one-based
3082 return STATEIMAGEMASKTOINDEX(tvItem.state) - 1;
3083 }
3084
3085 void wxTreeCtrl::DoSetItemState(const wxTreeItemId& item, int state)
3086 {
3087 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
3088
3089 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_STATEIMAGEMASK);
3090
3091 // state images are one-based
3092 // 0 if no state image display (wxTREE_ITEMSTATE_NONE = -1)
3093 tvItem.state = INDEXTOSTATEIMAGEMASK(state + 1);
3094
3095 DoSetItem(&tvItem);
3096 }
3097
3098 #endif // wxUSE_TREECTRL