]> git.saurik.com Git - wxWidgets.git/blob - src/msw/treectrl.cpp
Test header and renderer aligment separately, II
[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
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.
758 #if 0
759 if ( m_windowStyle & wxTR_MULTIPLE )
760 {
761 wxBitmap bmp;
762
763 // create the DC compatible with the current screen
764 HDC hdcMem = CreateCompatibleDC(NULL);
765
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);
775
776 // then draw a check mark into it
777 RECT rect = { 0, 0, x, y };
778 if ( !::DrawFrameControl(hdcMem, &rect,
779 DFC_BUTTON,
780 DFCS_BUTTONCHECK | DFCS_CHECKED) )
781 {
782 wxLogLastError(wxT("DrawFrameControl(check)"));
783 }
784
785 bmp.SetHBITMAP((WXHBITMAP)hbmpCheck);
786 imagelistCheckboxes.Add(bmp);
787
788 if ( !::DrawFrameControl(hdcMem, &rect,
789 DFC_BUTTON,
790 DFCS_BUTTONCHECK) )
791 {
792 wxLogLastError(wxT("DrawFrameControl(uncheck)"));
793 }
794
795 bmp.SetHBITMAP((WXHBITMAP)hbmpCheck);
796 imagelistCheckboxes.Add(bmp);
797
798 // clean up
799 ::DeleteDC(hdcMem);
800
801 // set the imagelist
802 SetStateImageList(&imagelistCheckboxes);
803 }
804 #endif // 0
805
806 wxSetCCUnicodeFormat(GetHwnd());
807
808 return true;
809 }
810
811 wxTreeCtrl::~wxTreeCtrl()
812 {
813 // delete any attributes
814 if ( m_hasAnyAttr )
815 {
816 WX_CLEAR_HASH_MAP(wxMapTreeAttr, m_attrs);
817
818 // prevent TVN_DELETEITEM handler from deleting the attributes again!
819 m_hasAnyAttr = false;
820 }
821
822 DeleteTextCtrl();
823
824 // delete user data to prevent memory leaks
825 // also deletes hidden root node storage.
826 DeleteAllItems();
827 }
828
829 // ----------------------------------------------------------------------------
830 // accessors
831 // ----------------------------------------------------------------------------
832
833 /* static */ wxVisualAttributes
834 wxTreeCtrl::GetClassDefaultAttributes(wxWindowVariant variant)
835 {
836 wxVisualAttributes attrs = GetCompositeControlsDefaultAttributes(variant);
837
838 // common controls have their own default font
839 attrs.font = wxGetCCDefaultFont();
840
841 return attrs;
842 }
843
844
845 // simple wrappers which add error checking in debug mode
846
847 bool wxTreeCtrl::DoGetItem(wxTreeViewItem *tvItem) const
848 {
849 wxCHECK_MSG( tvItem->hItem != TVI_ROOT, false,
850 _T("can't retrieve virtual root item") );
851
852 if ( !TreeView_GetItem(GetHwnd(), tvItem) )
853 {
854 wxLogLastError(wxT("TreeView_GetItem"));
855
856 return false;
857 }
858
859 return true;
860 }
861
862 void wxTreeCtrl::DoSetItem(wxTreeViewItem *tvItem)
863 {
864 TreeItemUnlocker unlocker(tvItem->hItem);
865
866 if ( TreeView_SetItem(GetHwnd(), tvItem) == -1 )
867 {
868 wxLogLastError(wxT("TreeView_SetItem"));
869 }
870 }
871
872 unsigned int wxTreeCtrl::GetCount() const
873 {
874 return (unsigned int)TreeView_GetCount(GetHwnd());
875 }
876
877 unsigned int wxTreeCtrl::GetIndent() const
878 {
879 return TreeView_GetIndent(GetHwnd());
880 }
881
882 void wxTreeCtrl::SetIndent(unsigned int indent)
883 {
884 TreeView_SetIndent(GetHwnd(), indent);
885 }
886
887 void wxTreeCtrl::SetAnyImageList(wxImageList *imageList, int which)
888 {
889 // no error return
890 (void) TreeView_SetImageList(GetHwnd(),
891 imageList ? imageList->GetHIMAGELIST() : 0,
892 which);
893 }
894
895 void wxTreeCtrl::SetImageList(wxImageList *imageList)
896 {
897 if (m_ownsImageListNormal)
898 delete m_imageListNormal;
899
900 SetAnyImageList(m_imageListNormal = imageList, TVSIL_NORMAL);
901 m_ownsImageListNormal = false;
902 }
903
904 void wxTreeCtrl::SetStateImageList(wxImageList *imageList)
905 {
906 if (m_ownsImageListState) delete m_imageListState;
907 SetAnyImageList(m_imageListState = imageList, TVSIL_STATE);
908 m_ownsImageListState = false;
909 }
910
911 size_t wxTreeCtrl::GetChildrenCount(const wxTreeItemId& item,
912 bool recursively) const
913 {
914 wxCHECK_MSG( item.IsOk(), 0u, wxT("invalid tree item") );
915
916 TraverseCounter counter(this, item, recursively);
917 return counter.GetCount() - 1;
918 }
919
920 // ----------------------------------------------------------------------------
921 // control colours
922 // ----------------------------------------------------------------------------
923
924 bool wxTreeCtrl::SetBackgroundColour(const wxColour &colour)
925 {
926 #if !wxUSE_COMCTL32_SAFELY
927 if ( !wxWindowBase::SetBackgroundColour(colour) )
928 return false;
929
930 ::SendMessage(GetHwnd(), TVM_SETBKCOLOR, 0, colour.GetPixel());
931 #endif
932
933 return true;
934 }
935
936 bool wxTreeCtrl::SetForegroundColour(const wxColour &colour)
937 {
938 #if !wxUSE_COMCTL32_SAFELY
939 if ( !wxWindowBase::SetForegroundColour(colour) )
940 return false;
941
942 ::SendMessage(GetHwnd(), TVM_SETTEXTCOLOR, 0, colour.GetPixel());
943 #endif
944
945 return true;
946 }
947
948 // ----------------------------------------------------------------------------
949 // Item access
950 // ----------------------------------------------------------------------------
951
952 bool wxTreeCtrl::IsHiddenRoot(const wxTreeItemId& item) const
953 {
954 return HITEM(item) == TVI_ROOT && HasFlag(wxTR_HIDE_ROOT);
955 }
956
957 wxString wxTreeCtrl::GetItemText(const wxTreeItemId& item) const
958 {
959 wxCHECK_MSG( item.IsOk(), wxEmptyString, wxT("invalid tree item") );
960
961 wxChar buf[512]; // the size is arbitrary...
962
963 wxTreeViewItem tvItem(item, TVIF_TEXT);
964 tvItem.pszText = buf;
965 tvItem.cchTextMax = WXSIZEOF(buf);
966 if ( !DoGetItem(&tvItem) )
967 {
968 // don't return some garbage which was on stack, but an empty string
969 buf[0] = wxT('\0');
970 }
971
972 return wxString(buf);
973 }
974
975 void wxTreeCtrl::SetItemText(const wxTreeItemId& item, const wxString& text)
976 {
977 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
978
979 if ( IS_VIRTUAL_ROOT(item) )
980 return;
981
982 wxTreeViewItem tvItem(item, TVIF_TEXT);
983 tvItem.pszText = (wxChar *)text.wx_str(); // conversion is ok
984 DoSetItem(&tvItem);
985
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
989 //
990 // don't use GetEditControl() here because m_textCtrl is not set yet
991 HWND hwndEdit = TreeView_GetEditControl(GetHwnd());
992 if ( hwndEdit )
993 {
994 if ( item == m_idEdited )
995 {
996 ::SetWindowText(hwndEdit, text.wx_str());
997 }
998 }
999 }
1000
1001 int wxTreeCtrl::GetItemImage(const wxTreeItemId& item,
1002 wxTreeItemIcon which) const
1003 {
1004 wxCHECK_MSG( item.IsOk(), -1, wxT("invalid tree item") );
1005
1006 if ( IsHiddenRoot(item) )
1007 {
1008 // no images for hidden root item
1009 return -1;
1010 }
1011
1012 wxTreeItemParam *param = GetItemParam(item);
1013
1014 return param && param->HasImage(which) ? param->GetImage(which) : -1;
1015 }
1016
1017 void wxTreeCtrl::SetItemImage(const wxTreeItemId& item, int image,
1018 wxTreeItemIcon which)
1019 {
1020 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1021 wxCHECK_RET( which >= 0 &&
1022 which < wxTreeItemIcon_Max,
1023 wxT("invalid image index"));
1024
1025
1026 if ( IsHiddenRoot(item) )
1027 {
1028 // no images for hidden root item
1029 return;
1030 }
1031
1032 wxTreeItemParam *data = GetItemParam(item);
1033 if ( !data )
1034 return;
1035
1036 data->SetImage(image, which);
1037
1038 RefreshItem(item);
1039 }
1040
1041 wxTreeItemParam *wxTreeCtrl::GetItemParam(const wxTreeItemId& item) const
1042 {
1043 wxCHECK_MSG( item.IsOk(), NULL, wxT("invalid tree item") );
1044
1045 wxTreeViewItem tvItem(item, TVIF_PARAM);
1046
1047 // hidden root may still have data.
1048 if ( IS_VIRTUAL_ROOT(item) )
1049 {
1050 return GET_VIRTUAL_ROOT()->GetParam();
1051 }
1052
1053 // visible node.
1054 if ( !DoGetItem(&tvItem) )
1055 {
1056 return NULL;
1057 }
1058
1059 return (wxTreeItemParam *)tvItem.lParam;
1060 }
1061
1062 wxTreeItemData *wxTreeCtrl::GetItemData(const wxTreeItemId& item) const
1063 {
1064 wxTreeItemParam *data = GetItemParam(item);
1065
1066 return data ? data->GetData() : NULL;
1067 }
1068
1069 void wxTreeCtrl::SetItemData(const wxTreeItemId& item, wxTreeItemData *data)
1070 {
1071 // first, associate this piece of data with this item
1072 if ( data )
1073 {
1074 data->SetId(item);
1075 }
1076
1077 wxTreeItemParam *param = GetItemParam(item);
1078
1079 wxCHECK_RET( param, wxT("failed to change tree items data") );
1080
1081 param->SetData(data);
1082 }
1083
1084 void wxTreeCtrl::SetItemHasChildren(const wxTreeItemId& item, bool has)
1085 {
1086 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1087
1088 if ( IS_VIRTUAL_ROOT(item) )
1089 return;
1090
1091 wxTreeViewItem tvItem(item, TVIF_CHILDREN);
1092 tvItem.cChildren = (int)has;
1093 DoSetItem(&tvItem);
1094 }
1095
1096 void wxTreeCtrl::SetItemBold(const wxTreeItemId& item, bool bold)
1097 {
1098 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1099
1100 if ( IS_VIRTUAL_ROOT(item) )
1101 return;
1102
1103 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_BOLD);
1104 tvItem.state = bold ? TVIS_BOLD : 0;
1105 DoSetItem(&tvItem);
1106 }
1107
1108 void wxTreeCtrl::SetItemDropHighlight(const wxTreeItemId& item, bool highlight)
1109 {
1110 if ( IS_VIRTUAL_ROOT(item) )
1111 return;
1112
1113 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_DROPHILITED);
1114 tvItem.state = highlight ? TVIS_DROPHILITED : 0;
1115 DoSetItem(&tvItem);
1116 }
1117
1118 void wxTreeCtrl::RefreshItem(const wxTreeItemId& item)
1119 {
1120 if ( IS_VIRTUAL_ROOT(item) )
1121 return;
1122
1123 wxRect rect;
1124 if ( GetBoundingRect(item, rect) )
1125 {
1126 RefreshRect(rect);
1127 }
1128 }
1129
1130 wxColour wxTreeCtrl::GetItemTextColour(const wxTreeItemId& item) const
1131 {
1132 wxCHECK_MSG( item.IsOk(), wxNullColour, wxT("invalid tree item") );
1133
1134 wxMapTreeAttr::const_iterator it = m_attrs.find(item.m_pItem);
1135 return it == m_attrs.end() ? wxNullColour : it->second->GetTextColour();
1136 }
1137
1138 wxColour wxTreeCtrl::GetItemBackgroundColour(const wxTreeItemId& item) const
1139 {
1140 wxCHECK_MSG( item.IsOk(), wxNullColour, wxT("invalid tree item") );
1141
1142 wxMapTreeAttr::const_iterator it = m_attrs.find(item.m_pItem);
1143 return it == m_attrs.end() ? wxNullColour : it->second->GetBackgroundColour();
1144 }
1145
1146 wxFont wxTreeCtrl::GetItemFont(const wxTreeItemId& item) const
1147 {
1148 wxCHECK_MSG( item.IsOk(), wxNullFont, wxT("invalid tree item") );
1149
1150 wxMapTreeAttr::const_iterator it = m_attrs.find(item.m_pItem);
1151 return it == m_attrs.end() ? wxNullFont : it->second->GetFont();
1152 }
1153
1154 void wxTreeCtrl::SetItemTextColour(const wxTreeItemId& item,
1155 const wxColour& col)
1156 {
1157 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1158
1159 wxTreeItemAttr *attr;
1160 wxMapTreeAttr::iterator it = m_attrs.find(item.m_pItem);
1161 if ( it == m_attrs.end() )
1162 {
1163 m_hasAnyAttr = true;
1164
1165 m_attrs[item.m_pItem] =
1166 attr = new wxTreeItemAttr;
1167 }
1168 else
1169 {
1170 attr = it->second;
1171 }
1172
1173 attr->SetTextColour(col);
1174
1175 RefreshItem(item);
1176 }
1177
1178 void wxTreeCtrl::SetItemBackgroundColour(const wxTreeItemId& item,
1179 const wxColour& col)
1180 {
1181 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1182
1183 wxTreeItemAttr *attr;
1184 wxMapTreeAttr::iterator it = m_attrs.find(item.m_pItem);
1185 if ( it == m_attrs.end() )
1186 {
1187 m_hasAnyAttr = true;
1188
1189 m_attrs[item.m_pItem] =
1190 attr = new wxTreeItemAttr;
1191 }
1192 else // already in the hash
1193 {
1194 attr = it->second;
1195 }
1196
1197 attr->SetBackgroundColour(col);
1198
1199 RefreshItem(item);
1200 }
1201
1202 void wxTreeCtrl::SetItemFont(const wxTreeItemId& item, const wxFont& font)
1203 {
1204 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1205
1206 wxTreeItemAttr *attr;
1207 wxMapTreeAttr::iterator it = m_attrs.find(item.m_pItem);
1208 if ( it == m_attrs.end() )
1209 {
1210 m_hasAnyAttr = true;
1211
1212 m_attrs[item.m_pItem] =
1213 attr = new wxTreeItemAttr;
1214 }
1215 else // already in the hash
1216 {
1217 attr = it->second;
1218 }
1219
1220 attr->SetFont(font);
1221
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));
1225
1226 RefreshItem(item);
1227 }
1228
1229 // ----------------------------------------------------------------------------
1230 // Item status
1231 // ----------------------------------------------------------------------------
1232
1233 bool wxTreeCtrl::IsVisible(const wxTreeItemId& item) const
1234 {
1235 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1236
1237 if ( item == wxTreeItemId(TVI_ROOT) )
1238 {
1239 // virtual (hidden) root is never visible
1240 return false;
1241 }
1242
1243 // Bug in Gnu-Win32 headers, so don't use the macro TreeView_GetItemRect
1244 RECT rect;
1245
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);
1249
1250 // true means to get rect for just the text, not the whole line
1251 if ( !::SendMessage(GetHwnd(), TVM_GETITEMRECT, true, (LPARAM)&rect) )
1252 {
1253 // if TVM_GETITEMRECT returned false, then the item is definitely not
1254 // visible (because its parent is not expanded)
1255 return false;
1256 }
1257
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;
1262 }
1263
1264 bool wxTreeCtrl::ItemHasChildren(const wxTreeItemId& item) const
1265 {
1266 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1267
1268 wxTreeViewItem tvItem(item, TVIF_CHILDREN);
1269 DoGetItem(&tvItem);
1270
1271 return tvItem.cChildren != 0;
1272 }
1273
1274 bool wxTreeCtrl::IsExpanded(const wxTreeItemId& item) const
1275 {
1276 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1277
1278 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_EXPANDED);
1279 DoGetItem(&tvItem);
1280
1281 return (tvItem.state & TVIS_EXPANDED) != 0;
1282 }
1283
1284 bool wxTreeCtrl::IsSelected(const wxTreeItemId& item) const
1285 {
1286 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1287
1288 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_SELECTED);
1289 DoGetItem(&tvItem);
1290
1291 return (tvItem.state & TVIS_SELECTED) != 0;
1292 }
1293
1294 bool wxTreeCtrl::IsBold(const wxTreeItemId& item) const
1295 {
1296 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1297
1298 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_BOLD);
1299 DoGetItem(&tvItem);
1300
1301 return (tvItem.state & TVIS_BOLD) != 0;
1302 }
1303
1304 // ----------------------------------------------------------------------------
1305 // navigation
1306 // ----------------------------------------------------------------------------
1307
1308 wxTreeItemId wxTreeCtrl::GetRootItem() const
1309 {
1310 // Root may be real (visible) or virtual (hidden).
1311 if ( GET_VIRTUAL_ROOT() )
1312 return TVI_ROOT;
1313
1314 return wxTreeItemId(TreeView_GetRoot(GetHwnd()));
1315 }
1316
1317 wxTreeItemId wxTreeCtrl::GetSelection() const
1318 {
1319 wxCHECK_MSG( !(m_windowStyle & wxTR_MULTIPLE), wxTreeItemId(),
1320 wxT("this only works with single selection controls") );
1321
1322 return wxTreeItemId(TreeView_GetSelection(GetHwnd()));
1323 }
1324
1325 wxTreeItemId wxTreeCtrl::GetItemParent(const wxTreeItemId& item) const
1326 {
1327 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1328
1329 HTREEITEM hItem;
1330
1331 if ( IS_VIRTUAL_ROOT(item) )
1332 {
1333 // no parent for the virtual root
1334 hItem = 0;
1335 }
1336 else // normal item
1337 {
1338 hItem = TreeView_GetParent(GetHwnd(), HITEM(item));
1339 if ( !hItem && HasFlag(wxTR_HIDE_ROOT) )
1340 {
1341 // the top level items should have the virtual root as their parent
1342 hItem = TVI_ROOT;
1343 }
1344 }
1345
1346 return wxTreeItemId(hItem);
1347 }
1348
1349 wxTreeItemId wxTreeCtrl::GetFirstChild(const wxTreeItemId& item,
1350 wxTreeItemIdValue& cookie) const
1351 {
1352 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1353
1354 // remember the last child returned in 'cookie'
1355 cookie = TreeView_GetChild(GetHwnd(), HITEM(item));
1356
1357 return wxTreeItemId(cookie);
1358 }
1359
1360 wxTreeItemId wxTreeCtrl::GetNextChild(const wxTreeItemId& WXUNUSED(item),
1361 wxTreeItemIdValue& cookie) const
1362 {
1363 wxTreeItemId fromCookie(cookie);
1364
1365 HTREEITEM hitem = HITEM(fromCookie);
1366
1367 hitem = TreeView_GetNextSibling(GetHwnd(), hitem);
1368
1369 wxTreeItemId item(hitem);
1370
1371 cookie = item.m_pItem;
1372
1373 return item;
1374 }
1375
1376 wxTreeItemId wxTreeCtrl::GetLastChild(const wxTreeItemId& item) const
1377 {
1378 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1379
1380 // can this be done more efficiently?
1381 wxTreeItemIdValue cookie;
1382
1383 wxTreeItemId childLast,
1384 child = GetFirstChild(item, cookie);
1385 while ( child.IsOk() )
1386 {
1387 childLast = child;
1388 child = GetNextChild(item, cookie);
1389 }
1390
1391 return childLast;
1392 }
1393
1394 wxTreeItemId wxTreeCtrl::GetNextSibling(const wxTreeItemId& item) const
1395 {
1396 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1397 return wxTreeItemId(TreeView_GetNextSibling(GetHwnd(), HITEM(item)));
1398 }
1399
1400 wxTreeItemId wxTreeCtrl::GetPrevSibling(const wxTreeItemId& item) const
1401 {
1402 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1403 return wxTreeItemId(TreeView_GetPrevSibling(GetHwnd(), HITEM(item)));
1404 }
1405
1406 wxTreeItemId wxTreeCtrl::GetFirstVisibleItem() const
1407 {
1408 return wxTreeItemId(TreeView_GetFirstVisible(GetHwnd()));
1409 }
1410
1411 wxTreeItemId wxTreeCtrl::GetNextVisible(const wxTreeItemId& item) const
1412 {
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!"));
1415
1416 wxTreeItemId next(TreeView_GetNextVisible(GetHwnd(), HITEM(item)));
1417 if ( next.IsOk() && !IsVisible(next) )
1418 {
1419 // Win32 considers that any non-collapsed item is visible while we want
1420 // to return only really visible items
1421 next.Unset();
1422 }
1423
1424 return next;
1425 }
1426
1427 wxTreeItemId wxTreeCtrl::GetPrevVisible(const wxTreeItemId& item) const
1428 {
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!"));
1431
1432 wxTreeItemId prev(TreeView_GetPrevVisible(GetHwnd(), HITEM(item)));
1433 if ( prev.IsOk() && !IsVisible(prev) )
1434 {
1435 // just as above, Win32 function will happily return the previous item
1436 // in the tree for the first visible item too
1437 prev.Unset();
1438 }
1439
1440 return prev;
1441 }
1442
1443 // ----------------------------------------------------------------------------
1444 // multiple selections emulation
1445 // ----------------------------------------------------------------------------
1446
1447 bool wxTreeCtrl::IsItemChecked(const wxTreeItemId& item) const
1448 {
1449 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1450
1451 // receive the desired information.
1452 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_STATEIMAGEMASK);
1453 DoGetItem(&tvItem);
1454
1455 // state image indices are 1 based
1456 return ((tvItem.state >> 12) - 1) == 1;
1457 }
1458
1459 void wxTreeCtrl::SetItemCheck(const wxTreeItemId& item, bool check)
1460 {
1461 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1462
1463 // receive the desired information.
1464 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_STATEIMAGEMASK);
1465
1466 DoGetItem(&tvItem);
1467
1468 // state images are one-based
1469 tvItem.state = (check ? 2 : 1) << 12;
1470
1471 DoSetItem(&tvItem);
1472 }
1473
1474 size_t wxTreeCtrl::GetSelections(wxArrayTreeItemIds& selections) const
1475 {
1476 TraverseSelections selector(this, selections);
1477
1478 return selector.GetCount();
1479 }
1480
1481 // ----------------------------------------------------------------------------
1482 // Usual operations
1483 // ----------------------------------------------------------------------------
1484
1485 wxTreeItemId wxTreeCtrl::DoInsertAfter(const wxTreeItemId& parent,
1486 const wxTreeItemId& hInsertAfter,
1487 const wxString& text,
1488 int image, int selectedImage,
1489 wxTreeItemData *data)
1490 {
1491 wxCHECK_MSG( parent.IsOk() || !TreeView_GetRoot(GetHwnd()),
1492 wxTreeItemId(),
1493 _T("can't have more than one root in the tree") );
1494
1495 TV_INSERTSTRUCT tvIns;
1496 tvIns.hParent = HITEM(parent);
1497 tvIns.hInsertAfter = HITEM(hInsertAfter);
1498
1499 // this is how we insert the item as the first child: supply a NULL
1500 // hInsertAfter
1501 if ( !tvIns.hInsertAfter )
1502 {
1503 tvIns.hInsertAfter = TVI_FIRST;
1504 }
1505
1506 UINT mask = 0;
1507 if ( !text.empty() )
1508 {
1509 mask |= TVIF_TEXT;
1510 tvIns.item.pszText = (wxChar *)text.wx_str(); // cast is ok
1511 }
1512 else
1513 {
1514 tvIns.item.pszText = NULL;
1515 tvIns.item.cchTextMax = 0;
1516 }
1517
1518 // create the param which will store the other item parameters
1519 wxTreeItemParam *param = new wxTreeItemParam;
1520
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;
1526
1527 param->SetImage(image, wxTreeItemIcon_Normal);
1528 param->SetImage(selectedImage, wxTreeItemIcon_Selected);
1529
1530 mask |= TVIF_PARAM;
1531 tvIns.item.lParam = (LPARAM)param;
1532 tvIns.item.mask = mask;
1533
1534 const bool firstChild = !TreeView_GetChild(GetHwnd(), HITEM(parent));
1535
1536 HTREEITEM id = TreeView_InsertItem(GetHwnd(), &tvIns);
1537 if ( id == 0 )
1538 {
1539 wxLogLastError(wxT("TreeView_InsertItem"));
1540 }
1541
1542 // apparently some Windows versions (2000 and XP are reported to do this)
1543 // sometimes don't refresh the tree after adding the first child and so we
1544 // need this to make the "[+]" appear
1545 if ( firstChild )
1546 {
1547 RECT rect;
1548 TreeView_GetItemRect(GetHwnd(), HITEM(parent), &rect, FALSE);
1549 ::InvalidateRect(GetHwnd(), &rect, FALSE);
1550 }
1551
1552 // associate the application tree item with Win32 tree item handle
1553 param->SetItem(id);
1554
1555 // setup wxTreeItemData
1556 if ( data != NULL )
1557 {
1558 param->SetData(data);
1559 data->SetId(id);
1560 }
1561
1562 return wxTreeItemId(id);
1563 }
1564
1565 wxTreeItemId wxTreeCtrl::AddRoot(const wxString& text,
1566 int image, int selectedImage,
1567 wxTreeItemData *data)
1568 {
1569 if ( HasFlag(wxTR_HIDE_ROOT) )
1570 {
1571 wxASSERT_MSG( !m_pVirtualRoot, _T("tree can have only a single root") );
1572
1573 // create a virtual root item, the parent for all the others
1574 wxTreeItemParam *param = new wxTreeItemParam;
1575 param->SetData(data);
1576
1577 m_pVirtualRoot = new wxVirtualNode(param);
1578
1579 return TVI_ROOT;
1580 }
1581
1582 return DoInsertAfter(wxTreeItemId(), wxTreeItemId(),
1583 text, image, selectedImage, data);
1584 }
1585
1586 wxTreeItemId wxTreeCtrl::DoInsertItem(const wxTreeItemId& parent,
1587 size_t index,
1588 const wxString& text,
1589 int image, int selectedImage,
1590 wxTreeItemData *data)
1591 {
1592 wxTreeItemId idPrev;
1593 if ( index == (size_t)-1 )
1594 {
1595 // special value: append to the end
1596 idPrev = TVI_LAST;
1597 }
1598 else // find the item from index
1599 {
1600 wxTreeItemIdValue cookie;
1601 wxTreeItemId idCur = GetFirstChild(parent, cookie);
1602 while ( index != 0 && idCur.IsOk() )
1603 {
1604 index--;
1605
1606 idPrev = idCur;
1607 idCur = GetNextChild(parent, cookie);
1608 }
1609
1610 // assert, not check: if the index is invalid, we will append the item
1611 // to the end
1612 wxASSERT_MSG( index == 0, _T("bad index in wxTreeCtrl::InsertItem") );
1613 }
1614
1615 return DoInsertAfter(parent, idPrev, text, image, selectedImage, data);
1616 }
1617
1618 void wxTreeCtrl::Delete(const wxTreeItemId& item)
1619 {
1620 // unlock tree selections on vista, without this the
1621 // tree ctrl will eventually crash after item deletion
1622 TreeItemUnlocker unlock_all;
1623
1624 if ( !TreeView_DeleteItem(GetHwnd(), HITEM(item)) )
1625 {
1626 wxLogLastError(wxT("TreeView_DeleteItem"));
1627 }
1628 }
1629
1630 // delete all children (but don't delete the item itself)
1631 void wxTreeCtrl::DeleteChildren(const wxTreeItemId& item)
1632 {
1633 // unlock tree selections on vista for the duration of this call
1634 TreeItemUnlocker unlock_all;
1635
1636 wxTreeItemIdValue cookie;
1637
1638 wxArrayTreeItemIds children;
1639 wxTreeItemId child = GetFirstChild(item, cookie);
1640 while ( child.IsOk() )
1641 {
1642 children.Add(child);
1643
1644 child = GetNextChild(item, cookie);
1645 }
1646
1647 size_t nCount = children.Count();
1648 for ( size_t n = 0; n < nCount; n++ )
1649 {
1650 if ( !TreeView_DeleteItem(GetHwnd(), HITEM(children[n])) )
1651 {
1652 wxLogLastError(wxT("TreeView_DeleteItem"));
1653 }
1654 }
1655 }
1656
1657 void wxTreeCtrl::DeleteAllItems()
1658 {
1659 // unlock tree selections on vista for the duration of this call
1660 TreeItemUnlocker unlock_all;
1661
1662 // delete the "virtual" root item.
1663 if ( GET_VIRTUAL_ROOT() )
1664 {
1665 delete GET_VIRTUAL_ROOT();
1666 m_pVirtualRoot = NULL;
1667 }
1668
1669 // and all the real items
1670
1671 if ( !TreeView_DeleteAllItems(GetHwnd()) )
1672 {
1673 wxLogLastError(wxT("TreeView_DeleteAllItems"));
1674 }
1675 }
1676
1677 void wxTreeCtrl::DoExpand(const wxTreeItemId& item, int flag)
1678 {
1679 wxASSERT_MSG( flag == TVE_COLLAPSE ||
1680 flag == (TVE_COLLAPSE | TVE_COLLAPSERESET) ||
1681 flag == TVE_EXPAND ||
1682 flag == TVE_TOGGLE,
1683 wxT("Unknown flag in wxTreeCtrl::DoExpand") );
1684
1685 // A hidden root can be neither expanded nor collapsed.
1686 wxCHECK_RET( !IsHiddenRoot(item),
1687 wxT("Can't expand/collapse hidden root node!") );
1688
1689 // TreeView_Expand doesn't send TVN_ITEMEXPAND(ING) messages, so we must
1690 // emulate them. This behaviour has changed slightly with comctl32.dll
1691 // v 4.70 - now it does send them but only the first time. To maintain
1692 // compatible behaviour and also in order to not have surprises with the
1693 // future versions, don't rely on this and still do everything ourselves.
1694 // To avoid that the messages be sent twice when the item is expanded for
1695 // the first time we must clear TVIS_EXPANDEDONCE style manually.
1696
1697 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_EXPANDEDONCE);
1698 tvItem.state = 0;
1699 DoSetItem(&tvItem);
1700
1701 if ( TreeView_Expand(GetHwnd(), HITEM(item), flag) != 0 )
1702 {
1703 // note that the {EXPAND|COLLAPS}ING event is sent by TreeView_Expand()
1704 // itself
1705 wxTreeEvent event(gs_expandEvents[IsExpanded(item) ? IDX_EXPAND
1706 : IDX_COLLAPSE]
1707 [IDX_DONE],
1708 this, item);
1709 (void)HandleWindowEvent(event);
1710 }
1711 //else: change didn't took place, so do nothing at all
1712 }
1713
1714 void wxTreeCtrl::Expand(const wxTreeItemId& item)
1715 {
1716 DoExpand(item, TVE_EXPAND);
1717 }
1718
1719 void wxTreeCtrl::Collapse(const wxTreeItemId& item)
1720 {
1721 DoExpand(item, TVE_COLLAPSE);
1722 }
1723
1724 void wxTreeCtrl::CollapseAndReset(const wxTreeItemId& item)
1725 {
1726 DoExpand(item, TVE_COLLAPSE | TVE_COLLAPSERESET);
1727 }
1728
1729 void wxTreeCtrl::Toggle(const wxTreeItemId& item)
1730 {
1731 DoExpand(item, TVE_TOGGLE);
1732 }
1733
1734 void wxTreeCtrl::Unselect()
1735 {
1736 wxASSERT_MSG( !(m_windowStyle & wxTR_MULTIPLE),
1737 wxT("doesn't make sense, may be you want UnselectAll()?") );
1738
1739 // just remove the selection
1740 SelectItem(wxTreeItemId());
1741 }
1742
1743 void wxTreeCtrl::UnselectAll()
1744 {
1745 if ( m_windowStyle & wxTR_MULTIPLE )
1746 {
1747 wxArrayTreeItemIds selections;
1748 size_t count = GetSelections(selections);
1749 for ( size_t n = 0; n < count; n++ )
1750 {
1751 ::UnselectItem(GetHwnd(), HITEM(selections[n]));
1752 }
1753
1754 m_htSelStart.Unset();
1755 }
1756 else
1757 {
1758 // just remove the selection
1759 Unselect();
1760 }
1761 }
1762
1763 void wxTreeCtrl::SelectItem(const wxTreeItemId& item, bool select)
1764 {
1765 wxCHECK_RET( !IsHiddenRoot(item), _T("can't select hidden root item") );
1766
1767 wxASSERT_MSG( select || HasFlag(wxTR_MULTIPLE),
1768 _T("SelectItem(false) works only for multiselect") );
1769
1770 wxTreeEvent event(wxEVT_COMMAND_TREE_SEL_CHANGING, this, item);
1771 if ( !HandleWindowEvent(event) || event.IsAllowed() )
1772 {
1773 if ( HasFlag(wxTR_MULTIPLE) )
1774 {
1775 if ( !::SelectItem(GetHwnd(), HITEM(item), select) )
1776 {
1777 wxLogLastError(wxT("TreeView_SelectItem"));
1778 return;
1779 }
1780 }
1781 else // single selection
1782 {
1783 // use TreeView_SelectItem() to deselect the previous selection
1784 if ( !TreeView_SelectItem(GetHwnd(), HITEM(item)) )
1785 {
1786 wxLogLastError(wxT("TreeView_SelectItem"));
1787 return;
1788 }
1789 }
1790
1791 event.SetEventType(wxEVT_COMMAND_TREE_SEL_CHANGED);
1792 (void)HandleWindowEvent(event);
1793 }
1794 //else: program vetoed the change
1795 }
1796
1797 void wxTreeCtrl::EnsureVisible(const wxTreeItemId& item)
1798 {
1799 wxCHECK_RET( !IsHiddenRoot(item), _T("can't show hidden root item") );
1800
1801 // no error return
1802 TreeView_EnsureVisible(GetHwnd(), HITEM(item));
1803 }
1804
1805 void wxTreeCtrl::ScrollTo(const wxTreeItemId& item)
1806 {
1807 if ( !TreeView_SelectSetFirstVisible(GetHwnd(), HITEM(item)) )
1808 {
1809 wxLogLastError(wxT("TreeView_SelectSetFirstVisible"));
1810 }
1811 }
1812
1813 wxTextCtrl *wxTreeCtrl::GetEditControl() const
1814 {
1815 return m_textCtrl;
1816 }
1817
1818 void wxTreeCtrl::DeleteTextCtrl()
1819 {
1820 if ( m_textCtrl )
1821 {
1822 // the HWND corresponding to this control is deleted by the tree
1823 // control itself and we don't know when exactly this happens, so check
1824 // if the window still exists before calling UnsubclassWin()
1825 if ( !::IsWindow(GetHwndOf(m_textCtrl)) )
1826 {
1827 m_textCtrl->SetHWND(0);
1828 }
1829
1830 m_textCtrl->UnsubclassWin();
1831 m_textCtrl->SetHWND(0);
1832 delete m_textCtrl;
1833 m_textCtrl = NULL;
1834
1835 m_idEdited.Unset();
1836 }
1837 }
1838
1839 wxTextCtrl *wxTreeCtrl::EditLabel(const wxTreeItemId& item,
1840 wxClassInfo *textControlClass)
1841 {
1842 wxASSERT( textControlClass->IsKindOf(CLASSINFO(wxTextCtrl)) );
1843
1844 DeleteTextCtrl();
1845
1846 m_idEdited = item;
1847 m_textCtrl = (wxTextCtrl *)textControlClass->CreateObject();
1848 HWND hWnd = (HWND) TreeView_EditLabel(GetHwnd(), HITEM(item));
1849
1850 // this is not an error - the TVN_BEGINLABELEDIT handler might have
1851 // returned false
1852 if ( !hWnd )
1853 {
1854 delete m_textCtrl;
1855 m_textCtrl = NULL;
1856 return NULL;
1857 }
1858
1859 // textctrl is subclassed in MSWOnNotify
1860 return m_textCtrl;
1861 }
1862
1863 // End label editing, optionally cancelling the edit
1864 void wxTreeCtrl::DoEndEditLabel(bool discardChanges)
1865 {
1866 TreeView_EndEditLabelNow(GetHwnd(), discardChanges);
1867
1868 DeleteTextCtrl();
1869 }
1870
1871 wxTreeItemId wxTreeCtrl::DoTreeHitTest(const wxPoint& point, int& flags) const
1872 {
1873 TV_HITTESTINFO hitTestInfo;
1874 hitTestInfo.pt.x = (int)point.x;
1875 hitTestInfo.pt.y = (int)point.y;
1876
1877 (void) TreeView_HitTest(GetHwnd(), &hitTestInfo);
1878
1879 flags = 0;
1880
1881 // avoid repetition
1882 #define TRANSLATE_FLAG(flag) if ( hitTestInfo.flags & TVHT_##flag ) \
1883 flags |= wxTREE_HITTEST_##flag
1884
1885 TRANSLATE_FLAG(ABOVE);
1886 TRANSLATE_FLAG(BELOW);
1887 TRANSLATE_FLAG(NOWHERE);
1888 TRANSLATE_FLAG(ONITEMBUTTON);
1889 TRANSLATE_FLAG(ONITEMICON);
1890 TRANSLATE_FLAG(ONITEMINDENT);
1891 TRANSLATE_FLAG(ONITEMLABEL);
1892 TRANSLATE_FLAG(ONITEMRIGHT);
1893 TRANSLATE_FLAG(ONITEMSTATEICON);
1894 TRANSLATE_FLAG(TOLEFT);
1895 TRANSLATE_FLAG(TORIGHT);
1896
1897 #undef TRANSLATE_FLAG
1898
1899 return wxTreeItemId(hitTestInfo.hItem);
1900 }
1901
1902 bool wxTreeCtrl::GetBoundingRect(const wxTreeItemId& item,
1903 wxRect& rect,
1904 bool textOnly) const
1905 {
1906 RECT rc;
1907
1908 // Virtual root items have no bounding rectangle
1909 if ( IS_VIRTUAL_ROOT(item) )
1910 {
1911 return false;
1912 }
1913
1914 if ( TreeView_GetItemRect(GetHwnd(), HITEM(item),
1915 &rc, textOnly) )
1916 {
1917 rect = wxRect(wxPoint(rc.left, rc.top), wxPoint(rc.right, rc.bottom));
1918
1919 return true;
1920 }
1921 else
1922 {
1923 // couldn't retrieve rect: for example, item isn't visible
1924 return false;
1925 }
1926 }
1927
1928 // ----------------------------------------------------------------------------
1929 // sorting stuff
1930 // ----------------------------------------------------------------------------
1931
1932 // this is just a tiny namespace which is friend to wxTreeCtrl and so can use
1933 // functions such as IsDataIndirect()
1934 class wxTreeSortHelper
1935 {
1936 public:
1937 static int CALLBACK Compare(LPARAM data1, LPARAM data2, LPARAM tree);
1938
1939 private:
1940 static wxTreeItemId GetIdFromData(LPARAM lParam)
1941 {
1942 return ((wxTreeItemParam*)lParam)->GetItem();
1943 }
1944 };
1945
1946 int CALLBACK wxTreeSortHelper::Compare(LPARAM pItem1,
1947 LPARAM pItem2,
1948 LPARAM htree)
1949 {
1950 wxCHECK_MSG( pItem1 && pItem2, 0,
1951 wxT("sorting tree without data doesn't make sense") );
1952
1953 wxTreeCtrl *tree = (wxTreeCtrl *)htree;
1954
1955 return tree->OnCompareItems(GetIdFromData(pItem1),
1956 GetIdFromData(pItem2));
1957 }
1958
1959 void wxTreeCtrl::SortChildren(const wxTreeItemId& item)
1960 {
1961 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1962
1963 // rely on the fact that TreeView_SortChildren does the same thing as our
1964 // default behaviour, i.e. sorts items alphabetically and so call it
1965 // directly if we're not in derived class (much more efficient!)
1966 // RN: Note that if you find you're code doesn't sort as expected this
1967 // may be why as if you don't use the DECLARE_CLASS/IMPLEMENT_CLASS
1968 // combo for your derived wxTreeCtrl if will sort without
1969 // OnCompareItems
1970 if ( GetClassInfo() == CLASSINFO(wxTreeCtrl) )
1971 {
1972 TreeView_SortChildren(GetHwnd(), HITEM(item), 0);
1973 }
1974 else
1975 {
1976 TV_SORTCB tvSort;
1977 tvSort.hParent = HITEM(item);
1978 tvSort.lpfnCompare = wxTreeSortHelper::Compare;
1979 tvSort.lParam = (LPARAM)this;
1980 TreeView_SortChildrenCB(GetHwnd(), &tvSort, 0 /* reserved */);
1981 }
1982 }
1983
1984 // ----------------------------------------------------------------------------
1985 // implementation
1986 // ----------------------------------------------------------------------------
1987
1988 bool wxTreeCtrl::MSWShouldPreProcessMessage(WXMSG* msg)
1989 {
1990 if ( msg->message == WM_KEYDOWN )
1991 {
1992 // Only eat VK_RETURN if not being used by the application in
1993 // conjunction with modifiers
1994 if ( (msg->wParam == VK_RETURN) && !wxIsAnyModifierDown() )
1995 {
1996 // we need VK_RETURN to generate wxEVT_COMMAND_TREE_ITEM_ACTIVATED
1997 return false;
1998 }
1999 }
2000
2001 return wxTreeCtrlBase::MSWShouldPreProcessMessage(msg);
2002 }
2003
2004 bool wxTreeCtrl::MSWCommand(WXUINT cmd, WXWORD id_)
2005 {
2006 const int id = (signed short)id_;
2007
2008 if ( cmd == EN_UPDATE )
2009 {
2010 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, id);
2011 event.SetEventObject( this );
2012 ProcessCommand(event);
2013 }
2014 else if ( cmd == EN_KILLFOCUS )
2015 {
2016 wxCommandEvent event(wxEVT_KILL_FOCUS, id);
2017 event.SetEventObject( this );
2018 ProcessCommand(event);
2019 }
2020 else
2021 {
2022 // nothing done
2023 return false;
2024 }
2025
2026 // command processed
2027 return true;
2028 }
2029
2030 // we hook into WndProc to process WM_MOUSEMOVE/WM_BUTTONUP messages - as we
2031 // only do it during dragging, minimize wxWin overhead (this is important for
2032 // WM_MOUSEMOVE as they're a lot of them) by catching Windows messages directly
2033 // instead of passing by wxWin events
2034 WXLRESULT wxTreeCtrl::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
2035 {
2036 bool processed = false;
2037 WXLRESULT rc = 0;
2038 bool isMultiple = HasFlag(wxTR_MULTIPLE);
2039
2040 // This message is sent after a right-click, or when the "menu" key is pressed
2041 if ( nMsg == WM_CONTEXTMENU )
2042 {
2043 int x = GET_X_LPARAM(lParam),
2044 y = GET_Y_LPARAM(lParam);
2045
2046 // the item for which the menu should be shown
2047 wxTreeItemId item;
2048
2049 // the position where the menu should be shown in client coordinates
2050 // (so that it can be passed directly to PopupMenu())
2051 wxPoint pt;
2052
2053 if ( x == -1 || y == -1 )
2054 {
2055 // this means that the event was generated from keyboard (e.g. with
2056 // Shift-F10 or special Windows menu key)
2057 //
2058 // use the Explorer standard of putting the menu at the left edge
2059 // of the text, in the vertical middle of the text
2060 item = wxTreeItemId(TreeView_GetSelection(GetHwnd()));
2061 if ( item.IsOk() )
2062 {
2063 // Use the bounding rectangle of only the text part
2064 wxRect rect;
2065 GetBoundingRect(item, rect, true);
2066 pt = wxPoint(rect.GetX(), rect.GetY() + rect.GetHeight() / 2);
2067 }
2068 }
2069 else // event from mouse, use mouse position
2070 {
2071 pt = ScreenToClient(wxPoint(x, y));
2072
2073 TV_HITTESTINFO tvhti;
2074 tvhti.pt.x = pt.x;
2075 tvhti.pt.y = pt.y;
2076 if ( TreeView_HitTest(GetHwnd(), &tvhti) )
2077 item = wxTreeItemId(tvhti.hItem);
2078 }
2079
2080 // create the event
2081 wxTreeEvent event(wxEVT_COMMAND_TREE_ITEM_MENU, this, item);
2082
2083 event.m_pointDrag = pt;
2084
2085 if ( HandleWindowEvent(event) )
2086 processed = true;
2087 //else: continue with generating wxEVT_CONTEXT_MENU in base class code
2088 }
2089 else if ( (nMsg >= WM_MOUSEFIRST) && (nMsg <= WM_MOUSELAST) )
2090 {
2091 // we only process mouse messages here and these parameters have the
2092 // same meaning for all of them
2093 int x = GET_X_LPARAM(lParam),
2094 y = GET_Y_LPARAM(lParam);
2095
2096 TV_HITTESTINFO tvht;
2097 tvht.pt.x = x;
2098 tvht.pt.y = y;
2099
2100 HTREEITEM htItem = TreeView_HitTest(GetHwnd(), &tvht);
2101
2102 switch ( nMsg )
2103 {
2104 case WM_LBUTTONDOWN:
2105 if ( htItem && isMultiple && (tvht.flags & TVHT_ONITEM) != 0 )
2106 {
2107 m_htClickedItem = (WXHTREEITEM) htItem;
2108 m_ptClick = wxPoint(x, y);
2109
2110 if ( wParam & MK_CONTROL )
2111 {
2112 SetFocus();
2113
2114 // toggle selected state
2115 ToggleItemSelection(htItem);
2116
2117 ::SetFocus(GetHwnd(), htItem);
2118
2119 // reset on any click without Shift
2120 m_htSelStart.Unset();
2121
2122 processed = true;
2123 }
2124 else if ( wParam & MK_SHIFT )
2125 {
2126 // this selects all items between the starting one and
2127 // the current
2128
2129 if ( !m_htSelStart )
2130 {
2131 // take the focused item
2132 m_htSelStart = TreeView_GetSelection(GetHwnd());
2133 }
2134
2135 if ( m_htSelStart )
2136 SelectRange(GetHwnd(), HITEM(m_htSelStart), htItem,
2137 !(wParam & MK_CONTROL));
2138 else
2139 ::SelectItem(GetHwnd(), htItem);
2140
2141 ::SetFocus(GetHwnd(), htItem);
2142
2143 processed = true;
2144 }
2145 else // normal click
2146 {
2147 // avoid doing anything if we click on the only
2148 // currently selected item
2149
2150 SetFocus();
2151
2152 wxArrayTreeItemIds selections;
2153 size_t count = GetSelections(selections);
2154 if ( count == 0 ||
2155 count > 1 ||
2156 HITEM(selections[0]) != htItem )
2157 {
2158 // clear the previously selected items, if the
2159 // user clicked outside of the present selection.
2160 // otherwise, perform the deselection on mouse-up.
2161 // this allows multiple drag and drop to work.
2162
2163 if (!IsItemSelected(GetHwnd(), htItem))
2164 {
2165 UnselectAll();
2166
2167 // prevent the click from starting in-place editing
2168 // which should only happen if we click on the
2169 // already selected item (and nothing else is
2170 // selected)
2171
2172 TreeView_SelectItem(GetHwnd(), 0);
2173 ::SelectItem(GetHwnd(), htItem);
2174 }
2175 ::SetFocus(GetHwnd(), htItem);
2176 processed = true;
2177 }
2178 else // click on a single selected item
2179 {
2180 // don't interfere with the default processing in
2181 // WM_MOUSEMOVE handler below as the default window
2182 // proc will start the drag itself if we let have
2183 // WM_LBUTTONDOWN
2184 m_htClickedItem.Unset();
2185 }
2186
2187 // reset on any click without Shift
2188 m_htSelStart.Unset();
2189 }
2190 }
2191 break;
2192
2193 case WM_RBUTTONDOWN:
2194 // default handler removes the highlight from the currently
2195 // focused item when right mouse button is pressed on another
2196 // one but keeps the remaining items highlighted, which is
2197 // confusing, so override this default behaviour for tree with
2198 // multiple selections
2199 if ( isMultiple )
2200 {
2201 if ( !IsItemSelected(GetHwnd(), htItem) )
2202 {
2203 UnselectAll();
2204 SelectItem(htItem);
2205 ::SetFocus(GetHwnd(), htItem);
2206 }
2207
2208 // fire EVT_RIGHT_DOWN
2209 HandleMouseEvent(nMsg, x, y, wParam);
2210
2211 // send NM_RCLICK
2212 NMHDR nmhdr;
2213 nmhdr.hwndFrom = GetHwnd();
2214 nmhdr.idFrom = ::GetWindowLong(GetHwnd(), GWL_ID);
2215 nmhdr.code = NM_RCLICK;
2216 ::SendMessage(::GetParent(GetHwnd()), WM_NOTIFY,
2217 nmhdr.idFrom, (LPARAM)&nmhdr);
2218
2219 // prevent tree control default processing, as we've
2220 // already done everything
2221 processed = true;
2222 }
2223 break;
2224
2225 case WM_MOUSEMOVE:
2226 #ifndef __WXWINCE__
2227 if ( m_htClickedItem )
2228 {
2229 int cx = abs(m_ptClick.x - x);
2230 int cy = abs(m_ptClick.y - y);
2231
2232 if ( cx > ::GetSystemMetrics(SM_CXDRAG) ||
2233 cy > ::GetSystemMetrics(SM_CYDRAG) )
2234 {
2235 NM_TREEVIEW tv;
2236 wxZeroMemory(tv);
2237
2238 tv.hdr.hwndFrom = GetHwnd();
2239 tv.hdr.idFrom = ::GetWindowLong(GetHwnd(), GWL_ID);
2240 tv.hdr.code = TVN_BEGINDRAG;
2241
2242 tv.itemNew.hItem = HITEM(m_htClickedItem);
2243
2244
2245 TVITEM tviAux;
2246 wxZeroMemory(tviAux);
2247
2248 tviAux.hItem = HITEM(m_htClickedItem);
2249 tviAux.mask = TVIF_STATE | TVIF_PARAM;
2250 tviAux.stateMask = 0xffffffff;
2251 TreeView_GetItem(GetHwnd(), &tviAux);
2252
2253 tv.itemNew.state = tviAux.state;
2254 tv.itemNew.lParam = tviAux.lParam;
2255
2256 tv.ptDrag.x = x;
2257 tv.ptDrag.y = y;
2258
2259 // do it before SendMessage() call below to avoid
2260 // reentrancies here if there is another WM_MOUSEMOVE
2261 // in the queue already
2262 m_htClickedItem.Unset();
2263
2264 ::SendMessage(GetHwndOf(GetParent()), WM_NOTIFY,
2265 tv.hdr.idFrom, (LPARAM)&tv );
2266
2267 // don't pass it to the default window proc, it would
2268 // start dragging again
2269 processed = true;
2270 }
2271 }
2272 #endif // __WXWINCE__
2273
2274 #if wxUSE_DRAGIMAGE
2275 if ( m_dragImage )
2276 {
2277 m_dragImage->Move(wxPoint(x, y));
2278 if ( htItem )
2279 {
2280 // highlight the item as target (hiding drag image is
2281 // necessary - otherwise the display will be corrupted)
2282 m_dragImage->Hide();
2283 TreeView_SelectDropTarget(GetHwnd(), htItem);
2284 m_dragImage->Show();
2285 }
2286 }
2287 #endif // wxUSE_DRAGIMAGE
2288 break;
2289
2290 case WM_LBUTTONUP:
2291
2292 // facilitates multiple drag-and-drop
2293 if (htItem && isMultiple)
2294 {
2295 wxArrayTreeItemIds selections;
2296 size_t count = GetSelections(selections);
2297
2298 if (count > 1 &&
2299 !(wParam & MK_CONTROL) &&
2300 !(wParam & MK_SHIFT))
2301 {
2302 UnselectAll();
2303 TreeView_SelectItem(GetHwnd(), htItem);
2304 ::SelectItem(GetHwnd(), htItem);
2305 ::SetFocus(GetHwnd(), htItem);
2306 }
2307 m_htClickedItem.Unset();
2308 }
2309
2310 // fall through
2311
2312 case WM_RBUTTONUP:
2313 #if wxUSE_DRAGIMAGE
2314 if ( m_dragImage )
2315 {
2316 m_dragImage->EndDrag();
2317 delete m_dragImage;
2318 m_dragImage = NULL;
2319
2320 // generate the drag end event
2321 wxTreeEvent event(wxEVT_COMMAND_TREE_END_DRAG, this, htItem);
2322 event.m_pointDrag = wxPoint(x, y);
2323
2324 (void)HandleWindowEvent(event);
2325
2326 // if we don't do it, the tree seems to think that 2 items
2327 // are selected simultaneously which is quite weird
2328 TreeView_SelectDropTarget(GetHwnd(), 0);
2329 }
2330 #endif // wxUSE_DRAGIMAGE
2331 break;
2332 }
2333 }
2334 else if ( (nMsg == WM_SETFOCUS || nMsg == WM_KILLFOCUS) && isMultiple )
2335 {
2336 // the tree control greys out the selected item when it loses focus and
2337 // paints it as selected again when it regains it, but it won't do it
2338 // for the other items itself - help it
2339 wxArrayTreeItemIds selections;
2340 size_t count = GetSelections(selections);
2341 RECT rect;
2342 for ( size_t n = 0; n < count; n++ )
2343 {
2344 // TreeView_GetItemRect() will return false if item is not visible,
2345 // which may happen perfectly well
2346 if ( TreeView_GetItemRect(GetHwnd(), HITEM(selections[n]),
2347 &rect, TRUE) )
2348 {
2349 ::InvalidateRect(GetHwnd(), &rect, FALSE);
2350 }
2351 }
2352 }
2353 else if ( nMsg == WM_KEYDOWN && isMultiple )
2354 {
2355 bool bCtrl = wxIsCtrlDown(),
2356 bShift = wxIsShiftDown();
2357
2358 HTREEITEM htSel = (HTREEITEM)TreeView_GetSelection(GetHwnd());
2359 switch ( wParam )
2360 {
2361 case VK_SPACE:
2362 if ( bCtrl )
2363 {
2364 ToggleItemSelection(htSel);
2365 }
2366 else
2367 {
2368 UnselectAll();
2369
2370 ::SelectItem(GetHwnd(), htSel);
2371 }
2372
2373 processed = true;
2374 break;
2375
2376 case VK_UP:
2377 case VK_DOWN:
2378 if ( !bCtrl && !bShift )
2379 {
2380 // no modifiers, just clear selection and then let the default
2381 // processing to take place
2382 UnselectAll();
2383 }
2384 else if ( htSel )
2385 {
2386 (void)wxControl::MSWWindowProc(nMsg, wParam, lParam);
2387
2388 HTREEITEM htNext = (HTREEITEM)
2389 TreeView_GetNextItem
2390 (
2391 GetHwnd(),
2392 htSel,
2393 wParam == VK_UP ? TVGN_PREVIOUSVISIBLE
2394 : TVGN_NEXTVISIBLE
2395 );
2396
2397 if ( !htNext )
2398 {
2399 // at the top/bottom
2400 htNext = htSel;
2401 }
2402
2403 if ( bShift )
2404 {
2405 if ( !m_htSelStart )
2406 m_htSelStart = htSel;
2407
2408 SelectRange(GetHwnd(), HITEM(m_htSelStart), htNext);
2409 }
2410 else // bCtrl
2411 {
2412 // without changing selection
2413 ::SetFocus(GetHwnd(), htNext);
2414 }
2415
2416 processed = true;
2417 }
2418 break;
2419
2420 case VK_HOME:
2421 case VK_END:
2422 case VK_PRIOR:
2423 case VK_NEXT:
2424 // TODO: handle Shift/Ctrl with these keys
2425 if ( !bCtrl && !bShift )
2426 {
2427 UnselectAll();
2428
2429 m_htSelStart.Unset();
2430 }
2431 }
2432 }
2433 else if ( nMsg == WM_COMMAND )
2434 {
2435 // if we receive a EN_KILLFOCUS command from the in-place edit control
2436 // used for label editing, make sure to end editing
2437 WORD id, cmd;
2438 WXHWND hwnd;
2439 UnpackCommand(wParam, lParam, &id, &hwnd, &cmd);
2440
2441 if ( cmd == EN_KILLFOCUS )
2442 {
2443 if ( m_textCtrl && m_textCtrl->GetHandle() == hwnd )
2444 {
2445 DoEndEditLabel();
2446
2447 processed = true;
2448 }
2449 }
2450 }
2451
2452 if ( !processed )
2453 rc = wxControl::MSWWindowProc(nMsg, wParam, lParam);
2454
2455 return rc;
2456 }
2457
2458 WXLRESULT
2459 wxTreeCtrl::MSWDefWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
2460 {
2461 if ( nMsg == WM_CHAR )
2462 {
2463 // don't let the control process Space and Return keys because it
2464 // doesn't do anything useful with them anyhow but always beeps
2465 // annoyingly when it receives them and there is no way to turn it off
2466 // simply if you just process TREEITEM_ACTIVATED event to which Space
2467 // and Enter presses are mapped in your code
2468 if ( wParam == VK_SPACE || wParam == VK_RETURN )
2469 return 0;
2470 }
2471 #if wxUSE_DRAGIMAGE
2472 else if ( nMsg == WM_KEYDOWN )
2473 {
2474 if ( wParam == VK_ESCAPE )
2475 {
2476 if ( m_dragImage )
2477 {
2478 m_dragImage->EndDrag();
2479 delete m_dragImage;
2480 m_dragImage = NULL;
2481
2482 // if we don't do it, the tree seems to think that 2 items
2483 // are selected simultaneously which is quite weird
2484 TreeView_SelectDropTarget(GetHwnd(), 0);
2485 }
2486 }
2487 }
2488 #endif // wxUSE_DRAGIMAGE
2489
2490 return wxControl::MSWDefWindowProc(nMsg, wParam, lParam);
2491 }
2492
2493 // process WM_NOTIFY Windows message
2494 bool wxTreeCtrl::MSWOnNotify(int idCtrl, WXLPARAM lParam, WXLPARAM *result)
2495 {
2496 wxTreeEvent event(wxEVT_NULL, this);
2497 wxEventType eventType = wxEVT_NULL;
2498 NMHDR *hdr = (NMHDR *)lParam;
2499
2500 switch ( hdr->code )
2501 {
2502 case TVN_BEGINDRAG:
2503 eventType = wxEVT_COMMAND_TREE_BEGIN_DRAG;
2504 // fall through
2505
2506 case TVN_BEGINRDRAG:
2507 {
2508 if ( eventType == wxEVT_NULL )
2509 eventType = wxEVT_COMMAND_TREE_BEGIN_RDRAG;
2510 //else: left drag, already set above
2511
2512 NM_TREEVIEW *tv = (NM_TREEVIEW *)lParam;
2513
2514 event.m_item = tv->itemNew.hItem;
2515 event.m_pointDrag = wxPoint(tv->ptDrag.x, tv->ptDrag.y);
2516
2517 // don't allow dragging by default: the user code must
2518 // explicitly say that it wants to allow it to avoid breaking
2519 // the old apps
2520 event.Veto();
2521 }
2522 break;
2523
2524 case TVN_BEGINLABELEDIT:
2525 {
2526 eventType = wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT;
2527 TV_DISPINFO *info = (TV_DISPINFO *)lParam;
2528
2529 // although the user event handler may still veto it, it is
2530 // important to set it now so that calls to SetItemText() from
2531 // the event handler would change the text controls contents
2532 m_idEdited =
2533 event.m_item = info->item.hItem;
2534 event.m_label = info->item.pszText;
2535 event.m_editCancelled = false;
2536 }
2537 break;
2538
2539 case TVN_DELETEITEM:
2540 {
2541 eventType = wxEVT_COMMAND_TREE_DELETE_ITEM;
2542 NM_TREEVIEW *tv = (NM_TREEVIEW *)lParam;
2543
2544 event.m_item = tv->itemOld.hItem;
2545
2546 if ( m_hasAnyAttr )
2547 {
2548 wxMapTreeAttr::iterator it = m_attrs.find(tv->itemOld.hItem);
2549 if ( it != m_attrs.end() )
2550 {
2551 delete it->second;
2552 m_attrs.erase(it);
2553 }
2554 }
2555 }
2556 break;
2557
2558 case TVN_ENDLABELEDIT:
2559 {
2560 eventType = wxEVT_COMMAND_TREE_END_LABEL_EDIT;
2561 TV_DISPINFO *info = (TV_DISPINFO *)lParam;
2562
2563 event.m_item = info->item.hItem;
2564 event.m_label = info->item.pszText;
2565 event.m_editCancelled = info->item.pszText == NULL;
2566 break;
2567 }
2568
2569 #ifndef __WXWINCE__
2570 // These *must* not be removed or TVN_GETINFOTIP will
2571 // not be processed each time the mouse is moved
2572 // and the tooltip will only ever update once.
2573 case TTN_NEEDTEXTA:
2574 case TTN_NEEDTEXTW:
2575 {
2576 *result = 0;
2577
2578 break;
2579 }
2580
2581 #ifdef TVN_GETINFOTIP
2582 case TVN_GETINFOTIP:
2583 {
2584 eventType = wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP;
2585 NMTVGETINFOTIP *info = (NMTVGETINFOTIP*)lParam;
2586
2587 // Which item are we trying to get a tooltip for?
2588 event.m_item = info->hItem;
2589
2590 break;
2591 }
2592 #endif // TVN_GETINFOTIP
2593 #endif // !__WXWINCE__
2594
2595 case TVN_GETDISPINFO:
2596 eventType = wxEVT_COMMAND_TREE_GET_INFO;
2597 // fall through
2598
2599 case TVN_SETDISPINFO:
2600 {
2601 if ( eventType == wxEVT_NULL )
2602 eventType = wxEVT_COMMAND_TREE_SET_INFO;
2603 //else: get, already set above
2604
2605 TV_DISPINFO *info = (TV_DISPINFO *)lParam;
2606
2607 event.m_item = info->item.hItem;
2608 break;
2609 }
2610
2611 case TVN_ITEMEXPANDING:
2612 case TVN_ITEMEXPANDED:
2613 {
2614 NM_TREEVIEW *tv = (NM_TREEVIEW*)lParam;
2615
2616 int what;
2617 switch ( tv->action )
2618 {
2619 default:
2620 wxLogDebug(wxT("unexpected code %d in TVN_ITEMEXPAND message"), tv->action);
2621 // fall through
2622
2623 case TVE_EXPAND:
2624 what = IDX_EXPAND;
2625 break;
2626
2627 case TVE_COLLAPSE:
2628 what = IDX_COLLAPSE;
2629 break;
2630 }
2631
2632 int how = hdr->code == TVN_ITEMEXPANDING ? IDX_DOING
2633 : IDX_DONE;
2634
2635 eventType = gs_expandEvents[what][how];
2636
2637 event.m_item = tv->itemNew.hItem;
2638 }
2639 break;
2640
2641 case TVN_KEYDOWN:
2642 {
2643 eventType = wxEVT_COMMAND_TREE_KEY_DOWN;
2644 TV_KEYDOWN *info = (TV_KEYDOWN *)lParam;
2645
2646 // fabricate the lParam and wParam parameters sufficiently
2647 // similar to the ones from a "real" WM_KEYDOWN so that
2648 // CreateKeyEvent() works correctly
2649 WXLPARAM lParam = (wxIsAltDown() ? KF_ALTDOWN : 0) << 16;
2650
2651 WXWPARAM wParam = info->wVKey;
2652
2653 int keyCode = wxCharCodeMSWToWX(wParam);
2654 if ( !keyCode )
2655 {
2656 // wxCharCodeMSWToWX() returns 0 to indicate that this is a
2657 // simple ASCII key
2658 keyCode = wParam;
2659 }
2660
2661 event.m_evtKey = CreateKeyEvent(wxEVT_KEY_DOWN,
2662 keyCode,
2663 lParam,
2664 wParam);
2665
2666 // a separate event for Space/Return
2667 if ( !wxIsAnyModifierDown() &&
2668 ((info->wVKey == VK_SPACE) || (info->wVKey == VK_RETURN)) )
2669 {
2670 wxTreeItemId item;
2671 if ( !HasFlag(wxTR_MULTIPLE) )
2672 item = GetSelection();
2673
2674 wxTreeEvent event2(wxEVT_COMMAND_TREE_ITEM_ACTIVATED,
2675 this, item);
2676 (void)HandleWindowEvent(event2);
2677 }
2678 }
2679 break;
2680
2681
2682 // Vista's tree control has introduced some problems with our
2683 // multi-selection tree. When TreeView_SelectItem() is called,
2684 // the wrong items are deselected.
2685
2686 // Fortunately, Vista provides a new notification, TVN_ITEMCHANGING
2687 // that can be used to regulate this incorrect behavior. The
2688 // following messages will allow only the unlocked item's selection
2689 // state to change
2690
2691 case TVN_ITEMCHANGINGA:
2692 case TVN_ITEMCHANGINGW:
2693 {
2694 // we only need to handles these in multi-select trees
2695 if ( HasFlag(wxTR_MULTIPLE) )
2696 {
2697 // get info about the item about to be changed
2698 NMTVITEMCHANGE* info = (NMTVITEMCHANGE*)lParam;
2699 if (TreeItemUnlocker::IsLocked(info->hItem))
2700 {
2701 // item's state is locked, don't allow the change
2702 // returning 1 will disallow the change
2703 *result = 1;
2704 return true;
2705 }
2706 }
2707
2708 // allow the state change
2709 }
2710 return false;
2711
2712 // NB: MSLU is broken and sends TVN_SELCHANGEDA instead of
2713 // TVN_SELCHANGEDW in Unicode mode under Win98. Therefore
2714 // we have to handle both messages:
2715 case TVN_SELCHANGEDA:
2716 case TVN_SELCHANGEDW:
2717 eventType = wxEVT_COMMAND_TREE_SEL_CHANGED;
2718 // fall through
2719
2720 case TVN_SELCHANGINGA:
2721 case TVN_SELCHANGINGW:
2722 {
2723 if ( eventType == wxEVT_NULL )
2724 eventType = wxEVT_COMMAND_TREE_SEL_CHANGING;
2725 //else: already set above
2726
2727 if (hdr->code == TVN_SELCHANGINGW ||
2728 hdr->code == TVN_SELCHANGEDW)
2729 {
2730 NM_TREEVIEWW *tv = (NM_TREEVIEWW *)lParam;
2731 event.m_item = tv->itemNew.hItem;
2732 event.m_itemOld = tv->itemOld.hItem;
2733 }
2734 else
2735 {
2736 NM_TREEVIEWA *tv = (NM_TREEVIEWA *)lParam;
2737 event.m_item = tv->itemNew.hItem;
2738 event.m_itemOld = tv->itemOld.hItem;
2739 }
2740 }
2741
2742 // we receive this message from WM_LBUTTONDOWN handler inside
2743 // comctl32.dll and so before the click is passed to
2744 // DefWindowProc() which sets the focus to the window which was
2745 // clicked and this can lead to unexpected event sequences: for
2746 // example, we may get a "selection change" event from the tree
2747 // before getting a "kill focus" event for the text control which
2748 // had the focus previously, thus breaking user code doing input
2749 // validation
2750 //
2751 // to avoid such surprises, we force the generation of focus events
2752 // now, before we generate the selection change ones
2753 SetFocus();
2754 break;
2755
2756 // instead of explicitly checking for _WIN32_IE, check if the
2757 // required symbols are available in the headers
2758 #if defined(CDDS_PREPAINT) && !wxUSE_COMCTL32_SAFELY
2759 case NM_CUSTOMDRAW:
2760 {
2761 LPNMTVCUSTOMDRAW lptvcd = (LPNMTVCUSTOMDRAW)lParam;
2762 NMCUSTOMDRAW& nmcd = lptvcd->nmcd;
2763 switch ( nmcd.dwDrawStage )
2764 {
2765 case CDDS_PREPAINT:
2766 // if we've got any items with non standard attributes,
2767 // notify us before painting each item
2768 *result = m_hasAnyAttr ? CDRF_NOTIFYITEMDRAW
2769 : CDRF_DODEFAULT;
2770 break;
2771
2772 case CDDS_ITEMPREPAINT:
2773 {
2774 wxMapTreeAttr::iterator
2775 it = m_attrs.find((void *)nmcd.dwItemSpec);
2776
2777 if ( it == m_attrs.end() )
2778 {
2779 // nothing to do for this item
2780 *result = CDRF_DODEFAULT;
2781 break;
2782 }
2783
2784 wxTreeItemAttr * const attr = it->second;
2785
2786 wxTreeViewItem tvItem((void *)nmcd.dwItemSpec,
2787 TVIF_STATE, TVIS_DROPHILITED);
2788 DoGetItem(&tvItem);
2789 const UINT tvItemState = tvItem.state;
2790
2791 // selection colours should override ours,
2792 // otherwise it is too confusing to the user
2793 if ( !(nmcd.uItemState & CDIS_SELECTED) &&
2794 !(tvItemState & TVIS_DROPHILITED) )
2795 {
2796 wxColour colBack;
2797 if ( attr->HasBackgroundColour() )
2798 {
2799 colBack = attr->GetBackgroundColour();
2800 lptvcd->clrTextBk = wxColourToRGB(colBack);
2801 }
2802 }
2803
2804 // but we still want to keep the special foreground
2805 // colour when we don't have focus (we can't keep
2806 // it when we do, it would usually be unreadable on
2807 // the almost inverted bg colour...)
2808 if ( ( !(nmcd.uItemState & CDIS_SELECTED) ||
2809 FindFocus() != this ) &&
2810 !(tvItemState & TVIS_DROPHILITED) )
2811 {
2812 wxColour colText;
2813 if ( attr->HasTextColour() )
2814 {
2815 colText = attr->GetTextColour();
2816 lptvcd->clrText = wxColourToRGB(colText);
2817 }
2818 }
2819
2820 if ( attr->HasFont() )
2821 {
2822 HFONT hFont = GetHfontOf(attr->GetFont());
2823
2824 ::SelectObject(nmcd.hdc, hFont);
2825
2826 *result = CDRF_NEWFONT;
2827 }
2828 else // no specific font
2829 {
2830 *result = CDRF_DODEFAULT;
2831 }
2832 }
2833 break;
2834
2835 default:
2836 *result = CDRF_DODEFAULT;
2837 }
2838 }
2839
2840 // we always process it
2841 return true;
2842 #endif // have owner drawn support in headers
2843
2844 case NM_CLICK:
2845 {
2846 DWORD pos = GetMessagePos();
2847 POINT point;
2848 point.x = LOWORD(pos);
2849 point.y = HIWORD(pos);
2850 ::MapWindowPoints(HWND_DESKTOP, GetHwnd(), &point, 1);
2851 int flags = 0;
2852 wxTreeItemId item = HitTest(wxPoint(point.x, point.y), flags);
2853 if (flags & wxTREE_HITTEST_ONITEMSTATEICON)
2854 {
2855 event.m_item = item;
2856 eventType = wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK;
2857 }
2858 break;
2859 }
2860
2861 case NM_DBLCLK:
2862 case NM_RCLICK:
2863 {
2864 TV_HITTESTINFO tvhti;
2865 ::GetCursorPos(&tvhti.pt);
2866 ::ScreenToClient(GetHwnd(), &tvhti.pt);
2867 if ( TreeView_HitTest(GetHwnd(), &tvhti) )
2868 {
2869 if ( tvhti.flags & TVHT_ONITEM )
2870 {
2871 event.m_item = tvhti.hItem;
2872 eventType = (int)hdr->code == NM_DBLCLK
2873 ? wxEVT_COMMAND_TREE_ITEM_ACTIVATED
2874 : wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK;
2875
2876 event.m_pointDrag.x = tvhti.pt.x;
2877 event.m_pointDrag.y = tvhti.pt.y;
2878 }
2879
2880 break;
2881 }
2882 }
2883 // fall through
2884
2885 default:
2886 return wxControl::MSWOnNotify(idCtrl, lParam, result);
2887 }
2888
2889 event.SetEventType(eventType);
2890
2891 if ( event.m_item.IsOk() )
2892 event.SetClientObject(GetItemData(event.m_item));
2893
2894 bool processed = HandleWindowEvent(event);
2895
2896 // post processing
2897 switch ( hdr->code )
2898 {
2899 case NM_DBLCLK:
2900 // we translate NM_DBLCLK into ACTIVATED event, so don't interpret
2901 // the return code of this event handler as the return value for
2902 // NM_DBLCLK - otherwise, double clicking the item to toggle its
2903 // expanded status would never work
2904 *result = false;
2905 break;
2906
2907 case NM_RCLICK:
2908 // prevent tree control from sending WM_CONTEXTMENU to our parent
2909 // (which it does if NM_RCLICK is not handled) because we want to
2910 // send it to the control itself
2911 *result =
2912 processed = true;
2913
2914 ::SendMessage(GetHwnd(), WM_CONTEXTMENU,
2915 (WPARAM)GetHwnd(), ::GetMessagePos());
2916 break;
2917
2918 case TVN_BEGINDRAG:
2919 case TVN_BEGINRDRAG:
2920 #if wxUSE_DRAGIMAGE
2921 if ( event.IsAllowed() )
2922 {
2923 // normally this is impossible because the m_dragImage is
2924 // deleted once the drag operation is over
2925 wxASSERT_MSG( !m_dragImage, _T("starting to drag once again?") );
2926
2927 m_dragImage = new wxDragImage(*this, event.m_item);
2928 m_dragImage->BeginDrag(wxPoint(0,0), this);
2929 m_dragImage->Show();
2930 }
2931 #endif // wxUSE_DRAGIMAGE
2932 break;
2933
2934 case TVN_DELETEITEM:
2935 {
2936 // NB: we might process this message using wxWidgets event
2937 // tables, but due to overhead of wxWin event system we
2938 // prefer to do it here ourself (otherwise deleting a tree
2939 // with many items is just too slow)
2940 NM_TREEVIEW *tv = (NM_TREEVIEW *)lParam;
2941
2942 wxTreeItemParam *param =
2943 (wxTreeItemParam *)tv->itemOld.lParam;
2944 delete param;
2945
2946 processed = true; // Make sure we don't get called twice
2947 }
2948 break;
2949
2950 case TVN_BEGINLABELEDIT:
2951 // return true to cancel label editing
2952 *result = !event.IsAllowed();
2953
2954 // set ES_WANTRETURN ( like we do in BeginLabelEdit )
2955 if ( event.IsAllowed() )
2956 {
2957 HWND hText = TreeView_GetEditControl(GetHwnd());
2958 if ( hText )
2959 {
2960 // MBN: if m_textCtrl already has an HWND, it is a stale
2961 // pointer from a previous edit (because the user
2962 // didn't modify the label before dismissing the control,
2963 // and TVN_ENDLABELEDIT was not sent), so delete it
2964 if ( m_textCtrl && m_textCtrl->GetHWND() )
2965 DeleteTextCtrl();
2966 if ( !m_textCtrl )
2967 m_textCtrl = new wxTextCtrl();
2968 m_textCtrl->SetParent(this);
2969 m_textCtrl->SetHWND((WXHWND)hText);
2970 m_textCtrl->SubclassWin((WXHWND)hText);
2971
2972 // set wxTE_PROCESS_ENTER style for the text control to
2973 // force it to process the Enter presses itself, otherwise
2974 // they could be stolen from it by the dialog
2975 // navigation code
2976 m_textCtrl->SetWindowStyle(m_textCtrl->GetWindowStyle()
2977 | wxTE_PROCESS_ENTER);
2978 }
2979 }
2980 else // we had set m_idEdited before
2981 {
2982 m_idEdited.Unset();
2983 }
2984 break;
2985
2986 case TVN_ENDLABELEDIT:
2987 // return true to set the label to the new string: note that we
2988 // also must pretend that we did process the message or it is going
2989 // to be passed to DefWindowProc() which will happily return false
2990 // cancelling the label change
2991 *result = event.IsAllowed();
2992 processed = true;
2993
2994 // ensure that we don't have the text ctrl which is going to be
2995 // deleted any more
2996 DeleteTextCtrl();
2997 break;
2998
2999 #ifndef __WXWINCE__
3000 #ifdef TVN_GETINFOTIP
3001 case TVN_GETINFOTIP:
3002 {
3003 // If the user permitted a tooltip change, change it
3004 if (event.IsAllowed())
3005 {
3006 SetToolTip(event.m_label);
3007 }
3008 }
3009 break;
3010 #endif
3011 #endif
3012
3013 case TVN_SELCHANGING:
3014 case TVN_ITEMEXPANDING:
3015 // return true to prevent the action from happening
3016 *result = !event.IsAllowed();
3017 break;
3018
3019 case TVN_ITEMEXPANDED:
3020 {
3021 NM_TREEVIEW *tv = (NM_TREEVIEW *)lParam;
3022 const wxTreeItemId id(tv->itemNew.hItem);
3023
3024 if ( tv->action == TVE_COLLAPSE )
3025 {
3026 if ( wxApp::GetComCtl32Version() >= 600 )
3027 {
3028 // for some reason the item selection rectangle depends
3029 // on whether it is expanded or collapsed (at least
3030 // with comctl32.dll v6): it is wider (by 3 pixels) in
3031 // the expanded state, so when the item collapses and
3032 // then is deselected the rightmost 3 pixels of the
3033 // previously drawn selection are left on the screen
3034 //
3035 // it's not clear if it's a bug in comctl32.dll or in
3036 // our code (because it does not happen in Explorer but
3037 // OTOH we don't do anything which could result in this
3038 // AFAICS) but we do need to work around it to avoid
3039 // ugly artifacts
3040 RefreshItem(id);
3041 }
3042 }
3043 else // expand
3044 {
3045 // the item is also not refreshed properly after expansion when
3046 // it has an image depending on the expanded/collapsed state:
3047 // again, it's not clear if the bug is in comctl32.dll or our
3048 // code...
3049 int image = GetItemImage(id, wxTreeItemIcon_Expanded);
3050 if ( image != -1 )
3051 {
3052 RefreshItem(id);
3053 }
3054 }
3055 }
3056 break;
3057
3058 case TVN_GETDISPINFO:
3059 // NB: so far the user can't set the image himself anyhow, so do it
3060 // anyway - but this may change later
3061 //if ( /* !processed && */ )
3062 {
3063 wxTreeItemId item = event.m_item;
3064 TV_DISPINFO *info = (TV_DISPINFO *)lParam;
3065
3066 const wxTreeItemParam * const param = GetItemParam(item);
3067 if ( !param )
3068 break;
3069
3070 if ( info->item.mask & TVIF_IMAGE )
3071 {
3072 info->item.iImage =
3073 param->GetImage
3074 (
3075 IsExpanded(item) ? wxTreeItemIcon_Expanded
3076 : wxTreeItemIcon_Normal
3077 );
3078 }
3079 if ( info->item.mask & TVIF_SELECTEDIMAGE )
3080 {
3081 info->item.iSelectedImage =
3082 param->GetImage
3083 (
3084 IsExpanded(item) ? wxTreeItemIcon_SelectedExpanded
3085 : wxTreeItemIcon_Selected
3086 );
3087 }
3088 }
3089 break;
3090
3091 //default:
3092 // for the other messages the return value is ignored and there is
3093 // nothing special to do
3094 }
3095 return processed;
3096 }
3097
3098 // ----------------------------------------------------------------------------
3099 // State control.
3100 // ----------------------------------------------------------------------------
3101
3102 // why do they define INDEXTOSTATEIMAGEMASK but not the inverse?
3103 #define STATEIMAGEMASKTOINDEX(state) (((state) & TVIS_STATEIMAGEMASK) >> 12)
3104
3105 void wxTreeCtrl::SetState(const wxTreeItemId& node, int state)
3106 {
3107 TV_ITEM tvi;
3108 tvi.hItem = (HTREEITEM)node.m_pItem;
3109 tvi.mask = TVIF_STATE;
3110 tvi.stateMask = TVIS_STATEIMAGEMASK;
3111
3112 // Select the specified state, or -1 == cycle to the next one.
3113 if ( state == -1 )
3114 {
3115 TreeView_GetItem(GetHwnd(), &tvi);
3116
3117 state = STATEIMAGEMASKTOINDEX(tvi.state) + 1;
3118 if ( state == m_imageListState->GetImageCount() )
3119 state = 1;
3120 }
3121
3122 wxCHECK_RET( state < m_imageListState->GetImageCount(),
3123 _T("wxTreeCtrl::SetState(): item index out of bounds") );
3124
3125 tvi.state = INDEXTOSTATEIMAGEMASK(state);
3126
3127 TreeView_SetItem(GetHwnd(), &tvi);
3128 }
3129
3130 int wxTreeCtrl::GetState(const wxTreeItemId& node)
3131 {
3132 TV_ITEM tvi;
3133 tvi.hItem = (HTREEITEM)node.m_pItem;
3134 tvi.mask = TVIF_STATE;
3135 tvi.stateMask = TVIS_STATEIMAGEMASK;
3136 TreeView_GetItem(GetHwnd(), &tvi);
3137
3138 return STATEIMAGEMASKTOINDEX(tvi.state);
3139 }
3140
3141 #endif // wxUSE_TREECTRL