Improve hit detection in wxMSW wxTreeCtrl with wxTR_FULL_ROW_HIGHLIGHT style.
[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/dynlib.h"
41 #include "wx/msw/private.h"
42
43 // Set this to 1 to be _absolutely_ sure that repainting will work for all
44 // comctl32.dll versions
45 #define wxUSE_COMCTL32_SAFELY 0
46
47 #include "wx/imaglist.h"
48 #include "wx/msw/dragimag.h"
49
50 // macros to hide the cast ugliness
51 // --------------------------------
52
53 // get HTREEITEM from wxTreeItemId
54 #define HITEM(item) ((HTREEITEM)(((item).m_pItem)))
55
56
57 // older SDKs are missing these
58 #ifndef TVN_ITEMCHANGINGA
59
60 #define TVN_ITEMCHANGINGA (TVN_FIRST-16)
61 #define TVN_ITEMCHANGINGW (TVN_FIRST-17)
62
63 typedef struct tagNMTVITEMCHANGE
64 {
65 NMHDR hdr;
66 UINT uChanged;
67 HTREEITEM hItem;
68 UINT uStateNew;
69 UINT uStateOld;
70 LPARAM lParam;
71 } NMTVITEMCHANGE;
72
73 #endif
74
75
76 // this helper class is used on vista systems for preventing unwanted
77 // item state changes in the vista tree control. It is only effective in
78 // multi-select mode on vista systems.
79
80 // The vista tree control includes some new code that originally broke the
81 // multi-selection tree, causing seemingly spurious item selection state changes
82 // during Shift or Ctrl-click item selection. (To witness the original broken
83 // behavior, simply make IsLocked() below always return false). This problem was
84 // solved by using the following class to 'unlock' an item's selection state.
85
86 class TreeItemUnlocker
87 {
88 public:
89 // unlock a single item
90 TreeItemUnlocker(HTREEITEM item) { ms_unlockedItem = item; }
91
92 // unlock all items, don't use unless absolutely necessary
93 TreeItemUnlocker() { ms_unlockedItem = (HTREEITEM)-1; }
94
95 // lock everything back
96 ~TreeItemUnlocker() { ms_unlockedItem = NULL; }
97
98
99 // check if the item state is currently locked
100 static bool IsLocked(HTREEITEM item)
101 { return ms_unlockedItem != (HTREEITEM)-1 && item != ms_unlockedItem; }
102
103 private:
104 static HTREEITEM ms_unlockedItem;
105 };
106
107 HTREEITEM TreeItemUnlocker::ms_unlockedItem = NULL;
108
109 // another helper class: set the variable to true during its lifetime and reset
110 // it to false when it is destroyed
111 //
112 // it is currently always used with wxTreeCtrl::m_changingSelection
113 class TempSetter
114 {
115 public:
116 TempSetter(bool& var) : m_var(var)
117 {
118 wxASSERT_MSG( !m_var, "variable shouldn't be already set" );
119 m_var = true;
120 }
121
122 ~TempSetter()
123 {
124 m_var = false;
125 }
126
127 private:
128 bool& m_var;
129
130 wxDECLARE_NO_COPY_CLASS(TempSetter);
131 };
132
133 // ----------------------------------------------------------------------------
134 // private functions
135 // ----------------------------------------------------------------------------
136
137 // wrappers for TreeView_GetItem/TreeView_SetItem
138 static bool IsItemSelected(HWND hwndTV, HTREEITEM hItem)
139 {
140 TV_ITEM tvi;
141 tvi.mask = TVIF_STATE | TVIF_HANDLE;
142 tvi.stateMask = TVIS_SELECTED;
143 tvi.hItem = hItem;
144
145 TreeItemUnlocker unlocker(hItem);
146
147 if ( !TreeView_GetItem(hwndTV, &tvi) )
148 {
149 wxLogLastError(wxT("TreeView_GetItem"));
150 }
151
152 return (tvi.state & TVIS_SELECTED) != 0;
153 }
154
155 static bool SelectItem(HWND hwndTV, HTREEITEM hItem, bool select = true)
156 {
157 TV_ITEM tvi;
158 tvi.mask = TVIF_STATE | TVIF_HANDLE;
159 tvi.stateMask = TVIS_SELECTED;
160 tvi.state = select ? TVIS_SELECTED : 0;
161 tvi.hItem = hItem;
162
163 TreeItemUnlocker unlocker(hItem);
164
165 if ( TreeView_SetItem(hwndTV, &tvi) == -1 )
166 {
167 wxLogLastError(wxT("TreeView_SetItem"));
168 return false;
169 }
170
171 return true;
172 }
173
174 static inline void UnselectItem(HWND hwndTV, HTREEITEM htItem)
175 {
176 SelectItem(hwndTV, htItem, false);
177 }
178
179 static inline void ToggleItemSelection(HWND hwndTV, HTREEITEM htItem)
180 {
181 SelectItem(hwndTV, htItem, !IsItemSelected(hwndTV, htItem));
182 }
183
184 // helper function which selects all items in a range and, optionally,
185 // deselects all the other ones
186 //
187 // returns true if the selection changed at all or false if nothing changed
188
189 // flags for SelectRange()
190 enum
191 {
192 SR_SIMULATE = 1, // don't do anything, just return true or false
193 SR_UNSELECT_OTHERS = 2 // deselect the items not in range
194 };
195
196 static bool SelectRange(HWND hwndTV,
197 HTREEITEM htFirst,
198 HTREEITEM htLast,
199 int flags)
200 {
201 // find the first (or last) item and select it
202 bool changed = false;
203 bool cont = true;
204 HTREEITEM htItem = (HTREEITEM)TreeView_GetRoot(hwndTV);
205
206 while ( htItem && cont )
207 {
208 if ( (htItem == htFirst) || (htItem == htLast) )
209 {
210 if ( !IsItemSelected(hwndTV, htItem) )
211 {
212 if ( !(flags & SR_SIMULATE) )
213 {
214 SelectItem(hwndTV, htItem);
215 }
216
217 changed = true;
218 }
219
220 cont = false;
221 }
222 else // not first or last
223 {
224 if ( flags & SR_UNSELECT_OTHERS )
225 {
226 if ( IsItemSelected(hwndTV, htItem) )
227 {
228 if ( !(flags & SR_SIMULATE) )
229 UnselectItem(hwndTV, htItem);
230
231 changed = true;
232 }
233 }
234 }
235
236 htItem = (HTREEITEM)TreeView_GetNextVisible(hwndTV, htItem);
237 }
238
239 // select the items in range
240 cont = htFirst != htLast;
241 while ( htItem && cont )
242 {
243 if ( !IsItemSelected(hwndTV, htItem) )
244 {
245 if ( !(flags & SR_SIMULATE) )
246 {
247 SelectItem(hwndTV, htItem);
248 }
249
250 changed = true;
251 }
252
253 cont = (htItem != htFirst) && (htItem != htLast);
254
255 htItem = (HTREEITEM)TreeView_GetNextVisible(hwndTV, htItem);
256 }
257
258 // optionally deselect the rest
259 if ( flags & SR_UNSELECT_OTHERS )
260 {
261 while ( htItem )
262 {
263 if ( IsItemSelected(hwndTV, htItem) )
264 {
265 if ( !(flags & SR_SIMULATE) )
266 {
267 UnselectItem(hwndTV, htItem);
268 }
269
270 changed = true;
271 }
272
273 htItem = (HTREEITEM)TreeView_GetNextVisible(hwndTV, htItem);
274 }
275 }
276
277 // seems to be necessary - otherwise the just selected items don't always
278 // appear as selected
279 if ( !(flags & SR_SIMULATE) )
280 {
281 UpdateWindow(hwndTV);
282 }
283
284 return changed;
285 }
286
287 // helper function which tricks the standard control into changing the focused
288 // item without changing anything else (if someone knows why Microsoft doesn't
289 // allow to do it by just setting TVIS_FOCUSED flag, please tell me!)
290 //
291 // returns true if the focus was changed, false if the given item was already
292 // the focused one
293 static bool SetFocus(HWND hwndTV, HTREEITEM htItem)
294 {
295 // the current focus
296 HTREEITEM htFocus = (HTREEITEM)TreeView_GetSelection(hwndTV);
297
298 if ( htItem == htFocus )
299 return false;
300
301 if ( htItem )
302 {
303 // remember the selection state of the item
304 bool wasSelected = IsItemSelected(hwndTV, htItem);
305
306 if ( htFocus && IsItemSelected(hwndTV, htFocus) )
307 {
308 // prevent the tree from unselecting the old focus which it
309 // would do by default (TreeView_SelectItem unselects the
310 // focused item)
311 TreeView_SelectItem(hwndTV, 0);
312 SelectItem(hwndTV, htFocus);
313 }
314
315 TreeView_SelectItem(hwndTV, htItem);
316
317 if ( !wasSelected )
318 {
319 // need to clear the selection which TreeView_SelectItem() gave
320 // us
321 UnselectItem(hwndTV, htItem);
322 }
323 //else: was selected, still selected - ok
324 }
325 else // reset focus
326 {
327 bool wasFocusSelected = IsItemSelected(hwndTV, htFocus);
328
329 // just clear the focus
330 TreeView_SelectItem(hwndTV, 0);
331
332 if ( wasFocusSelected )
333 {
334 // restore the selection state
335 SelectItem(hwndTV, htFocus);
336 }
337 }
338
339 return true;
340 }
341
342 // ----------------------------------------------------------------------------
343 // private classes
344 // ----------------------------------------------------------------------------
345
346 // a convenient wrapper around TV_ITEM struct which adds a ctor
347 #ifdef __VISUALC__
348 #pragma warning( disable : 4097 ) // inheriting from typedef
349 #endif
350
351 struct wxTreeViewItem : public TV_ITEM
352 {
353 wxTreeViewItem(const wxTreeItemId& item, // the item handle
354 UINT mask_, // fields which are valid
355 UINT stateMask_ = 0) // for TVIF_STATE only
356 {
357 wxZeroMemory(*this);
358
359 // hItem member is always valid
360 mask = mask_ | TVIF_HANDLE;
361 stateMask = stateMask_;
362 hItem = HITEM(item);
363 }
364 };
365
366 // ----------------------------------------------------------------------------
367 // This class is our userdata/lParam for the TV_ITEMs stored in the treeview.
368 //
369 // We need this for a couple of reasons:
370 //
371 // 1) This class is needed for support of different images: the Win32 common
372 // control natively supports only 2 images (the normal one and another for the
373 // selected state). We wish to provide support for 2 more of them for folder
374 // items (i.e. those which have children): for expanded state and for expanded
375 // selected state. For this we use this structure to store the additional items
376 // images.
377 //
378 // 2) This class is also needed to hold the HITEM so that we can sort
379 // it correctly in the MSW sort callback.
380 //
381 // In addition it makes other workarounds such as this easier and helps
382 // simplify the code.
383 // ----------------------------------------------------------------------------
384
385 class wxTreeItemParam
386 {
387 public:
388 wxTreeItemParam()
389 {
390 m_data = NULL;
391
392 for ( size_t n = 0; n < WXSIZEOF(m_images); n++ )
393 {
394 m_images[n] = -1;
395 }
396 }
397
398 // dtor deletes the associated data as well
399 virtual ~wxTreeItemParam() { delete m_data; }
400
401 // accessors
402 // get the real data associated with the item
403 wxTreeItemData *GetData() const { return m_data; }
404 // change it
405 void SetData(wxTreeItemData *data) { m_data = data; }
406
407 // do we have such image?
408 bool HasImage(wxTreeItemIcon which) const { return m_images[which] != -1; }
409 // get image, falling back to the other images if this one is not
410 // specified
411 int GetImage(wxTreeItemIcon which) const
412 {
413 int image = m_images[which];
414 if ( image == -1 )
415 {
416 switch ( which )
417 {
418 case wxTreeItemIcon_SelectedExpanded:
419 image = GetImage(wxTreeItemIcon_Expanded);
420 if ( image != -1 )
421 break;
422 //else: fall through
423
424 case wxTreeItemIcon_Selected:
425 case wxTreeItemIcon_Expanded:
426 image = GetImage(wxTreeItemIcon_Normal);
427 break;
428
429 case wxTreeItemIcon_Normal:
430 // no fallback
431 break;
432
433 default:
434 wxFAIL_MSG( wxT("unsupported wxTreeItemIcon value") );
435 }
436 }
437
438 return image;
439 }
440 // change the given image
441 void SetImage(int image, wxTreeItemIcon which) { m_images[which] = image; }
442
443 // get item
444 const wxTreeItemId& GetItem() const { return m_item; }
445 // set item
446 void SetItem(const wxTreeItemId& item) { m_item = item; }
447
448 protected:
449 // all the images associated with the item
450 int m_images[wxTreeItemIcon_Max];
451
452 // item for sort callbacks
453 wxTreeItemId m_item;
454
455 // the real client data
456 wxTreeItemData *m_data;
457
458 wxDECLARE_NO_COPY_CLASS(wxTreeItemParam);
459 };
460
461 // wxVirutalNode is used in place of a single root when 'hidden' root is
462 // specified.
463 class wxVirtualNode : public wxTreeViewItem
464 {
465 public:
466 wxVirtualNode(wxTreeItemParam *param)
467 : wxTreeViewItem(TVI_ROOT, 0)
468 {
469 m_param = param;
470 }
471
472 ~wxVirtualNode()
473 {
474 delete m_param;
475 }
476
477 wxTreeItemParam *GetParam() const { return m_param; }
478 void SetParam(wxTreeItemParam *param) { delete m_param; m_param = param; }
479
480 private:
481 wxTreeItemParam *m_param;
482
483 wxDECLARE_NO_COPY_CLASS(wxVirtualNode);
484 };
485
486 #ifdef __VISUALC__
487 #pragma warning( default : 4097 )
488 #endif
489
490 // a macro to get the virtual root, returns NULL if none
491 #define GET_VIRTUAL_ROOT() ((wxVirtualNode *)m_pVirtualRoot)
492
493 // returns true if the item is the virtual root
494 #define IS_VIRTUAL_ROOT(item) (HITEM(item) == TVI_ROOT)
495
496 // a class which encapsulates the tree traversal logic: it vists all (unless
497 // OnVisit() returns false) items under the given one
498 class wxTreeTraversal
499 {
500 public:
501 wxTreeTraversal(const wxTreeCtrl *tree)
502 {
503 m_tree = tree;
504 }
505
506 // give it a virtual dtor: not really needed as the class is never used
507 // polymorphically and not even allocated on heap at all, but this is safer
508 // (in case it ever is) and silences the compiler warnings for now
509 virtual ~wxTreeTraversal() { }
510
511 // do traverse the tree: visit all items (recursively by default) under the
512 // given one; return true if all items were traversed or false if the
513 // traversal was aborted because OnVisit returned false
514 bool DoTraverse(const wxTreeItemId& root, bool recursively = true);
515
516 // override this function to do whatever is needed for each item, return
517 // false to stop traversing
518 virtual bool OnVisit(const wxTreeItemId& item) = 0;
519
520 protected:
521 const wxTreeCtrl *GetTree() const { return m_tree; }
522
523 private:
524 bool Traverse(const wxTreeItemId& root, bool recursively);
525
526 const wxTreeCtrl *m_tree;
527
528 wxDECLARE_NO_COPY_CLASS(wxTreeTraversal);
529 };
530
531 // internal class for getting the selected items
532 class TraverseSelections : public wxTreeTraversal
533 {
534 public:
535 TraverseSelections(const wxTreeCtrl *tree,
536 wxArrayTreeItemIds& selections)
537 : wxTreeTraversal(tree), m_selections(selections)
538 {
539 m_selections.Empty();
540
541 if (tree->GetCount() > 0)
542 DoTraverse(tree->GetRootItem());
543 }
544
545 virtual bool OnVisit(const wxTreeItemId& item)
546 {
547 const wxTreeCtrl * const tree = GetTree();
548
549 // can't visit a virtual node.
550 if ( (tree->GetRootItem() == item) && tree->HasFlag(wxTR_HIDE_ROOT) )
551 {
552 return true;
553 }
554
555 if ( ::IsItemSelected(GetHwndOf(tree), HITEM(item)) )
556 {
557 m_selections.Add(item);
558 }
559
560 return true;
561 }
562
563 size_t GetCount() const { return m_selections.GetCount(); }
564
565 private:
566 wxArrayTreeItemIds& m_selections;
567
568 wxDECLARE_NO_COPY_CLASS(TraverseSelections);
569 };
570
571 // internal class for counting tree items
572 class TraverseCounter : public wxTreeTraversal
573 {
574 public:
575 TraverseCounter(const wxTreeCtrl *tree,
576 const wxTreeItemId& root,
577 bool recursively)
578 : wxTreeTraversal(tree)
579 {
580 m_count = 0;
581
582 DoTraverse(root, recursively);
583 }
584
585 virtual bool OnVisit(const wxTreeItemId& WXUNUSED(item))
586 {
587 m_count++;
588
589 return true;
590 }
591
592 size_t GetCount() const { return m_count; }
593
594 private:
595 size_t m_count;
596
597 wxDECLARE_NO_COPY_CLASS(TraverseCounter);
598 };
599
600 // ----------------------------------------------------------------------------
601 // wxWin macros
602 // ----------------------------------------------------------------------------
603
604 #if wxUSE_EXTENDED_RTTI
605 WX_DEFINE_FLAGS( wxTreeCtrlStyle )
606
607 wxBEGIN_FLAGS( wxTreeCtrlStyle )
608 // new style border flags, we put them first to
609 // use them for streaming out
610 wxFLAGS_MEMBER(wxBORDER_SIMPLE)
611 wxFLAGS_MEMBER(wxBORDER_SUNKEN)
612 wxFLAGS_MEMBER(wxBORDER_DOUBLE)
613 wxFLAGS_MEMBER(wxBORDER_RAISED)
614 wxFLAGS_MEMBER(wxBORDER_STATIC)
615 wxFLAGS_MEMBER(wxBORDER_NONE)
616
617 // old style border flags
618 wxFLAGS_MEMBER(wxSIMPLE_BORDER)
619 wxFLAGS_MEMBER(wxSUNKEN_BORDER)
620 wxFLAGS_MEMBER(wxDOUBLE_BORDER)
621 wxFLAGS_MEMBER(wxRAISED_BORDER)
622 wxFLAGS_MEMBER(wxSTATIC_BORDER)
623 wxFLAGS_MEMBER(wxBORDER)
624
625 // standard window styles
626 wxFLAGS_MEMBER(wxTAB_TRAVERSAL)
627 wxFLAGS_MEMBER(wxCLIP_CHILDREN)
628 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW)
629 wxFLAGS_MEMBER(wxWANTS_CHARS)
630 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE)
631 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB )
632 wxFLAGS_MEMBER(wxVSCROLL)
633 wxFLAGS_MEMBER(wxHSCROLL)
634
635 wxFLAGS_MEMBER(wxTR_EDIT_LABELS)
636 wxFLAGS_MEMBER(wxTR_NO_BUTTONS)
637 wxFLAGS_MEMBER(wxTR_HAS_BUTTONS)
638 wxFLAGS_MEMBER(wxTR_TWIST_BUTTONS)
639 wxFLAGS_MEMBER(wxTR_NO_LINES)
640 wxFLAGS_MEMBER(wxTR_FULL_ROW_HIGHLIGHT)
641 wxFLAGS_MEMBER(wxTR_LINES_AT_ROOT)
642 wxFLAGS_MEMBER(wxTR_HIDE_ROOT)
643 wxFLAGS_MEMBER(wxTR_ROW_LINES)
644 wxFLAGS_MEMBER(wxTR_HAS_VARIABLE_ROW_HEIGHT)
645 wxFLAGS_MEMBER(wxTR_SINGLE)
646 wxFLAGS_MEMBER(wxTR_MULTIPLE)
647 #if WXWIN_COMPATIBILITY_2_8
648 wxFLAGS_MEMBER(wxTR_EXTENDED)
649 #endif
650 wxFLAGS_MEMBER(wxTR_DEFAULT_STYLE)
651
652 wxEND_FLAGS( wxTreeCtrlStyle )
653
654 IMPLEMENT_DYNAMIC_CLASS_XTI(wxTreeCtrl, wxControl,"wx/treectrl.h")
655
656 wxBEGIN_PROPERTIES_TABLE(wxTreeCtrl)
657 wxEVENT_PROPERTY( TextUpdated , wxEVT_COMMAND_TEXT_UPDATED , wxCommandEvent )
658 wxEVENT_RANGE_PROPERTY( TreeEvent , wxEVT_COMMAND_TREE_BEGIN_DRAG , wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK , wxTreeEvent )
659 wxPROPERTY_FLAGS( WindowStyle , wxTreeCtrlStyle , long , SetWindowStyleFlag , GetWindowStyleFlag , EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
660 wxEND_PROPERTIES_TABLE()
661
662 wxBEGIN_HANDLERS_TABLE(wxTreeCtrl)
663 wxEND_HANDLERS_TABLE()
664
665 wxCONSTRUCTOR_5( wxTreeCtrl , wxWindow* , Parent , wxWindowID , Id , wxPoint , Position , wxSize , Size , long , WindowStyle )
666 #else
667 IMPLEMENT_DYNAMIC_CLASS(wxTreeCtrl, wxControl)
668 #endif
669
670 // ----------------------------------------------------------------------------
671 // constants
672 // ----------------------------------------------------------------------------
673
674 // indices in gs_expandEvents table below
675 enum
676 {
677 IDX_COLLAPSE,
678 IDX_EXPAND,
679 IDX_WHAT_MAX
680 };
681
682 enum
683 {
684 IDX_DONE,
685 IDX_DOING,
686 IDX_HOW_MAX
687 };
688
689 // handy table for sending events - it has to be initialized during run-time
690 // now so can't be const any more
691 static /* const */ wxEventType gs_expandEvents[IDX_WHAT_MAX][IDX_HOW_MAX];
692
693 /*
694 but logically it's a const table with the following entries:
695 =
696 {
697 { wxEVT_COMMAND_TREE_ITEM_COLLAPSED, wxEVT_COMMAND_TREE_ITEM_COLLAPSING },
698 { wxEVT_COMMAND_TREE_ITEM_EXPANDED, wxEVT_COMMAND_TREE_ITEM_EXPANDING }
699 };
700 */
701
702 // ============================================================================
703 // implementation
704 // ============================================================================
705
706 // ----------------------------------------------------------------------------
707 // tree traversal
708 // ----------------------------------------------------------------------------
709
710 bool wxTreeTraversal::DoTraverse(const wxTreeItemId& root, bool recursively)
711 {
712 if ( !OnVisit(root) )
713 return false;
714
715 return Traverse(root, recursively);
716 }
717
718 bool wxTreeTraversal::Traverse(const wxTreeItemId& root, bool recursively)
719 {
720 wxTreeItemIdValue cookie;
721 wxTreeItemId child = m_tree->GetFirstChild(root, cookie);
722 while ( child.IsOk() )
723 {
724 // depth first traversal
725 if ( recursively && !Traverse(child, true) )
726 return false;
727
728 if ( !OnVisit(child) )
729 return false;
730
731 child = m_tree->GetNextChild(root, cookie);
732 }
733
734 return true;
735 }
736
737 // ----------------------------------------------------------------------------
738 // construction and destruction
739 // ----------------------------------------------------------------------------
740
741 void wxTreeCtrl::Init()
742 {
743 m_textCtrl = NULL;
744 m_hasAnyAttr = false;
745 #if wxUSE_DRAGIMAGE
746 m_dragImage = NULL;
747 #endif
748 m_pVirtualRoot = NULL;
749 m_dragStarted = false;
750 m_focusLost = true;
751 m_changingSelection = false;
752 m_triggerStateImageClick = false;
753 m_mouseUpDeselect = false;
754
755 // initialize the global array of events now as it can't be done statically
756 // with the wxEVT_XXX values being allocated during run-time only
757 gs_expandEvents[IDX_COLLAPSE][IDX_DONE] = wxEVT_COMMAND_TREE_ITEM_COLLAPSED;
758 gs_expandEvents[IDX_COLLAPSE][IDX_DOING] = wxEVT_COMMAND_TREE_ITEM_COLLAPSING;
759 gs_expandEvents[IDX_EXPAND][IDX_DONE] = wxEVT_COMMAND_TREE_ITEM_EXPANDED;
760 gs_expandEvents[IDX_EXPAND][IDX_DOING] = wxEVT_COMMAND_TREE_ITEM_EXPANDING;
761 }
762
763 bool wxTreeCtrl::Create(wxWindow *parent,
764 wxWindowID id,
765 const wxPoint& pos,
766 const wxSize& size,
767 long style,
768 const wxValidator& validator,
769 const wxString& name)
770 {
771 Init();
772
773 if ( (style & wxBORDER_MASK) == wxBORDER_DEFAULT )
774 style |= wxBORDER_SUNKEN;
775
776 if ( !CreateControl(parent, id, pos, size, style, validator, name) )
777 return false;
778
779 WXDWORD exStyle = 0;
780 DWORD wstyle = MSWGetStyle(m_windowStyle, & exStyle);
781 wstyle |= WS_TABSTOP | TVS_SHOWSELALWAYS;
782
783 if ( !(m_windowStyle & wxTR_NO_LINES) )
784 wstyle |= TVS_HASLINES;
785 if ( m_windowStyle & wxTR_HAS_BUTTONS )
786 wstyle |= TVS_HASBUTTONS;
787
788 if ( m_windowStyle & wxTR_EDIT_LABELS )
789 wstyle |= TVS_EDITLABELS;
790
791 if ( m_windowStyle & wxTR_LINES_AT_ROOT )
792 wstyle |= TVS_LINESATROOT;
793
794 if ( m_windowStyle & wxTR_FULL_ROW_HIGHLIGHT )
795 {
796 if ( wxApp::GetComCtl32Version() >= 471 )
797 wstyle |= TVS_FULLROWSELECT;
798 }
799
800 #if !defined(__WXWINCE__) && defined(TVS_INFOTIP)
801 // Need so that TVN_GETINFOTIP messages will be sent
802 wstyle |= TVS_INFOTIP;
803 #endif
804
805 // Create the tree control.
806 if ( !MSWCreateControl(WC_TREEVIEW, wstyle, pos, size) )
807 return false;
808
809 #if wxUSE_COMCTL32_SAFELY
810 wxWindow::SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
811 wxWindow::SetForegroundColour(wxWindow::GetParent()->GetForegroundColour());
812 #elif 1
813 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
814 SetForegroundColour(wxWindow::GetParent()->GetForegroundColour());
815 #else
816 // This works around a bug in the Windows tree control whereby for some versions
817 // of comctrl32, setting any colour actually draws the background in black.
818 // This will initialise the background to the system colour.
819 // THIS FIX NOW REVERTED since it caused problems on _other_ systems.
820 // Assume the user has an updated comctl32.dll.
821 ::SendMessage(GetHwnd(), TVM_SETBKCOLOR, 0,-1);
822 wxWindow::SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
823 SetForegroundColour(wxWindow::GetParent()->GetForegroundColour());
824 #endif
825
826 wxSetCCUnicodeFormat(GetHwnd());
827
828 return true;
829 }
830
831 wxTreeCtrl::~wxTreeCtrl()
832 {
833 // delete any attributes
834 if ( m_hasAnyAttr )
835 {
836 WX_CLEAR_HASH_MAP(wxMapTreeAttr, m_attrs);
837
838 // prevent TVN_DELETEITEM handler from deleting the attributes again!
839 m_hasAnyAttr = false;
840 }
841
842 DeleteTextCtrl();
843
844 // delete user data to prevent memory leaks
845 // also deletes hidden root node storage.
846 DeleteAllItems();
847 }
848
849 // ----------------------------------------------------------------------------
850 // accessors
851 // ----------------------------------------------------------------------------
852
853 /* static */ wxVisualAttributes
854 wxTreeCtrl::GetClassDefaultAttributes(wxWindowVariant variant)
855 {
856 wxVisualAttributes attrs = GetCompositeControlsDefaultAttributes(variant);
857
858 // common controls have their own default font
859 attrs.font = wxGetCCDefaultFont();
860
861 return attrs;
862 }
863
864
865 // simple wrappers which add error checking in debug mode
866
867 bool wxTreeCtrl::DoGetItem(wxTreeViewItem *tvItem) const
868 {
869 wxCHECK_MSG( tvItem->hItem != TVI_ROOT, false,
870 wxT("can't retrieve virtual root item") );
871
872 if ( !TreeView_GetItem(GetHwnd(), tvItem) )
873 {
874 wxLogLastError(wxT("TreeView_GetItem"));
875
876 return false;
877 }
878
879 return true;
880 }
881
882 void wxTreeCtrl::DoSetItem(wxTreeViewItem *tvItem)
883 {
884 TreeItemUnlocker unlocker(tvItem->hItem);
885
886 if ( TreeView_SetItem(GetHwnd(), tvItem) == -1 )
887 {
888 wxLogLastError(wxT("TreeView_SetItem"));
889 }
890 }
891
892 unsigned int wxTreeCtrl::GetCount() const
893 {
894 return (unsigned int)TreeView_GetCount(GetHwnd());
895 }
896
897 unsigned int wxTreeCtrl::GetIndent() const
898 {
899 return TreeView_GetIndent(GetHwnd());
900 }
901
902 void wxTreeCtrl::SetIndent(unsigned int indent)
903 {
904 TreeView_SetIndent(GetHwnd(), indent);
905 }
906
907 void wxTreeCtrl::SetAnyImageList(wxImageList *imageList, int which)
908 {
909 // no error return
910 (void) TreeView_SetImageList(GetHwnd(),
911 imageList ? imageList->GetHIMAGELIST() : 0,
912 which);
913 }
914
915 void wxTreeCtrl::SetImageList(wxImageList *imageList)
916 {
917 if (m_ownsImageListNormal)
918 delete m_imageListNormal;
919
920 SetAnyImageList(m_imageListNormal = imageList, TVSIL_NORMAL);
921 m_ownsImageListNormal = false;
922 }
923
924 void wxTreeCtrl::SetStateImageList(wxImageList *imageList)
925 {
926 if (m_ownsImageListState) delete m_imageListState;
927 SetAnyImageList(m_imageListState = imageList, TVSIL_STATE);
928 m_ownsImageListState = false;
929 }
930
931 size_t wxTreeCtrl::GetChildrenCount(const wxTreeItemId& item,
932 bool recursively) const
933 {
934 wxCHECK_MSG( item.IsOk(), 0u, wxT("invalid tree item") );
935
936 TraverseCounter counter(this, item, recursively);
937 return counter.GetCount() - 1;
938 }
939
940 // ----------------------------------------------------------------------------
941 // control colours
942 // ----------------------------------------------------------------------------
943
944 bool wxTreeCtrl::SetBackgroundColour(const wxColour &colour)
945 {
946 #if !wxUSE_COMCTL32_SAFELY
947 if ( !wxWindowBase::SetBackgroundColour(colour) )
948 return false;
949
950 ::SendMessage(GetHwnd(), TVM_SETBKCOLOR, 0, colour.GetPixel());
951 #endif
952
953 return true;
954 }
955
956 bool wxTreeCtrl::SetForegroundColour(const wxColour &colour)
957 {
958 #if !wxUSE_COMCTL32_SAFELY
959 if ( !wxWindowBase::SetForegroundColour(colour) )
960 return false;
961
962 ::SendMessage(GetHwnd(), TVM_SETTEXTCOLOR, 0, colour.GetPixel());
963 #endif
964
965 return true;
966 }
967
968 // ----------------------------------------------------------------------------
969 // Item access
970 // ----------------------------------------------------------------------------
971
972 bool wxTreeCtrl::IsHiddenRoot(const wxTreeItemId& item) const
973 {
974 return HITEM(item) == TVI_ROOT && HasFlag(wxTR_HIDE_ROOT);
975 }
976
977 wxString wxTreeCtrl::GetItemText(const wxTreeItemId& item) const
978 {
979 wxCHECK_MSG( item.IsOk(), wxEmptyString, wxT("invalid tree item") );
980
981 wxChar buf[512]; // the size is arbitrary...
982
983 wxTreeViewItem tvItem(item, TVIF_TEXT);
984 tvItem.pszText = buf;
985 tvItem.cchTextMax = WXSIZEOF(buf);
986 if ( !DoGetItem(&tvItem) )
987 {
988 // don't return some garbage which was on stack, but an empty string
989 buf[0] = wxT('\0');
990 }
991
992 return wxString(buf);
993 }
994
995 void wxTreeCtrl::SetItemText(const wxTreeItemId& item, const wxString& text)
996 {
997 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
998
999 if ( IS_VIRTUAL_ROOT(item) )
1000 return;
1001
1002 wxTreeViewItem tvItem(item, TVIF_TEXT);
1003 tvItem.pszText = (wxChar *)text.wx_str(); // conversion is ok
1004 DoSetItem(&tvItem);
1005
1006 // when setting the text of the item being edited, the text control should
1007 // be updated to reflect the new text as well, otherwise calling
1008 // SetItemText() in the OnBeginLabelEdit() handler doesn't have any effect
1009 //
1010 // don't use GetEditControl() here because m_textCtrl is not set yet
1011 HWND hwndEdit = TreeView_GetEditControl(GetHwnd());
1012 if ( hwndEdit )
1013 {
1014 if ( item == m_idEdited )
1015 {
1016 ::SetWindowText(hwndEdit, text.wx_str());
1017 }
1018 }
1019 }
1020
1021 int wxTreeCtrl::GetItemImage(const wxTreeItemId& item,
1022 wxTreeItemIcon which) const
1023 {
1024 wxCHECK_MSG( item.IsOk(), -1, wxT("invalid tree item") );
1025
1026 if ( IsHiddenRoot(item) )
1027 {
1028 // no images for hidden root item
1029 return -1;
1030 }
1031
1032 wxTreeItemParam *param = GetItemParam(item);
1033
1034 return param && param->HasImage(which) ? param->GetImage(which) : -1;
1035 }
1036
1037 void wxTreeCtrl::SetItemImage(const wxTreeItemId& item, int image,
1038 wxTreeItemIcon which)
1039 {
1040 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1041 wxCHECK_RET( which >= 0 &&
1042 which < wxTreeItemIcon_Max,
1043 wxT("invalid image index"));
1044
1045
1046 if ( IsHiddenRoot(item) )
1047 {
1048 // no images for hidden root item
1049 return;
1050 }
1051
1052 wxTreeItemParam *data = GetItemParam(item);
1053 if ( !data )
1054 return;
1055
1056 data->SetImage(image, which);
1057
1058 RefreshItem(item);
1059 }
1060
1061 wxTreeItemParam *wxTreeCtrl::GetItemParam(const wxTreeItemId& item) const
1062 {
1063 wxCHECK_MSG( item.IsOk(), NULL, wxT("invalid tree item") );
1064
1065 wxTreeViewItem tvItem(item, TVIF_PARAM);
1066
1067 // hidden root may still have data.
1068 if ( IS_VIRTUAL_ROOT(item) )
1069 {
1070 return GET_VIRTUAL_ROOT()->GetParam();
1071 }
1072
1073 // visible node.
1074 if ( !DoGetItem(&tvItem) )
1075 {
1076 return NULL;
1077 }
1078
1079 return (wxTreeItemParam *)tvItem.lParam;
1080 }
1081
1082 bool wxTreeCtrl::HandleTreeEvent(wxTreeEvent& event) const
1083 {
1084 if ( event.m_item.IsOk() )
1085 {
1086 event.SetClientObject(GetItemData(event.m_item));
1087 }
1088
1089 return HandleWindowEvent(event);
1090 }
1091
1092 wxTreeItemData *wxTreeCtrl::GetItemData(const wxTreeItemId& item) const
1093 {
1094 wxTreeItemParam *data = GetItemParam(item);
1095
1096 return data ? data->GetData() : NULL;
1097 }
1098
1099 void wxTreeCtrl::SetItemData(const wxTreeItemId& item, wxTreeItemData *data)
1100 {
1101 // first, associate this piece of data with this item
1102 if ( data )
1103 {
1104 data->SetId(item);
1105 }
1106
1107 wxTreeItemParam *param = GetItemParam(item);
1108
1109 wxCHECK_RET( param, wxT("failed to change tree items data") );
1110
1111 param->SetData(data);
1112 }
1113
1114 void wxTreeCtrl::SetItemHasChildren(const wxTreeItemId& item, bool has)
1115 {
1116 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1117
1118 if ( IS_VIRTUAL_ROOT(item) )
1119 return;
1120
1121 wxTreeViewItem tvItem(item, TVIF_CHILDREN);
1122 tvItem.cChildren = (int)has;
1123 DoSetItem(&tvItem);
1124 }
1125
1126 void wxTreeCtrl::SetItemBold(const wxTreeItemId& item, bool bold)
1127 {
1128 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1129
1130 if ( IS_VIRTUAL_ROOT(item) )
1131 return;
1132
1133 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_BOLD);
1134 tvItem.state = bold ? TVIS_BOLD : 0;
1135 DoSetItem(&tvItem);
1136 }
1137
1138 void wxTreeCtrl::SetItemDropHighlight(const wxTreeItemId& item, bool highlight)
1139 {
1140 if ( IS_VIRTUAL_ROOT(item) )
1141 return;
1142
1143 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_DROPHILITED);
1144 tvItem.state = highlight ? TVIS_DROPHILITED : 0;
1145 DoSetItem(&tvItem);
1146 }
1147
1148 void wxTreeCtrl::RefreshItem(const wxTreeItemId& item)
1149 {
1150 if ( IS_VIRTUAL_ROOT(item) )
1151 return;
1152
1153 wxRect rect;
1154 if ( GetBoundingRect(item, rect) )
1155 {
1156 RefreshRect(rect);
1157 }
1158 }
1159
1160 wxColour wxTreeCtrl::GetItemTextColour(const wxTreeItemId& item) const
1161 {
1162 wxCHECK_MSG( item.IsOk(), wxNullColour, wxT("invalid tree item") );
1163
1164 wxMapTreeAttr::const_iterator it = m_attrs.find(item.m_pItem);
1165 return it == m_attrs.end() ? wxNullColour : it->second->GetTextColour();
1166 }
1167
1168 wxColour wxTreeCtrl::GetItemBackgroundColour(const wxTreeItemId& item) const
1169 {
1170 wxCHECK_MSG( item.IsOk(), wxNullColour, wxT("invalid tree item") );
1171
1172 wxMapTreeAttr::const_iterator it = m_attrs.find(item.m_pItem);
1173 return it == m_attrs.end() ? wxNullColour : it->second->GetBackgroundColour();
1174 }
1175
1176 wxFont wxTreeCtrl::GetItemFont(const wxTreeItemId& item) const
1177 {
1178 wxCHECK_MSG( item.IsOk(), wxNullFont, wxT("invalid tree item") );
1179
1180 wxMapTreeAttr::const_iterator it = m_attrs.find(item.m_pItem);
1181 return it == m_attrs.end() ? wxNullFont : it->second->GetFont();
1182 }
1183
1184 void wxTreeCtrl::SetItemTextColour(const wxTreeItemId& item,
1185 const wxColour& col)
1186 {
1187 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1188
1189 wxTreeItemAttr *attr;
1190 wxMapTreeAttr::iterator it = m_attrs.find(item.m_pItem);
1191 if ( it == m_attrs.end() )
1192 {
1193 m_hasAnyAttr = true;
1194
1195 m_attrs[item.m_pItem] =
1196 attr = new wxTreeItemAttr;
1197 }
1198 else
1199 {
1200 attr = it->second;
1201 }
1202
1203 attr->SetTextColour(col);
1204
1205 RefreshItem(item);
1206 }
1207
1208 void wxTreeCtrl::SetItemBackgroundColour(const wxTreeItemId& item,
1209 const wxColour& col)
1210 {
1211 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1212
1213 wxTreeItemAttr *attr;
1214 wxMapTreeAttr::iterator it = m_attrs.find(item.m_pItem);
1215 if ( it == m_attrs.end() )
1216 {
1217 m_hasAnyAttr = true;
1218
1219 m_attrs[item.m_pItem] =
1220 attr = new wxTreeItemAttr;
1221 }
1222 else // already in the hash
1223 {
1224 attr = it->second;
1225 }
1226
1227 attr->SetBackgroundColour(col);
1228
1229 RefreshItem(item);
1230 }
1231
1232 void wxTreeCtrl::SetItemFont(const wxTreeItemId& item, const wxFont& font)
1233 {
1234 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
1235
1236 wxTreeItemAttr *attr;
1237 wxMapTreeAttr::iterator it = m_attrs.find(item.m_pItem);
1238 if ( it == m_attrs.end() )
1239 {
1240 m_hasAnyAttr = true;
1241
1242 m_attrs[item.m_pItem] =
1243 attr = new wxTreeItemAttr;
1244 }
1245 else // already in the hash
1246 {
1247 attr = it->second;
1248 }
1249
1250 attr->SetFont(font);
1251
1252 // Reset the item's text to ensure that the bounding rect will be adjusted
1253 // for the new font.
1254 SetItemText(item, GetItemText(item));
1255
1256 RefreshItem(item);
1257 }
1258
1259 // ----------------------------------------------------------------------------
1260 // Item status
1261 // ----------------------------------------------------------------------------
1262
1263 bool wxTreeCtrl::IsVisible(const wxTreeItemId& item) const
1264 {
1265 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1266
1267 if ( item == wxTreeItemId(TVI_ROOT) )
1268 {
1269 // virtual (hidden) root is never visible
1270 return false;
1271 }
1272
1273 // Bug in Gnu-Win32 headers, so don't use the macro TreeView_GetItemRect
1274 RECT rect;
1275
1276 // this ugliness comes directly from MSDN - it *is* the correct way to pass
1277 // the HTREEITEM with TVM_GETITEMRECT
1278 *(HTREEITEM *)&rect = HITEM(item);
1279
1280 // true means to get rect for just the text, not the whole line
1281 if ( !::SendMessage(GetHwnd(), TVM_GETITEMRECT, true, (LPARAM)&rect) )
1282 {
1283 // if TVM_GETITEMRECT returned false, then the item is definitely not
1284 // visible (because its parent is not expanded)
1285 return false;
1286 }
1287
1288 // however if it returned true, the item might still be outside the
1289 // currently visible part of the tree, test for it (notice that partly
1290 // visible means visible here)
1291 return rect.bottom > 0 && rect.top < GetClientSize().y;
1292 }
1293
1294 bool wxTreeCtrl::ItemHasChildren(const wxTreeItemId& item) const
1295 {
1296 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1297
1298 if ( IS_VIRTUAL_ROOT(item) )
1299 {
1300 wxTreeItemIdValue cookie;
1301 return GetFirstChild(item, cookie).IsOk();
1302 }
1303
1304 wxTreeViewItem tvItem(item, TVIF_CHILDREN);
1305 DoGetItem(&tvItem);
1306
1307 return tvItem.cChildren != 0;
1308 }
1309
1310 bool wxTreeCtrl::IsExpanded(const wxTreeItemId& item) const
1311 {
1312 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1313
1314 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_EXPANDED);
1315 DoGetItem(&tvItem);
1316
1317 return (tvItem.state & TVIS_EXPANDED) != 0;
1318 }
1319
1320 bool wxTreeCtrl::IsSelected(const wxTreeItemId& item) const
1321 {
1322 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1323
1324 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_SELECTED);
1325 DoGetItem(&tvItem);
1326
1327 return (tvItem.state & TVIS_SELECTED) != 0;
1328 }
1329
1330 bool wxTreeCtrl::IsBold(const wxTreeItemId& item) const
1331 {
1332 wxCHECK_MSG( item.IsOk(), false, wxT("invalid tree item") );
1333
1334 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_BOLD);
1335 DoGetItem(&tvItem);
1336
1337 return (tvItem.state & TVIS_BOLD) != 0;
1338 }
1339
1340 // ----------------------------------------------------------------------------
1341 // navigation
1342 // ----------------------------------------------------------------------------
1343
1344 wxTreeItemId wxTreeCtrl::GetRootItem() const
1345 {
1346 // Root may be real (visible) or virtual (hidden).
1347 if ( GET_VIRTUAL_ROOT() )
1348 return TVI_ROOT;
1349
1350 return wxTreeItemId(TreeView_GetRoot(GetHwnd()));
1351 }
1352
1353 wxTreeItemId wxTreeCtrl::GetSelection() const
1354 {
1355 wxCHECK_MSG( !HasFlag(wxTR_MULTIPLE), wxTreeItemId(),
1356 wxT("this only works with single selection controls") );
1357
1358 return GetFocusedItem();
1359 }
1360
1361 wxTreeItemId wxTreeCtrl::GetFocusedItem() const
1362 {
1363 return wxTreeItemId(TreeView_GetSelection(GetHwnd()));
1364 }
1365
1366 wxTreeItemId wxTreeCtrl::GetItemParent(const wxTreeItemId& item) const
1367 {
1368 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1369
1370 HTREEITEM hItem;
1371
1372 if ( IS_VIRTUAL_ROOT(item) )
1373 {
1374 // no parent for the virtual root
1375 hItem = 0;
1376 }
1377 else // normal item
1378 {
1379 hItem = TreeView_GetParent(GetHwnd(), HITEM(item));
1380 if ( !hItem && HasFlag(wxTR_HIDE_ROOT) )
1381 {
1382 // the top level items should have the virtual root as their parent
1383 hItem = TVI_ROOT;
1384 }
1385 }
1386
1387 return wxTreeItemId(hItem);
1388 }
1389
1390 wxTreeItemId wxTreeCtrl::GetFirstChild(const wxTreeItemId& item,
1391 wxTreeItemIdValue& cookie) const
1392 {
1393 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1394
1395 // remember the last child returned in 'cookie'
1396 cookie = TreeView_GetChild(GetHwnd(), HITEM(item));
1397
1398 return wxTreeItemId(cookie);
1399 }
1400
1401 wxTreeItemId wxTreeCtrl::GetNextChild(const wxTreeItemId& WXUNUSED(item),
1402 wxTreeItemIdValue& cookie) const
1403 {
1404 wxTreeItemId fromCookie(cookie);
1405
1406 HTREEITEM hitem = HITEM(fromCookie);
1407
1408 hitem = TreeView_GetNextSibling(GetHwnd(), hitem);
1409
1410 wxTreeItemId item(hitem);
1411
1412 cookie = item.m_pItem;
1413
1414 return item;
1415 }
1416
1417 wxTreeItemId wxTreeCtrl::GetLastChild(const wxTreeItemId& item) const
1418 {
1419 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1420
1421 // can this be done more efficiently?
1422 wxTreeItemIdValue cookie;
1423
1424 wxTreeItemId childLast,
1425 child = GetFirstChild(item, cookie);
1426 while ( child.IsOk() )
1427 {
1428 childLast = child;
1429 child = GetNextChild(item, cookie);
1430 }
1431
1432 return childLast;
1433 }
1434
1435 wxTreeItemId wxTreeCtrl::GetNextSibling(const wxTreeItemId& item) const
1436 {
1437 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1438 return wxTreeItemId(TreeView_GetNextSibling(GetHwnd(), HITEM(item)));
1439 }
1440
1441 wxTreeItemId wxTreeCtrl::GetPrevSibling(const wxTreeItemId& item) const
1442 {
1443 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1444 return wxTreeItemId(TreeView_GetPrevSibling(GetHwnd(), HITEM(item)));
1445 }
1446
1447 wxTreeItemId wxTreeCtrl::GetFirstVisibleItem() const
1448 {
1449 return wxTreeItemId(TreeView_GetFirstVisible(GetHwnd()));
1450 }
1451
1452 wxTreeItemId wxTreeCtrl::GetNextVisible(const wxTreeItemId& item) const
1453 {
1454 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1455 wxASSERT_MSG( IsVisible(item), wxT("The item you call GetNextVisible() for must be visible itself!"));
1456
1457 wxTreeItemId next(TreeView_GetNextVisible(GetHwnd(), HITEM(item)));
1458 if ( next.IsOk() && !IsVisible(next) )
1459 {
1460 // Win32 considers that any non-collapsed item is visible while we want
1461 // to return only really visible items
1462 next.Unset();
1463 }
1464
1465 return next;
1466 }
1467
1468 wxTreeItemId wxTreeCtrl::GetPrevVisible(const wxTreeItemId& item) const
1469 {
1470 wxCHECK_MSG( item.IsOk(), wxTreeItemId(), wxT("invalid tree item") );
1471 wxASSERT_MSG( IsVisible(item), wxT("The item you call GetPrevVisible() for must be visible itself!"));
1472
1473 wxTreeItemId prev(TreeView_GetPrevVisible(GetHwnd(), HITEM(item)));
1474 if ( prev.IsOk() && !IsVisible(prev) )
1475 {
1476 // just as above, Win32 function will happily return the previous item
1477 // in the tree for the first visible item too
1478 prev.Unset();
1479 }
1480
1481 return prev;
1482 }
1483
1484 // ----------------------------------------------------------------------------
1485 // multiple selections emulation
1486 // ----------------------------------------------------------------------------
1487
1488 size_t wxTreeCtrl::GetSelections(wxArrayTreeItemIds& selections) const
1489 {
1490 TraverseSelections selector(this, selections);
1491
1492 return selector.GetCount();
1493 }
1494
1495 // ----------------------------------------------------------------------------
1496 // Usual operations
1497 // ----------------------------------------------------------------------------
1498
1499 wxTreeItemId wxTreeCtrl::DoInsertAfter(const wxTreeItemId& parent,
1500 const wxTreeItemId& hInsertAfter,
1501 const wxString& text,
1502 int image, int selectedImage,
1503 wxTreeItemData *data)
1504 {
1505 wxCHECK_MSG( parent.IsOk() || !TreeView_GetRoot(GetHwnd()),
1506 wxTreeItemId(),
1507 wxT("can't have more than one root in the tree") );
1508
1509 TV_INSERTSTRUCT tvIns;
1510 tvIns.hParent = HITEM(parent);
1511 tvIns.hInsertAfter = HITEM(hInsertAfter);
1512
1513 // this is how we insert the item as the first child: supply a NULL
1514 // hInsertAfter
1515 if ( !tvIns.hInsertAfter )
1516 {
1517 tvIns.hInsertAfter = TVI_FIRST;
1518 }
1519
1520 UINT mask = 0;
1521 if ( !text.empty() )
1522 {
1523 mask |= TVIF_TEXT;
1524 tvIns.item.pszText = (wxChar *)text.wx_str(); // cast is ok
1525 }
1526 else
1527 {
1528 tvIns.item.pszText = NULL;
1529 tvIns.item.cchTextMax = 0;
1530 }
1531
1532 // create the param which will store the other item parameters
1533 wxTreeItemParam *param = new wxTreeItemParam;
1534
1535 // we return the images on demand as they depend on whether the item is
1536 // expanded or collapsed too in our case
1537 mask |= TVIF_IMAGE | TVIF_SELECTEDIMAGE;
1538 tvIns.item.iImage = I_IMAGECALLBACK;
1539 tvIns.item.iSelectedImage = I_IMAGECALLBACK;
1540
1541 param->SetImage(image, wxTreeItemIcon_Normal);
1542 param->SetImage(selectedImage, wxTreeItemIcon_Selected);
1543
1544 mask |= TVIF_PARAM;
1545 tvIns.item.lParam = (LPARAM)param;
1546 tvIns.item.mask = mask;
1547
1548 // don't use the hack below for the children of hidden root: this results
1549 // in a crash inside comctl32.dll when we call TreeView_GetItemRect()
1550 const bool firstChild = !IsHiddenRoot(parent) &&
1551 !TreeView_GetChild(GetHwnd(), HITEM(parent));
1552
1553 HTREEITEM id = TreeView_InsertItem(GetHwnd(), &tvIns);
1554 if ( id == 0 )
1555 {
1556 wxLogLastError(wxT("TreeView_InsertItem"));
1557 }
1558
1559 // apparently some Windows versions (2000 and XP are reported to do this)
1560 // sometimes don't refresh the tree after adding the first child and so we
1561 // need this to make the "[+]" appear
1562 if ( firstChild )
1563 {
1564 RECT rect;
1565 TreeView_GetItemRect(GetHwnd(), HITEM(parent), &rect, FALSE);
1566 ::InvalidateRect(GetHwnd(), &rect, FALSE);
1567 }
1568
1569 // associate the application tree item with Win32 tree item handle
1570 param->SetItem(id);
1571
1572 // setup wxTreeItemData
1573 if ( data != NULL )
1574 {
1575 param->SetData(data);
1576 data->SetId(id);
1577 }
1578
1579 return wxTreeItemId(id);
1580 }
1581
1582 wxTreeItemId wxTreeCtrl::AddRoot(const wxString& text,
1583 int image, int selectedImage,
1584 wxTreeItemData *data)
1585 {
1586 if ( HasFlag(wxTR_HIDE_ROOT) )
1587 {
1588 wxASSERT_MSG( !m_pVirtualRoot, wxT("tree can have only a single root") );
1589
1590 // create a virtual root item, the parent for all the others
1591 wxTreeItemParam *param = new wxTreeItemParam;
1592 param->SetData(data);
1593
1594 m_pVirtualRoot = new wxVirtualNode(param);
1595
1596 return TVI_ROOT;
1597 }
1598
1599 return DoInsertAfter(wxTreeItemId(), wxTreeItemId(),
1600 text, image, selectedImage, data);
1601 }
1602
1603 wxTreeItemId wxTreeCtrl::DoInsertItem(const wxTreeItemId& parent,
1604 size_t index,
1605 const wxString& text,
1606 int image, int selectedImage,
1607 wxTreeItemData *data)
1608 {
1609 wxTreeItemId idPrev;
1610 if ( index == (size_t)-1 )
1611 {
1612 // special value: append to the end
1613 idPrev = TVI_LAST;
1614 }
1615 else // find the item from index
1616 {
1617 wxTreeItemIdValue cookie;
1618 wxTreeItemId idCur = GetFirstChild(parent, cookie);
1619 while ( index != 0 && idCur.IsOk() )
1620 {
1621 index--;
1622
1623 idPrev = idCur;
1624 idCur = GetNextChild(parent, cookie);
1625 }
1626
1627 // assert, not check: if the index is invalid, we will append the item
1628 // to the end
1629 wxASSERT_MSG( index == 0, wxT("bad index in wxTreeCtrl::InsertItem") );
1630 }
1631
1632 return DoInsertAfter(parent, idPrev, text, image, selectedImage, data);
1633 }
1634
1635 void wxTreeCtrl::Delete(const wxTreeItemId& item)
1636 {
1637 // unlock tree selections on vista, without this the
1638 // tree ctrl will eventually crash after item deletion
1639 TreeItemUnlocker unlock_all;
1640
1641 if ( HasFlag(wxTR_MULTIPLE) )
1642 {
1643 bool selected = IsSelected(item);
1644 wxTreeItemId next;
1645
1646 if ( selected )
1647 {
1648 next = TreeView_GetNextVisible(GetHwnd(), HITEM(item));
1649
1650 if ( !next.IsOk() )
1651 {
1652 next = TreeView_GetPrevVisible(GetHwnd(), HITEM(item));
1653 }
1654 }
1655
1656 {
1657 TempSetter set(m_changingSelection);
1658 if ( !TreeView_DeleteItem(GetHwnd(), HITEM(item)) )
1659 {
1660 wxLogLastError(wxT("TreeView_DeleteItem"));
1661 return;
1662 }
1663 }
1664
1665 if ( !selected )
1666 {
1667 return;
1668 }
1669
1670 if ( next.IsOk() )
1671 {
1672 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING, this, next);
1673
1674 if ( IsTreeEventAllowed(changingEvent) )
1675 {
1676 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED, this, next);
1677 (void)HandleTreeEvent(changedEvent);
1678 }
1679 else
1680 {
1681 DoUnselectItem(next);
1682 ClearFocusedItem();
1683 }
1684 }
1685 }
1686 else
1687 {
1688 if ( !TreeView_DeleteItem(GetHwnd(), HITEM(item)) )
1689 {
1690 wxLogLastError(wxT("TreeView_DeleteItem"));
1691 }
1692 }
1693 }
1694
1695 // delete all children (but don't delete the item itself)
1696 void wxTreeCtrl::DeleteChildren(const wxTreeItemId& item)
1697 {
1698 // unlock tree selections on vista for the duration of this call
1699 TreeItemUnlocker unlock_all;
1700
1701 wxTreeItemIdValue cookie;
1702
1703 wxArrayTreeItemIds children;
1704 wxTreeItemId child = GetFirstChild(item, cookie);
1705 while ( child.IsOk() )
1706 {
1707 children.Add(child);
1708
1709 child = GetNextChild(item, cookie);
1710 }
1711
1712 size_t nCount = children.Count();
1713 for ( size_t n = 0; n < nCount; n++ )
1714 {
1715 Delete(children[n]);
1716 }
1717 }
1718
1719 void wxTreeCtrl::DeleteAllItems()
1720 {
1721 // unlock tree selections on vista for the duration of this call
1722 TreeItemUnlocker unlock_all;
1723
1724 // delete the "virtual" root item.
1725 if ( GET_VIRTUAL_ROOT() )
1726 {
1727 delete GET_VIRTUAL_ROOT();
1728 m_pVirtualRoot = NULL;
1729 }
1730
1731 // and all the real items
1732
1733 if ( !TreeView_DeleteAllItems(GetHwnd()) )
1734 {
1735 wxLogLastError(wxT("TreeView_DeleteAllItems"));
1736 }
1737 }
1738
1739 void wxTreeCtrl::DoExpand(const wxTreeItemId& item, int flag)
1740 {
1741 wxASSERT_MSG( flag == TVE_COLLAPSE ||
1742 flag == (TVE_COLLAPSE | TVE_COLLAPSERESET) ||
1743 flag == TVE_EXPAND ||
1744 flag == TVE_TOGGLE,
1745 wxT("Unknown flag in wxTreeCtrl::DoExpand") );
1746
1747 // A hidden root can be neither expanded nor collapsed.
1748 wxCHECK_RET( !IsHiddenRoot(item),
1749 wxT("Can't expand/collapse hidden root node!") );
1750
1751 // TreeView_Expand doesn't send TVN_ITEMEXPAND(ING) messages, so we must
1752 // emulate them. This behaviour has changed slightly with comctl32.dll
1753 // v 4.70 - now it does send them but only the first time. To maintain
1754 // compatible behaviour and also in order to not have surprises with the
1755 // future versions, don't rely on this and still do everything ourselves.
1756 // To avoid that the messages be sent twice when the item is expanded for
1757 // the first time we must clear TVIS_EXPANDEDONCE style manually.
1758
1759 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_EXPANDEDONCE);
1760 tvItem.state = 0;
1761 DoSetItem(&tvItem);
1762
1763 if ( IsExpanded(item) )
1764 {
1765 wxTreeEvent event(wxEVT_COMMAND_TREE_ITEM_COLLAPSING,
1766 this, wxTreeItemId(item));
1767
1768 if ( !IsTreeEventAllowed(event) )
1769 return;
1770 }
1771
1772 if ( TreeView_Expand(GetHwnd(), HITEM(item), flag) )
1773 {
1774 if ( IsExpanded(item) )
1775 return;
1776
1777 wxTreeEvent event(wxEVT_COMMAND_TREE_ITEM_COLLAPSED, this, item);
1778 (void)HandleTreeEvent(event);
1779 }
1780 //else: change didn't took place, so do nothing at all
1781 }
1782
1783 void wxTreeCtrl::Expand(const wxTreeItemId& item)
1784 {
1785 DoExpand(item, TVE_EXPAND);
1786 }
1787
1788 void wxTreeCtrl::Collapse(const wxTreeItemId& item)
1789 {
1790 DoExpand(item, TVE_COLLAPSE);
1791 }
1792
1793 void wxTreeCtrl::CollapseAndReset(const wxTreeItemId& item)
1794 {
1795 DoExpand(item, TVE_COLLAPSE | TVE_COLLAPSERESET);
1796 }
1797
1798 void wxTreeCtrl::Toggle(const wxTreeItemId& item)
1799 {
1800 DoExpand(item, TVE_TOGGLE);
1801 }
1802
1803 void wxTreeCtrl::Unselect()
1804 {
1805 wxASSERT_MSG( !HasFlag(wxTR_MULTIPLE),
1806 wxT("doesn't make sense, may be you want UnselectAll()?") );
1807
1808 // the current focus
1809 HTREEITEM htFocus = (HTREEITEM)TreeView_GetSelection(GetHwnd());
1810
1811 if ( !htFocus )
1812 {
1813 return;
1814 }
1815
1816 if ( HasFlag(wxTR_MULTIPLE) )
1817 {
1818 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING,
1819 this, wxTreeItemId());
1820 changingEvent.m_itemOld = htFocus;
1821
1822 if ( IsTreeEventAllowed(changingEvent) )
1823 {
1824 ClearFocusedItem();
1825
1826 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
1827 this, wxTreeItemId());
1828 changedEvent.m_itemOld = htFocus;
1829 (void)HandleTreeEvent(changedEvent);
1830 }
1831 }
1832 else
1833 {
1834 ClearFocusedItem();
1835 }
1836 }
1837
1838 void wxTreeCtrl::DoUnselectAll()
1839 {
1840 wxArrayTreeItemIds selections;
1841 size_t count = GetSelections(selections);
1842
1843 for ( size_t n = 0; n < count; n++ )
1844 {
1845 DoUnselectItem(selections[n]);
1846 }
1847
1848 m_htSelStart.Unset();
1849 }
1850
1851 void wxTreeCtrl::UnselectAll()
1852 {
1853 if ( HasFlag(wxTR_MULTIPLE) )
1854 {
1855 HTREEITEM htFocus = (HTREEITEM)TreeView_GetSelection(GetHwnd());
1856 if ( !htFocus ) return;
1857
1858 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING, this);
1859 changingEvent.m_itemOld = htFocus;
1860
1861 if ( IsTreeEventAllowed(changingEvent) )
1862 {
1863 DoUnselectAll();
1864
1865 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED, this);
1866 changedEvent.m_itemOld = htFocus;
1867 (void)HandleTreeEvent(changedEvent);
1868 }
1869 }
1870 else
1871 {
1872 Unselect();
1873 }
1874 }
1875
1876 void wxTreeCtrl::DoSelectItem(const wxTreeItemId& item, bool select)
1877 {
1878 TempSetter set(m_changingSelection);
1879
1880 ::SelectItem(GetHwnd(), HITEM(item), select);
1881 }
1882
1883 void wxTreeCtrl::SelectItem(const wxTreeItemId& item, bool select)
1884 {
1885 wxCHECK_RET( !IsHiddenRoot(item), wxT("can't select hidden root item") );
1886
1887 if ( select == IsSelected(item) )
1888 {
1889 // nothing to do, the item is already in the requested state
1890 return;
1891 }
1892
1893 if ( HasFlag(wxTR_MULTIPLE) )
1894 {
1895 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING, this, item);
1896
1897 if ( IsTreeEventAllowed(changingEvent) )
1898 {
1899 HTREEITEM htFocus = (HTREEITEM)TreeView_GetSelection(GetHwnd());
1900 DoSelectItem(item, select);
1901
1902 if ( !htFocus )
1903 {
1904 SetFocusedItem(item);
1905 }
1906
1907 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
1908 this, item);
1909 (void)HandleTreeEvent(changedEvent);
1910 }
1911 }
1912 else // single selection
1913 {
1914 wxTreeItemId itemOld, itemNew;
1915 if ( select )
1916 {
1917 itemOld = GetSelection();
1918 itemNew = item;
1919 }
1920 else // deselecting the currently selected item
1921 {
1922 itemOld = item;
1923 // leave itemNew invalid
1924 }
1925
1926 // in spite of the docs (MSDN Jan 99 edition), we don't seem to receive
1927 // the notification from the control (i.e. TVN_SELCHANG{ED|ING}), so
1928 // send them ourselves
1929
1930 wxTreeEvent
1931 changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING, this, itemNew);
1932 changingEvent.SetOldItem(itemOld);
1933
1934 if ( IsTreeEventAllowed(changingEvent) )
1935 {
1936 if ( !TreeView_SelectItem(GetHwnd(), HITEM(itemNew)) )
1937 {
1938 wxLogLastError(wxT("TreeView_SelectItem"));
1939 }
1940 else // ok
1941 {
1942 SetFocusedItem(item);
1943
1944 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
1945 this, itemNew);
1946 changedEvent.SetOldItem(itemOld);
1947 (void)HandleTreeEvent(changedEvent);
1948 }
1949 }
1950 //else: program vetoed the change
1951 }
1952 }
1953
1954 void wxTreeCtrl::EnsureVisible(const wxTreeItemId& item)
1955 {
1956 wxCHECK_RET( !IsHiddenRoot(item), wxT("can't show hidden root item") );
1957
1958 // no error return
1959 TreeView_EnsureVisible(GetHwnd(), HITEM(item));
1960 }
1961
1962 void wxTreeCtrl::ScrollTo(const wxTreeItemId& item)
1963 {
1964 if ( !TreeView_SelectSetFirstVisible(GetHwnd(), HITEM(item)) )
1965 {
1966 wxLogLastError(wxT("TreeView_SelectSetFirstVisible"));
1967 }
1968 }
1969
1970 wxTextCtrl *wxTreeCtrl::GetEditControl() const
1971 {
1972 return m_textCtrl;
1973 }
1974
1975 void wxTreeCtrl::DeleteTextCtrl()
1976 {
1977 if ( m_textCtrl )
1978 {
1979 // the HWND corresponding to this control is deleted by the tree
1980 // control itself and we don't know when exactly this happens, so check
1981 // if the window still exists before calling UnsubclassWin()
1982 if ( !::IsWindow(GetHwndOf(m_textCtrl)) )
1983 {
1984 m_textCtrl->SetHWND(0);
1985 }
1986
1987 m_textCtrl->UnsubclassWin();
1988 m_textCtrl->SetHWND(0);
1989 delete m_textCtrl;
1990 m_textCtrl = NULL;
1991
1992 m_idEdited.Unset();
1993 }
1994 }
1995
1996 wxTextCtrl *wxTreeCtrl::EditLabel(const wxTreeItemId& item,
1997 wxClassInfo *textControlClass)
1998 {
1999 wxASSERT( textControlClass->IsKindOf(CLASSINFO(wxTextCtrl)) );
2000
2001 DeleteTextCtrl();
2002
2003 m_idEdited = item;
2004 m_textCtrl = (wxTextCtrl *)textControlClass->CreateObject();
2005 HWND hWnd = (HWND) TreeView_EditLabel(GetHwnd(), HITEM(item));
2006
2007 // this is not an error - the TVN_BEGINLABELEDIT handler might have
2008 // returned false
2009 if ( !hWnd )
2010 {
2011 delete m_textCtrl;
2012 m_textCtrl = NULL;
2013 return NULL;
2014 }
2015
2016 // textctrl is subclassed in MSWOnNotify
2017 return m_textCtrl;
2018 }
2019
2020 // End label editing, optionally cancelling the edit
2021 void wxTreeCtrl::DoEndEditLabel(bool discardChanges)
2022 {
2023 TreeView_EndEditLabelNow(GetHwnd(), discardChanges);
2024
2025 DeleteTextCtrl();
2026 }
2027
2028 wxTreeItemId wxTreeCtrl::DoTreeHitTest(const wxPoint& point, int& flags) const
2029 {
2030 TV_HITTESTINFO hitTestInfo;
2031 hitTestInfo.pt.x = (int)point.x;
2032 hitTestInfo.pt.y = (int)point.y;
2033
2034 (void) TreeView_HitTest(GetHwnd(), &hitTestInfo);
2035
2036 flags = 0;
2037
2038 // avoid repetition
2039 #define TRANSLATE_FLAG(flag) if ( hitTestInfo.flags & TVHT_##flag ) \
2040 flags |= wxTREE_HITTEST_##flag
2041
2042 TRANSLATE_FLAG(ABOVE);
2043 TRANSLATE_FLAG(BELOW);
2044 TRANSLATE_FLAG(NOWHERE);
2045 TRANSLATE_FLAG(ONITEMBUTTON);
2046 TRANSLATE_FLAG(ONITEMICON);
2047 TRANSLATE_FLAG(ONITEMINDENT);
2048 TRANSLATE_FLAG(ONITEMLABEL);
2049 TRANSLATE_FLAG(ONITEMRIGHT);
2050 TRANSLATE_FLAG(ONITEMSTATEICON);
2051 TRANSLATE_FLAG(TOLEFT);
2052 TRANSLATE_FLAG(TORIGHT);
2053
2054 #undef TRANSLATE_FLAG
2055
2056 return wxTreeItemId(hitTestInfo.hItem);
2057 }
2058
2059 bool wxTreeCtrl::GetBoundingRect(const wxTreeItemId& item,
2060 wxRect& rect,
2061 bool textOnly) const
2062 {
2063 RECT rc;
2064
2065 // Virtual root items have no bounding rectangle
2066 if ( IS_VIRTUAL_ROOT(item) )
2067 {
2068 return false;
2069 }
2070
2071 if ( TreeView_GetItemRect(GetHwnd(), HITEM(item),
2072 &rc, textOnly) )
2073 {
2074 rect = wxRect(wxPoint(rc.left, rc.top), wxPoint(rc.right, rc.bottom));
2075
2076 return true;
2077 }
2078 else
2079 {
2080 // couldn't retrieve rect: for example, item isn't visible
2081 return false;
2082 }
2083 }
2084
2085 void wxTreeCtrl::ClearFocusedItem()
2086 {
2087 TempSetter set(m_changingSelection);
2088
2089 if ( !TreeView_SelectItem(GetHwnd(), 0) )
2090 {
2091 wxLogLastError(wxT("TreeView_SelectItem"));
2092 }
2093 }
2094
2095 void wxTreeCtrl::SetFocusedItem(const wxTreeItemId& item)
2096 {
2097 TempSetter set(m_changingSelection);
2098
2099 ::SetFocus(GetHwnd(), HITEM(item));
2100 }
2101
2102 void wxTreeCtrl::DoUnselectItem(const wxTreeItemId& item)
2103 {
2104 TempSetter set(m_changingSelection);
2105
2106 ::UnselectItem(GetHwnd(), HITEM(item));
2107 }
2108
2109 void wxTreeCtrl::DoToggleItemSelection(const wxTreeItemId& item)
2110 {
2111 TempSetter set(m_changingSelection);
2112
2113 ::ToggleItemSelection(GetHwnd(), HITEM(item));
2114 }
2115
2116 // ----------------------------------------------------------------------------
2117 // sorting stuff
2118 // ----------------------------------------------------------------------------
2119
2120 // this is just a tiny namespace which is friend to wxTreeCtrl and so can use
2121 // functions such as IsDataIndirect()
2122 class wxTreeSortHelper
2123 {
2124 public:
2125 static int CALLBACK Compare(LPARAM data1, LPARAM data2, LPARAM tree);
2126
2127 private:
2128 static wxTreeItemId GetIdFromData(LPARAM lParam)
2129 {
2130 return ((wxTreeItemParam*)lParam)->GetItem();
2131 }
2132 };
2133
2134 int CALLBACK wxTreeSortHelper::Compare(LPARAM pItem1,
2135 LPARAM pItem2,
2136 LPARAM htree)
2137 {
2138 wxCHECK_MSG( pItem1 && pItem2, 0,
2139 wxT("sorting tree without data doesn't make sense") );
2140
2141 wxTreeCtrl *tree = (wxTreeCtrl *)htree;
2142
2143 return tree->OnCompareItems(GetIdFromData(pItem1),
2144 GetIdFromData(pItem2));
2145 }
2146
2147 void wxTreeCtrl::SortChildren(const wxTreeItemId& item)
2148 {
2149 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
2150
2151 // rely on the fact that TreeView_SortChildren does the same thing as our
2152 // default behaviour, i.e. sorts items alphabetically and so call it
2153 // directly if we're not in derived class (much more efficient!)
2154 // RN: Note that if you find you're code doesn't sort as expected this
2155 // may be why as if you don't use the DECLARE_CLASS/IMPLEMENT_CLASS
2156 // combo for your derived wxTreeCtrl if will sort without
2157 // OnCompareItems
2158 if ( GetClassInfo() == CLASSINFO(wxTreeCtrl) )
2159 {
2160 TreeView_SortChildren(GetHwnd(), HITEM(item), 0);
2161 }
2162 else
2163 {
2164 TV_SORTCB tvSort;
2165 tvSort.hParent = HITEM(item);
2166 tvSort.lpfnCompare = wxTreeSortHelper::Compare;
2167 tvSort.lParam = (LPARAM)this;
2168 TreeView_SortChildrenCB(GetHwnd(), &tvSort, 0 /* reserved */);
2169 }
2170 }
2171
2172 // ----------------------------------------------------------------------------
2173 // implementation
2174 // ----------------------------------------------------------------------------
2175
2176 bool wxTreeCtrl::MSWShouldPreProcessMessage(WXMSG* msg)
2177 {
2178 if ( msg->message == WM_KEYDOWN )
2179 {
2180 // Only eat VK_RETURN if not being used by the application in
2181 // conjunction with modifiers
2182 if ( (msg->wParam == VK_RETURN) && !wxIsAnyModifierDown() )
2183 {
2184 // we need VK_RETURN to generate wxEVT_COMMAND_TREE_ITEM_ACTIVATED
2185 return false;
2186 }
2187 }
2188
2189 return wxTreeCtrlBase::MSWShouldPreProcessMessage(msg);
2190 }
2191
2192 bool wxTreeCtrl::MSWCommand(WXUINT cmd, WXWORD id_)
2193 {
2194 const int id = (signed short)id_;
2195
2196 if ( cmd == EN_UPDATE )
2197 {
2198 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, id);
2199 event.SetEventObject( this );
2200 ProcessCommand(event);
2201 }
2202 else if ( cmd == EN_KILLFOCUS )
2203 {
2204 wxCommandEvent event(wxEVT_KILL_FOCUS, id);
2205 event.SetEventObject( this );
2206 ProcessCommand(event);
2207 }
2208 else
2209 {
2210 // nothing done
2211 return false;
2212 }
2213
2214 // command processed
2215 return true;
2216 }
2217
2218 bool wxTreeCtrl::MSWIsOnItem(unsigned flags) const
2219 {
2220 unsigned mask = TVHT_ONITEM;
2221 if ( HasFlag(wxTR_FULL_ROW_HIGHLIGHT) )
2222 mask |= TVHT_ONITEMINDENT | TVHT_ONITEMRIGHT;
2223
2224 return (flags & mask) != 0;
2225 }
2226
2227 bool wxTreeCtrl::MSWHandleSelectionKey(unsigned vkey)
2228 {
2229 const bool bCtrl = wxIsCtrlDown();
2230 const bool bShift = wxIsShiftDown();
2231 const HTREEITEM htSel = (HTREEITEM)TreeView_GetSelection(GetHwnd());
2232
2233 switch ( vkey )
2234 {
2235 case VK_RETURN:
2236 case VK_SPACE:
2237 if ( !htSel )
2238 break;
2239
2240 if ( vkey != VK_RETURN && bCtrl )
2241 {
2242 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING,
2243 this, htSel);
2244 changingEvent.m_itemOld = htSel;
2245
2246 if ( IsTreeEventAllowed(changingEvent) )
2247 {
2248 DoToggleItemSelection(wxTreeItemId(htSel));
2249
2250 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
2251 this, htSel);
2252 changedEvent.m_itemOld = htSel;
2253 (void)HandleTreeEvent(changedEvent);
2254 }
2255 }
2256 else
2257 {
2258 wxArrayTreeItemIds selections;
2259 size_t count = GetSelections(selections);
2260
2261 if ( count != 1 || HITEM(selections[0]) != htSel )
2262 {
2263 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING,
2264 this, htSel);
2265 changingEvent.m_itemOld = htSel;
2266
2267 if ( IsTreeEventAllowed(changingEvent) )
2268 {
2269 DoUnselectAll();
2270 DoSelectItem(wxTreeItemId(htSel));
2271
2272 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
2273 this, htSel);
2274 changedEvent.m_itemOld = htSel;
2275 (void)HandleTreeEvent(changedEvent);
2276 }
2277 }
2278 }
2279 break;
2280
2281 case VK_UP:
2282 case VK_DOWN:
2283 if ( !bCtrl && !bShift )
2284 {
2285 wxArrayTreeItemIds selections;
2286 wxTreeItemId next;
2287
2288 if ( htSel )
2289 {
2290 next = vkey == VK_UP
2291 ? TreeView_GetPrevVisible(GetHwnd(), htSel)
2292 : TreeView_GetNextVisible(GetHwnd(), htSel);
2293 }
2294 else
2295 {
2296 next = GetRootItem();
2297
2298 if ( IsHiddenRoot(next) )
2299 next = TreeView_GetChild(GetHwnd(), HITEM(next));
2300 }
2301
2302 if ( !next.IsOk() )
2303 {
2304 break;
2305 }
2306
2307 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING,
2308 this, next);
2309 changingEvent.m_itemOld = htSel;
2310
2311 if ( IsTreeEventAllowed(changingEvent) )
2312 {
2313 DoUnselectAll();
2314 DoSelectItem(next);
2315 SetFocusedItem(next);
2316
2317 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
2318 this, next);
2319 changedEvent.m_itemOld = htSel;
2320 (void)HandleTreeEvent(changedEvent);
2321 }
2322 }
2323 else if ( htSel )
2324 {
2325 wxTreeItemId next = vkey == VK_UP
2326 ? TreeView_GetPrevVisible(GetHwnd(), htSel)
2327 : TreeView_GetNextVisible(GetHwnd(), htSel);
2328
2329 if ( !next.IsOk() )
2330 {
2331 break;
2332 }
2333
2334 if ( !m_htSelStart )
2335 {
2336 m_htSelStart = htSel;
2337 }
2338
2339 if ( bShift && SelectRange(GetHwnd(), HITEM(m_htSelStart), HITEM(next),
2340 SR_UNSELECT_OTHERS | SR_SIMULATE) )
2341 {
2342 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING, this, next);
2343 changingEvent.m_itemOld = htSel;
2344
2345 if ( IsTreeEventAllowed(changingEvent) )
2346 {
2347 SelectRange(GetHwnd(), HITEM(m_htSelStart), HITEM(next),
2348 SR_UNSELECT_OTHERS);
2349
2350 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED, this, next);
2351 changedEvent.m_itemOld = htSel;
2352 (void)HandleTreeEvent(changedEvent);
2353 }
2354 }
2355
2356 SetFocusedItem(next);
2357 }
2358 break;
2359
2360 case VK_LEFT:
2361 if ( HasChildren(htSel) && IsExpanded(htSel) )
2362 {
2363 Collapse(htSel);
2364 }
2365 else
2366 {
2367 wxTreeItemId next = GetItemParent(htSel);
2368
2369 if ( next.IsOk() && !IsHiddenRoot(next) )
2370 {
2371 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING,
2372 this, next);
2373 changingEvent.m_itemOld = htSel;
2374
2375 if ( IsTreeEventAllowed(changingEvent) )
2376 {
2377 DoUnselectAll();
2378 DoSelectItem(next);
2379 SetFocusedItem(next);
2380
2381 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
2382 this, next);
2383 changedEvent.m_itemOld = htSel;
2384 (void)HandleTreeEvent(changedEvent);
2385 }
2386 }
2387 }
2388 break;
2389
2390 case VK_RIGHT:
2391 if ( !IsVisible(htSel) )
2392 {
2393 EnsureVisible(htSel);
2394 }
2395
2396 if ( !HasChildren(htSel) )
2397 break;
2398
2399 if ( !IsExpanded(htSel) )
2400 {
2401 Expand(htSel);
2402 }
2403 else
2404 {
2405 wxTreeItemId next = TreeView_GetChild(GetHwnd(), htSel);
2406
2407 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING, this, next);
2408 changingEvent.m_itemOld = htSel;
2409
2410 if ( IsTreeEventAllowed(changingEvent) )
2411 {
2412 DoUnselectAll();
2413 DoSelectItem(next);
2414 SetFocusedItem(next);
2415
2416 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED, this, next);
2417 changedEvent.m_itemOld = htSel;
2418 (void)HandleTreeEvent(changedEvent);
2419 }
2420 }
2421 break;
2422
2423 case VK_HOME:
2424 case VK_END:
2425 {
2426 wxTreeItemId next = GetRootItem();
2427
2428 if ( IsHiddenRoot(next) )
2429 {
2430 next = TreeView_GetChild(GetHwnd(), HITEM(next));
2431 }
2432
2433 if ( !next.IsOk() )
2434 break;
2435
2436 if ( vkey == VK_END )
2437 {
2438 for ( ;; )
2439 {
2440 wxTreeItemId nextTemp = TreeView_GetNextVisible(
2441 GetHwnd(), HITEM(next));
2442
2443 if ( !nextTemp.IsOk() )
2444 break;
2445
2446 next = nextTemp;
2447 }
2448 }
2449
2450 if ( htSel == HITEM(next) )
2451 break;
2452
2453 if ( bShift )
2454 {
2455 if ( !m_htSelStart )
2456 {
2457 m_htSelStart = htSel;
2458 }
2459
2460 if ( SelectRange(GetHwnd(),
2461 HITEM(m_htSelStart), HITEM(next),
2462 SR_UNSELECT_OTHERS | SR_SIMULATE) )
2463 {
2464 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING,
2465 this, next);
2466 changingEvent.m_itemOld = htSel;
2467
2468 if ( IsTreeEventAllowed(changingEvent) )
2469 {
2470 SelectRange(GetHwnd(),
2471 HITEM(m_htSelStart), HITEM(next),
2472 SR_UNSELECT_OTHERS);
2473 SetFocusedItem(next);
2474
2475 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
2476 this, next);
2477 changedEvent.m_itemOld = htSel;
2478 (void)HandleTreeEvent(changedEvent);
2479 }
2480 }
2481 }
2482 else // no Shift
2483 {
2484 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING,
2485 this, next);
2486 changingEvent.m_itemOld = htSel;
2487
2488 if ( IsTreeEventAllowed(changingEvent) )
2489 {
2490 DoUnselectAll();
2491 DoSelectItem(next);
2492 SetFocusedItem(next);
2493
2494 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
2495 this, next);
2496 changedEvent.m_itemOld = htSel;
2497 (void)HandleTreeEvent(changedEvent);
2498 }
2499 }
2500 }
2501 break;
2502
2503 case VK_PRIOR:
2504 case VK_NEXT:
2505 if ( bCtrl )
2506 {
2507 wxTreeItemId firstVisible = GetFirstVisibleItem();
2508 size_t visibleCount = TreeView_GetVisibleCount(GetHwnd());
2509 wxTreeItemId nextAdjacent = (vkey == VK_PRIOR) ?
2510 TreeView_GetPrevVisible(GetHwnd(), HITEM(firstVisible)) :
2511 TreeView_GetNextVisible(GetHwnd(), HITEM(firstVisible));
2512
2513 if ( !nextAdjacent )
2514 {
2515 break;
2516 }
2517
2518 wxTreeItemId nextStart = firstVisible;
2519
2520 for ( size_t n = 1; n < visibleCount; n++ )
2521 {
2522 wxTreeItemId nextTemp = (vkey == VK_PRIOR) ?
2523 TreeView_GetPrevVisible(GetHwnd(), HITEM(nextStart)) :
2524 TreeView_GetNextVisible(GetHwnd(), HITEM(nextStart));
2525
2526 if ( nextTemp.IsOk() )
2527 {
2528 nextStart = nextTemp;
2529 }
2530 else
2531 {
2532 break;
2533 }
2534 }
2535
2536 EnsureVisible(nextStart);
2537
2538 if ( vkey == VK_NEXT )
2539 {
2540 wxTreeItemId nextEnd = nextStart;
2541
2542 for ( size_t n = 1; n < visibleCount; n++ )
2543 {
2544 wxTreeItemId nextTemp =
2545 TreeView_GetNextVisible(GetHwnd(), HITEM(nextEnd));
2546
2547 if ( nextTemp.IsOk() )
2548 {
2549 nextEnd = nextTemp;
2550 }
2551 else
2552 {
2553 break;
2554 }
2555 }
2556
2557 EnsureVisible(nextEnd);
2558 }
2559 }
2560 else // no Ctrl
2561 {
2562 size_t visibleCount = TreeView_GetVisibleCount(GetHwnd());
2563 wxTreeItemId nextAdjacent = (vkey == VK_PRIOR) ?
2564 TreeView_GetPrevVisible(GetHwnd(), htSel) :
2565 TreeView_GetNextVisible(GetHwnd(), htSel);
2566
2567 if ( !nextAdjacent )
2568 {
2569 break;
2570 }
2571
2572 wxTreeItemId next(htSel);
2573
2574 for ( size_t n = 1; n < visibleCount; n++ )
2575 {
2576 wxTreeItemId nextTemp = vkey == VK_PRIOR ?
2577 TreeView_GetPrevVisible(GetHwnd(), HITEM(next)) :
2578 TreeView_GetNextVisible(GetHwnd(), HITEM(next));
2579
2580 if ( !nextTemp.IsOk() )
2581 break;
2582
2583 next = nextTemp;
2584 }
2585
2586 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING,
2587 this, next);
2588 changingEvent.m_itemOld = htSel;
2589
2590 if ( IsTreeEventAllowed(changingEvent) )
2591 {
2592 DoUnselectAll();
2593 m_htSelStart.Unset();
2594 DoSelectItem(next);
2595 SetFocusedItem(next);
2596
2597 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
2598 this, next);
2599 changedEvent.m_itemOld = htSel;
2600 (void)HandleTreeEvent(changedEvent);
2601 }
2602 }
2603 break;
2604
2605 default:
2606 return false;
2607 }
2608
2609 return true;
2610 }
2611
2612 bool wxTreeCtrl::MSWHandleTreeKeyDownEvent(WXWPARAM wParam, WXLPARAM lParam)
2613 {
2614 wxTreeEvent keyEvent(wxEVT_COMMAND_TREE_KEY_DOWN, this);
2615
2616 int keyCode = wxCharCodeMSWToWX(wParam);
2617
2618 if ( !keyCode )
2619 {
2620 // wxCharCodeMSWToWX() returns 0 to indicate that this is a
2621 // simple ASCII key
2622 keyCode = wParam;
2623 }
2624
2625 keyEvent.m_evtKey = CreateKeyEvent(wxEVT_KEY_DOWN, keyCode,
2626 lParam, wParam);
2627
2628 bool processed = HandleTreeEvent(keyEvent);
2629
2630 // generate a separate event for Space/Return
2631 if ( !wxIsCtrlDown() && !wxIsShiftDown() && !wxIsAltDown() &&
2632 ((wParam == VK_SPACE) || (wParam == VK_RETURN)) )
2633 {
2634 const HTREEITEM htSel = (HTREEITEM)TreeView_GetSelection(GetHwnd());
2635 if ( htSel )
2636 {
2637 wxTreeEvent activatedEvent(wxEVT_COMMAND_TREE_ITEM_ACTIVATED,
2638 this, htSel);
2639 (void)HandleTreeEvent(activatedEvent);
2640 }
2641 }
2642
2643 return processed;
2644 }
2645
2646 // we hook into WndProc to process WM_MOUSEMOVE/WM_BUTTONUP messages - as we
2647 // only do it during dragging, minimize wxWin overhead (this is important for
2648 // WM_MOUSEMOVE as they're a lot of them) by catching Windows messages directly
2649 // instead of passing by wxWin events
2650 WXLRESULT
2651 wxTreeCtrl::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
2652 {
2653 bool processed = false;
2654 WXLRESULT rc = 0;
2655 bool isMultiple = HasFlag(wxTR_MULTIPLE);
2656
2657 if ( nMsg == WM_CONTEXTMENU )
2658 {
2659 int x = GET_X_LPARAM(lParam),
2660 y = GET_Y_LPARAM(lParam);
2661
2662 // the item for which the menu should be shown
2663 wxTreeItemId item;
2664
2665 // the position where the menu should be shown in client coordinates
2666 // (so that it can be passed directly to PopupMenu())
2667 wxPoint pt;
2668
2669 if ( x == -1 || y == -1 )
2670 {
2671 // this means that the event was generated from keyboard (e.g. with
2672 // Shift-F10 or special Windows menu key)
2673 //
2674 // use the Explorer standard of putting the menu at the left edge
2675 // of the text, in the vertical middle of the text
2676 item = wxTreeItemId(TreeView_GetSelection(GetHwnd()));
2677 if ( item.IsOk() )
2678 {
2679 // Use the bounding rectangle of only the text part
2680 wxRect rect;
2681 GetBoundingRect(item, rect, true);
2682 pt = wxPoint(rect.GetX(), rect.GetY() + rect.GetHeight() / 2);
2683 }
2684 }
2685 else // event from mouse, use mouse position
2686 {
2687 pt = ScreenToClient(wxPoint(x, y));
2688
2689 TV_HITTESTINFO tvhti;
2690 tvhti.pt.x = pt.x;
2691 tvhti.pt.y = pt.y;
2692
2693 if ( TreeView_HitTest(GetHwnd(), &tvhti) )
2694 item = wxTreeItemId(tvhti.hItem);
2695 }
2696
2697 // create the event
2698 wxTreeEvent event(wxEVT_COMMAND_TREE_ITEM_MENU, this, item);
2699
2700 event.m_pointDrag = pt;
2701
2702 if ( HandleTreeEvent(event) )
2703 processed = true;
2704 //else: continue with generating wxEVT_CONTEXT_MENU in base class code
2705 }
2706 else if ( (nMsg >= WM_MOUSEFIRST) && (nMsg <= WM_MOUSELAST) )
2707 {
2708 // we only process mouse messages here and these parameters have the
2709 // same meaning for all of them
2710 int x = GET_X_LPARAM(lParam),
2711 y = GET_Y_LPARAM(lParam);
2712
2713 TV_HITTESTINFO tvht;
2714 tvht.pt.x = x;
2715 tvht.pt.y = y;
2716
2717 HTREEITEM htOldItem = TreeView_GetSelection(GetHwnd());
2718 HTREEITEM htItem = TreeView_HitTest(GetHwnd(), &tvht);
2719
2720 switch ( nMsg )
2721 {
2722 case WM_LBUTTONDOWN:
2723 if ( !isMultiple )
2724 break;
2725
2726 m_htClickedItem.Unset();
2727
2728 if ( !MSWIsOnItem(tvht.flags) )
2729 {
2730 if ( tvht.flags & TVHT_ONITEMBUTTON )
2731 {
2732 // either it's going to be handled by user code or
2733 // we're going to use it ourselves to toggle the
2734 // branch, in either case don't pass it to the base
2735 // class which would generate another mouse click event
2736 // for it even though it's already handled here
2737 processed = true;
2738 SetFocus();
2739
2740 if ( !HandleMouseEvent(nMsg, x, y, wParam) )
2741 {
2742 if ( !IsExpanded(htItem) )
2743 {
2744 Expand(htItem);
2745 }
2746 else
2747 {
2748 Collapse(htItem);
2749 }
2750 }
2751 }
2752
2753 m_focusLost = false;
2754 break;
2755 }
2756
2757 processed = true;
2758 SetFocus();
2759 m_htClickedItem = (WXHTREEITEM) htItem;
2760 m_ptClick = wxPoint(x, y);
2761
2762 if ( wParam & MK_CONTROL )
2763 {
2764 if ( HandleMouseEvent(nMsg, x, y, wParam) )
2765 {
2766 m_htClickedItem.Unset();
2767 break;
2768 }
2769
2770 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING,
2771 this, htItem);
2772 changingEvent.m_itemOld = htOldItem;
2773
2774 if ( IsTreeEventAllowed(changingEvent) )
2775 {
2776 // toggle selected state
2777 DoToggleItemSelection(wxTreeItemId(htItem));
2778
2779 SetFocusedItem(wxTreeItemId(htItem));
2780
2781 // reset on any click without Shift
2782 m_htSelStart.Unset();
2783
2784 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
2785 this, htItem);
2786 changedEvent.m_itemOld = htOldItem;
2787 (void)HandleTreeEvent(changedEvent);
2788 }
2789 }
2790 else if ( wParam & MK_SHIFT )
2791 {
2792 if ( HandleMouseEvent(nMsg, x, y, wParam) )
2793 {
2794 m_htClickedItem.Unset();
2795 break;
2796 }
2797
2798 int srFlags = 0;
2799 bool willChange = true;
2800
2801 if ( !(wParam & MK_CONTROL) )
2802 {
2803 srFlags |= SR_UNSELECT_OTHERS;
2804 }
2805
2806 if ( !m_htSelStart )
2807 {
2808 // take the focused item
2809 m_htSelStart = htOldItem;
2810 }
2811 else
2812 {
2813 willChange = SelectRange(GetHwnd(), HITEM(m_htSelStart),
2814 htItem, srFlags | SR_SIMULATE);
2815 }
2816
2817 if ( willChange )
2818 {
2819 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING,
2820 this, htItem);
2821 changingEvent.m_itemOld = htOldItem;
2822
2823 if ( IsTreeEventAllowed(changingEvent) )
2824 {
2825 // this selects all items between the starting one
2826 // and the current
2827 if ( m_htSelStart )
2828 {
2829 SelectRange(GetHwnd(), HITEM(m_htSelStart),
2830 htItem, srFlags);
2831 }
2832 else
2833 {
2834 DoSelectItem(wxTreeItemId(htItem));
2835 }
2836
2837 SetFocusedItem(wxTreeItemId(htItem));
2838
2839 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
2840 this, htItem);
2841 changedEvent.m_itemOld = htOldItem;
2842 (void)HandleTreeEvent(changedEvent);
2843 }
2844 }
2845 }
2846 else // normal click
2847 {
2848 // avoid doing anything if we click on the only
2849 // currently selected item
2850
2851 wxArrayTreeItemIds selections;
2852 size_t count = GetSelections(selections);
2853
2854 if ( count == 0 ||
2855 count > 1 ||
2856 HITEM(selections[0]) != htItem )
2857 {
2858 if ( HandleMouseEvent(nMsg, x, y, wParam) )
2859 {
2860 m_htClickedItem.Unset();
2861 break;
2862 }
2863
2864 // clear the previously selected items, if the user
2865 // clicked outside of the present selection, otherwise,
2866 // perform the deselection on mouse-up, this allows
2867 // multiple drag and drop to work.
2868 if ( !IsItemSelected(GetHwnd(), htItem))
2869 {
2870 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING,
2871 this, htItem);
2872 changingEvent.m_itemOld = htOldItem;
2873
2874 if ( IsTreeEventAllowed(changingEvent) )
2875 {
2876 DoUnselectAll();
2877 DoSelectItem(wxTreeItemId(htItem));
2878 SetFocusedItem(wxTreeItemId(htItem));
2879
2880 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
2881 this, htItem);
2882 changedEvent.m_itemOld = htOldItem;
2883 (void)HandleTreeEvent(changedEvent);
2884 }
2885 }
2886 else
2887 {
2888 SetFocusedItem(wxTreeItemId(htItem));
2889 m_mouseUpDeselect = true;
2890 }
2891 }
2892 else // click on a single selected item
2893 {
2894 // don't interfere with the default processing in
2895 // WM_MOUSEMOVE handler below as the default window
2896 // proc will start the drag itself if we let have
2897 // WM_LBUTTONDOWN
2898 m_htClickedItem.Unset();
2899
2900 // prevent in-place editing from starting if focus lost
2901 // since previous click
2902 if ( m_focusLost )
2903 {
2904 ClearFocusedItem();
2905 DoSelectItem(wxTreeItemId(htItem));
2906 SetFocusedItem(wxTreeItemId(htItem));
2907 }
2908 else
2909 {
2910 processed = false;
2911 }
2912 }
2913
2914 // reset on any click without Shift
2915 m_htSelStart.Unset();
2916 }
2917
2918 m_focusLost = false;
2919
2920 // we consumed the event so we need to trigger state image
2921 // click if needed
2922 if ( processed )
2923 {
2924 int htFlags = 0;
2925 wxTreeItemId item = HitTest(wxPoint(x, y), htFlags);
2926
2927 if ( htFlags & wxTREE_HITTEST_ONITEMSTATEICON )
2928 {
2929 m_triggerStateImageClick = true;
2930 }
2931 }
2932 break;
2933
2934 case WM_RBUTTONDOWN:
2935 if ( !isMultiple )
2936 break;
2937
2938 processed = true;
2939 SetFocus();
2940
2941 if ( HandleMouseEvent(nMsg, x, y, wParam) || !htItem )
2942 {
2943 break;
2944 }
2945
2946 // default handler removes the highlight from the currently
2947 // focused item when right mouse button is pressed on another
2948 // one but keeps the remaining items highlighted, which is
2949 // confusing, so override this default behaviour
2950 if ( !IsItemSelected(GetHwnd(), htItem) )
2951 {
2952 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING,
2953 this, htItem);
2954 changingEvent.m_itemOld = htOldItem;
2955
2956 if ( IsTreeEventAllowed(changingEvent) )
2957 {
2958 DoUnselectAll();
2959 DoSelectItem(wxTreeItemId(htItem));
2960 SetFocusedItem(wxTreeItemId(htItem));
2961
2962 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
2963 this, htItem);
2964 changedEvent.m_itemOld = htOldItem;
2965 (void)HandleTreeEvent(changedEvent);
2966 }
2967 }
2968
2969 break;
2970
2971 case WM_MOUSEMOVE:
2972 #ifndef __WXWINCE__
2973 if ( m_htClickedItem )
2974 {
2975 int cx = abs(m_ptClick.x - x);
2976 int cy = abs(m_ptClick.y - y);
2977
2978 if ( cx > ::GetSystemMetrics(SM_CXDRAG) ||
2979 cy > ::GetSystemMetrics(SM_CYDRAG) )
2980 {
2981 NM_TREEVIEW tv;
2982 wxZeroMemory(tv);
2983
2984 tv.hdr.hwndFrom = GetHwnd();
2985 tv.hdr.idFrom = ::GetWindowLong(GetHwnd(), GWL_ID);
2986 tv.hdr.code = TVN_BEGINDRAG;
2987
2988 tv.itemNew.hItem = HITEM(m_htClickedItem);
2989
2990
2991 TVITEM tviAux;
2992 wxZeroMemory(tviAux);
2993
2994 tviAux.hItem = HITEM(m_htClickedItem);
2995 tviAux.mask = TVIF_STATE | TVIF_PARAM;
2996 tviAux.stateMask = 0xffffffff;
2997 TreeView_GetItem(GetHwnd(), &tviAux);
2998
2999 tv.itemNew.state = tviAux.state;
3000 tv.itemNew.lParam = tviAux.lParam;
3001
3002 tv.ptDrag.x = x;
3003 tv.ptDrag.y = y;
3004
3005 // do it before SendMessage() call below to avoid
3006 // reentrancies here if there is another WM_MOUSEMOVE
3007 // in the queue already
3008 m_htClickedItem.Unset();
3009
3010 ::SendMessage(GetHwndOf(GetParent()), WM_NOTIFY,
3011 tv.hdr.idFrom, (LPARAM)&tv );
3012
3013 // don't pass it to the default window proc, it would
3014 // start dragging again
3015 processed = true;
3016 }
3017 }
3018 #endif // __WXWINCE__
3019
3020 #if wxUSE_DRAGIMAGE
3021 if ( m_dragImage )
3022 {
3023 m_dragImage->Move(wxPoint(x, y));
3024 if ( htItem )
3025 {
3026 // highlight the item as target (hiding drag image is
3027 // necessary - otherwise the display will be corrupted)
3028 m_dragImage->Hide();
3029 TreeView_SelectDropTarget(GetHwnd(), htItem);
3030 m_dragImage->Show();
3031 }
3032 }
3033 #endif // wxUSE_DRAGIMAGE
3034 break;
3035
3036 case WM_LBUTTONUP:
3037 if ( isMultiple )
3038 {
3039 // deselect other items if needed
3040 if ( htItem )
3041 {
3042 if ( m_mouseUpDeselect )
3043 {
3044 m_mouseUpDeselect = false;
3045
3046 wxTreeEvent changingEvent(wxEVT_COMMAND_TREE_SEL_CHANGING,
3047 this, htItem);
3048 changingEvent.m_itemOld = htOldItem;
3049
3050 if ( IsTreeEventAllowed(changingEvent) )
3051 {
3052 DoUnselectAll();
3053 DoSelectItem(wxTreeItemId(htItem));
3054 SetFocusedItem(wxTreeItemId(htItem));
3055
3056 wxTreeEvent changedEvent(wxEVT_COMMAND_TREE_SEL_CHANGED,
3057 this, htItem);
3058 changedEvent.m_itemOld = htOldItem;
3059 (void)HandleTreeEvent(changedEvent);
3060 }
3061 }
3062 }
3063
3064 m_htClickedItem.Unset();
3065
3066 if ( m_triggerStateImageClick )
3067 {
3068 if ( tvht.flags & TVHT_ONITEMSTATEICON )
3069 {
3070 wxTreeEvent event(wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK,
3071 this, htItem);
3072 (void)HandleTreeEvent(event);
3073
3074 m_triggerStateImageClick = false;
3075 processed = true;
3076 }
3077 }
3078
3079 if ( !m_dragStarted && MSWIsOnItem(tvht.flags) )
3080 {
3081 processed = true;
3082 }
3083 }
3084
3085 // fall through
3086
3087 case WM_RBUTTONUP:
3088 #if wxUSE_DRAGIMAGE
3089 if ( m_dragImage )
3090 {
3091 m_dragImage->EndDrag();
3092 delete m_dragImage;
3093 m_dragImage = NULL;
3094
3095 // generate the drag end event
3096 wxTreeEvent event(wxEVT_COMMAND_TREE_END_DRAG,
3097 this, htItem);
3098 event.m_pointDrag = wxPoint(x, y);
3099 (void)HandleTreeEvent(event);
3100
3101 // if we don't do it, the tree seems to think that 2 items
3102 // are selected simultaneously which is quite weird
3103 TreeView_SelectDropTarget(GetHwnd(), 0);
3104 }
3105 #endif // wxUSE_DRAGIMAGE
3106
3107 if ( isMultiple && nMsg == WM_RBUTTONUP )
3108 {
3109 // send NM_RCLICK
3110 NMHDR nmhdr;
3111 nmhdr.hwndFrom = GetHwnd();
3112 nmhdr.idFrom = ::GetWindowLong(GetHwnd(), GWL_ID);
3113 nmhdr.code = NM_RCLICK;
3114 ::SendMessage(::GetParent(GetHwnd()), WM_NOTIFY,
3115 nmhdr.idFrom, (LPARAM)&nmhdr);
3116 processed = true;
3117 }
3118
3119 m_dragStarted = false;
3120
3121 break;
3122 }
3123 }
3124 else if ( (nMsg == WM_SETFOCUS || nMsg == WM_KILLFOCUS) )
3125 {
3126 if ( isMultiple )
3127 {
3128 // the tree control greys out the selected item when it loses focus
3129 // and paints it as selected again when it regains it, but it won't
3130 // do it for the other items itself - help it
3131 wxArrayTreeItemIds selections;
3132 size_t count = GetSelections(selections);
3133 RECT rect;
3134
3135 for ( size_t n = 0; n < count; n++ )
3136 {
3137 // TreeView_GetItemRect() will return false if item is not
3138 // visible, which may happen perfectly well
3139 if ( TreeView_GetItemRect(GetHwnd(), HITEM(selections[n]),
3140 &rect, TRUE) )
3141 {
3142 ::InvalidateRect(GetHwnd(), &rect, FALSE);
3143 }
3144 }
3145 }
3146
3147 if ( nMsg == WM_KILLFOCUS )
3148 {
3149 m_focusLost = true;
3150 }
3151 }
3152 else if ( (nMsg == WM_KEYDOWN || nMsg == WM_SYSKEYDOWN) && isMultiple )
3153 {
3154 // normally we want to generate wxEVT_KEY_DOWN events from TVN_KEYDOWN
3155 // notification but for the keys which can be used to change selection
3156 // we need to do it from here so as to not apply the default behaviour
3157 // if the events are handled by the user code
3158 switch ( wParam )
3159 {
3160 case VK_RETURN:
3161 case VK_SPACE:
3162 case VK_UP:
3163 case VK_DOWN:
3164 case VK_LEFT:
3165 case VK_RIGHT:
3166 case VK_HOME:
3167 case VK_END:
3168 case VK_PRIOR:
3169 case VK_NEXT:
3170 if ( !MSWHandleTreeKeyDownEvent(wParam, lParam) )
3171 {
3172 // use the key to update the selection if it was left
3173 // unprocessed
3174 MSWHandleSelectionKey(wParam);
3175 }
3176
3177 // pretend that we did process it in any case as we already
3178 // generated an event for it
3179 processed = true;
3180
3181 //default: for all the other keys leave processed as false so that
3182 // the tree control generates a TVN_KEYDOWN for us
3183 }
3184
3185 }
3186 else if ( nMsg == WM_COMMAND )
3187 {
3188 // if we receive a EN_KILLFOCUS command from the in-place edit control
3189 // used for label editing, make sure to end editing
3190 WORD id, cmd;
3191 WXHWND hwnd;
3192 UnpackCommand(wParam, lParam, &id, &hwnd, &cmd);
3193
3194 if ( cmd == EN_KILLFOCUS )
3195 {
3196 if ( m_textCtrl && m_textCtrl->GetHandle() == hwnd )
3197 {
3198 DoEndEditLabel();
3199
3200 processed = true;
3201 }
3202 }
3203 }
3204
3205 if ( !processed )
3206 rc = wxControl::MSWWindowProc(nMsg, wParam, lParam);
3207
3208 return rc;
3209 }
3210
3211 WXLRESULT
3212 wxTreeCtrl::MSWDefWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
3213 {
3214 if ( nMsg == WM_CHAR )
3215 {
3216 // don't let the control process Space and Return keys because it
3217 // doesn't do anything useful with them anyhow but always beeps
3218 // annoyingly when it receives them and there is no way to turn it off
3219 // simply if you just process TREEITEM_ACTIVATED event to which Space
3220 // and Enter presses are mapped in your code
3221 if ( wParam == VK_SPACE || wParam == VK_RETURN )
3222 return 0;
3223 }
3224 #if wxUSE_DRAGIMAGE
3225 else if ( nMsg == WM_KEYDOWN )
3226 {
3227 if ( wParam == VK_ESCAPE )
3228 {
3229 if ( m_dragImage )
3230 {
3231 m_dragImage->EndDrag();
3232 delete m_dragImage;
3233 m_dragImage = NULL;
3234
3235 // if we don't do it, the tree seems to think that 2 items
3236 // are selected simultaneously which is quite weird
3237 TreeView_SelectDropTarget(GetHwnd(), 0);
3238 }
3239 }
3240 }
3241 #endif // wxUSE_DRAGIMAGE
3242
3243 return wxControl::MSWDefWindowProc(nMsg, wParam, lParam);
3244 }
3245
3246 // process WM_NOTIFY Windows message
3247 bool wxTreeCtrl::MSWOnNotify(int idCtrl, WXLPARAM lParam, WXLPARAM *result)
3248 {
3249 wxTreeEvent event(wxEVT_NULL, this);
3250 wxEventType eventType = wxEVT_NULL;
3251 NMHDR *hdr = (NMHDR *)lParam;
3252
3253 switch ( hdr->code )
3254 {
3255 case TVN_BEGINDRAG:
3256 eventType = wxEVT_COMMAND_TREE_BEGIN_DRAG;
3257 // fall through
3258
3259 case TVN_BEGINRDRAG:
3260 {
3261 if ( eventType == wxEVT_NULL )
3262 eventType = wxEVT_COMMAND_TREE_BEGIN_RDRAG;
3263 //else: left drag, already set above
3264
3265 NM_TREEVIEW *tv = (NM_TREEVIEW *)lParam;
3266
3267 event.m_item = tv->itemNew.hItem;
3268 event.m_pointDrag = wxPoint(tv->ptDrag.x, tv->ptDrag.y);
3269
3270 // don't allow dragging by default: the user code must
3271 // explicitly say that it wants to allow it to avoid breaking
3272 // the old apps
3273 event.Veto();
3274 }
3275 break;
3276
3277 case TVN_BEGINLABELEDIT:
3278 {
3279 eventType = wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT;
3280 TV_DISPINFO *info = (TV_DISPINFO *)lParam;
3281
3282 // although the user event handler may still veto it, it is
3283 // important to set it now so that calls to SetItemText() from
3284 // the event handler would change the text controls contents
3285 m_idEdited =
3286 event.m_item = info->item.hItem;
3287 event.m_label = info->item.pszText;
3288 event.m_editCancelled = false;
3289 }
3290 break;
3291
3292 case TVN_DELETEITEM:
3293 {
3294 eventType = wxEVT_COMMAND_TREE_DELETE_ITEM;
3295 NM_TREEVIEW *tv = (NM_TREEVIEW *)lParam;
3296
3297 event.m_item = tv->itemOld.hItem;
3298
3299 if ( m_hasAnyAttr )
3300 {
3301 wxMapTreeAttr::iterator it = m_attrs.find(tv->itemOld.hItem);
3302 if ( it != m_attrs.end() )
3303 {
3304 delete it->second;
3305 m_attrs.erase(it);
3306 }
3307 }
3308 }
3309 break;
3310
3311 case TVN_ENDLABELEDIT:
3312 {
3313 eventType = wxEVT_COMMAND_TREE_END_LABEL_EDIT;
3314 TV_DISPINFO *info = (TV_DISPINFO *)lParam;
3315
3316 event.m_item = info->item.hItem;
3317 event.m_label = info->item.pszText;
3318 event.m_editCancelled = info->item.pszText == NULL;
3319 break;
3320 }
3321
3322 #ifndef __WXWINCE__
3323 // These *must* not be removed or TVN_GETINFOTIP will
3324 // not be processed each time the mouse is moved
3325 // and the tooltip will only ever update once.
3326 case TTN_NEEDTEXTA:
3327 case TTN_NEEDTEXTW:
3328 {
3329 *result = 0;
3330
3331 break;
3332 }
3333
3334 #ifdef TVN_GETINFOTIP
3335 case TVN_GETINFOTIP:
3336 {
3337 eventType = wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP;
3338 NMTVGETINFOTIP *info = (NMTVGETINFOTIP*)lParam;
3339
3340 // Which item are we trying to get a tooltip for?
3341 event.m_item = info->hItem;
3342
3343 break;
3344 }
3345 #endif // TVN_GETINFOTIP
3346 #endif // !__WXWINCE__
3347
3348 case TVN_GETDISPINFO:
3349 eventType = wxEVT_COMMAND_TREE_GET_INFO;
3350 // fall through
3351
3352 case TVN_SETDISPINFO:
3353 {
3354 if ( eventType == wxEVT_NULL )
3355 eventType = wxEVT_COMMAND_TREE_SET_INFO;
3356 //else: get, already set above
3357
3358 TV_DISPINFO *info = (TV_DISPINFO *)lParam;
3359
3360 event.m_item = info->item.hItem;
3361 break;
3362 }
3363
3364 case TVN_ITEMEXPANDING:
3365 case TVN_ITEMEXPANDED:
3366 {
3367 NM_TREEVIEW *tv = (NM_TREEVIEW*)lParam;
3368
3369 int what;
3370 switch ( tv->action )
3371 {
3372 default:
3373 wxLogDebug(wxT("unexpected code %d in TVN_ITEMEXPAND message"), tv->action);
3374 // fall through
3375
3376 case TVE_EXPAND:
3377 what = IDX_EXPAND;
3378 break;
3379
3380 case TVE_COLLAPSE:
3381 what = IDX_COLLAPSE;
3382 break;
3383 }
3384
3385 int how = hdr->code == TVN_ITEMEXPANDING ? IDX_DOING
3386 : IDX_DONE;
3387
3388 eventType = gs_expandEvents[what][how];
3389
3390 event.m_item = tv->itemNew.hItem;
3391 }
3392 break;
3393
3394 case TVN_KEYDOWN:
3395 {
3396 TV_KEYDOWN *info = (TV_KEYDOWN *)lParam;
3397
3398 // fabricate the lParam and wParam parameters sufficiently
3399 // similar to the ones from a "real" WM_KEYDOWN so that
3400 // CreateKeyEvent() works correctly
3401 return MSWHandleTreeKeyDownEvent(
3402 info->wVKey, (wxIsAltDown() ? KF_ALTDOWN : 0) << 16);
3403 }
3404
3405
3406 // Vista's tree control has introduced some problems with our
3407 // multi-selection tree. When TreeView_SelectItem() is called,
3408 // the wrong items are deselected.
3409
3410 // Fortunately, Vista provides a new notification, TVN_ITEMCHANGING
3411 // that can be used to regulate this incorrect behavior. The
3412 // following messages will allow only the unlocked item's selection
3413 // state to change
3414
3415 case TVN_ITEMCHANGINGA:
3416 case TVN_ITEMCHANGINGW:
3417 {
3418 // we only need to handles these in multi-select trees
3419 if ( HasFlag(wxTR_MULTIPLE) )
3420 {
3421 // get info about the item about to be changed
3422 NMTVITEMCHANGE* info = (NMTVITEMCHANGE*)lParam;
3423 if (TreeItemUnlocker::IsLocked(info->hItem))
3424 {
3425 // item's state is locked, don't allow the change
3426 // returning 1 will disallow the change
3427 *result = 1;
3428 return true;
3429 }
3430 }
3431
3432 // allow the state change
3433 }
3434 return false;
3435
3436 // NB: MSLU is broken and sends TVN_SELCHANGEDA instead of
3437 // TVN_SELCHANGEDW in Unicode mode under Win98. Therefore
3438 // we have to handle both messages:
3439 case TVN_SELCHANGEDA:
3440 case TVN_SELCHANGEDW:
3441 if ( !HasFlag(wxTR_MULTIPLE) || !m_changingSelection )
3442 {
3443 eventType = wxEVT_COMMAND_TREE_SEL_CHANGED;
3444 }
3445 // fall through
3446
3447 case TVN_SELCHANGINGA:
3448 case TVN_SELCHANGINGW:
3449 if ( !HasFlag(wxTR_MULTIPLE) || !m_changingSelection )
3450 {
3451 if ( eventType == wxEVT_NULL )
3452 eventType = wxEVT_COMMAND_TREE_SEL_CHANGING;
3453 //else: already set above
3454
3455 if (hdr->code == TVN_SELCHANGINGW ||
3456 hdr->code == TVN_SELCHANGEDW)
3457 {
3458 NM_TREEVIEWW *tv = (NM_TREEVIEWW *)lParam;
3459 event.m_item = tv->itemNew.hItem;
3460 event.m_itemOld = tv->itemOld.hItem;
3461 }
3462 else
3463 {
3464 NM_TREEVIEWA *tv = (NM_TREEVIEWA *)lParam;
3465 event.m_item = tv->itemNew.hItem;
3466 event.m_itemOld = tv->itemOld.hItem;
3467 }
3468 }
3469
3470 // we receive this message from WM_LBUTTONDOWN handler inside
3471 // comctl32.dll and so before the click is passed to
3472 // DefWindowProc() which sets the focus to the window which was
3473 // clicked and this can lead to unexpected event sequences: for
3474 // example, we may get a "selection change" event from the tree
3475 // before getting a "kill focus" event for the text control which
3476 // had the focus previously, thus breaking user code doing input
3477 // validation
3478 //
3479 // to avoid such surprises, we force the generation of focus events
3480 // now, before we generate the selection change ones
3481 SetFocus();
3482 break;
3483
3484 // instead of explicitly checking for _WIN32_IE, check if the
3485 // required symbols are available in the headers
3486 #if defined(CDDS_PREPAINT) && !wxUSE_COMCTL32_SAFELY
3487 case NM_CUSTOMDRAW:
3488 {
3489 LPNMTVCUSTOMDRAW lptvcd = (LPNMTVCUSTOMDRAW)lParam;
3490 NMCUSTOMDRAW& nmcd = lptvcd->nmcd;
3491 switch ( nmcd.dwDrawStage )
3492 {
3493 case CDDS_PREPAINT:
3494 // if we've got any items with non standard attributes,
3495 // notify us before painting each item
3496 *result = m_hasAnyAttr ? CDRF_NOTIFYITEMDRAW
3497 : CDRF_DODEFAULT;
3498
3499 // windows in TreeCtrl use one-based index for item state images,
3500 // 0 indexed image is not being used, we're using zero-based index,
3501 // so we have to add temp image (of zero index) to state image list
3502 // before we draw any item, then after items are drawn we have to
3503 // delete it (in POSTPAINT notify)
3504 if (m_imageListState && m_imageListState->GetImageCount() > 0)
3505 {
3506 typedef BOOL (wxSTDCALL *ImageList_Copy_t)
3507 (HIMAGELIST, int, HIMAGELIST, int, UINT);
3508 static ImageList_Copy_t s_pfnImageList_Copy = NULL;
3509 static bool loaded = false;
3510
3511 if ( !loaded )
3512 {
3513 wxLoadedDLL dllComCtl32(wxT("comctl32.dll"));
3514 if ( dllComCtl32.IsLoaded() )
3515 wxDL_INIT_FUNC(s_pfn, ImageList_Copy, dllComCtl32);
3516 }
3517
3518 if ( !s_pfnImageList_Copy )
3519 {
3520 // this code is broken with ImageList_Copy()
3521 // but I don't care enough about Win95 support
3522 // to write it now -- if anybody does, please
3523 // do it
3524 wxFAIL_MSG("TODO: implement this for Win95");
3525 break;
3526 }
3527
3528 const HIMAGELIST
3529 hImageList = GetHimagelistOf(m_imageListState);
3530
3531 // add temporary image
3532 int width, height;
3533 m_imageListState->GetSize(0, width, height);
3534
3535 HBITMAP hbmpTemp = ::CreateBitmap(width, height, 1, 1, NULL);
3536 int index = ::ImageList_Add(hImageList, hbmpTemp, hbmpTemp);
3537 ::DeleteObject(hbmpTemp);
3538
3539 if ( index != -1 )
3540 {
3541 // move images to right
3542 for ( int i = index; i > 0; i-- )
3543 {
3544 (*s_pfnImageList_Copy)(hImageList, i,
3545 hImageList, i-1,
3546 ILCF_MOVE);
3547 }
3548
3549 // we must remove the image in POSTPAINT notify
3550 *result |= CDRF_NOTIFYPOSTPAINT;
3551 }
3552 }
3553 break;
3554
3555 case CDDS_POSTPAINT:
3556 // we are deleting temp image of 0 index, which was
3557 // added before items were drawn (in PREPAINT notify)
3558 if (m_imageListState && m_imageListState->GetImageCount() > 0)
3559 m_imageListState->Remove(0);
3560 break;
3561
3562 case CDDS_ITEMPREPAINT:
3563 {
3564 wxMapTreeAttr::iterator
3565 it = m_attrs.find((void *)nmcd.dwItemSpec);
3566
3567 if ( it == m_attrs.end() )
3568 {
3569 // nothing to do for this item
3570 *result = CDRF_DODEFAULT;
3571 break;
3572 }
3573
3574 wxTreeItemAttr * const attr = it->second;
3575
3576 wxTreeViewItem tvItem((void *)nmcd.dwItemSpec,
3577 TVIF_STATE, TVIS_DROPHILITED);
3578 DoGetItem(&tvItem);
3579 const UINT tvItemState = tvItem.state;
3580
3581 // selection colours should override ours,
3582 // otherwise it is too confusing to the user
3583 if ( !(nmcd.uItemState & CDIS_SELECTED) &&
3584 !(tvItemState & TVIS_DROPHILITED) )
3585 {
3586 wxColour colBack;
3587 if ( attr->HasBackgroundColour() )
3588 {
3589 colBack = attr->GetBackgroundColour();
3590 lptvcd->clrTextBk = wxColourToRGB(colBack);
3591 }
3592 }
3593
3594 // but we still want to keep the special foreground
3595 // colour when we don't have focus (we can't keep
3596 // it when we do, it would usually be unreadable on
3597 // the almost inverted bg colour...)
3598 if ( ( !(nmcd.uItemState & CDIS_SELECTED) ||
3599 FindFocus() != this ) &&
3600 !(tvItemState & TVIS_DROPHILITED) )
3601 {
3602 wxColour colText;
3603 if ( attr->HasTextColour() )
3604 {
3605 colText = attr->GetTextColour();
3606 lptvcd->clrText = wxColourToRGB(colText);
3607 }
3608 }
3609
3610 if ( attr->HasFont() )
3611 {
3612 HFONT hFont = GetHfontOf(attr->GetFont());
3613
3614 ::SelectObject(nmcd.hdc, hFont);
3615
3616 *result = CDRF_NEWFONT;
3617 }
3618 else // no specific font
3619 {
3620 *result = CDRF_DODEFAULT;
3621 }
3622 }
3623 break;
3624
3625 default:
3626 *result = CDRF_DODEFAULT;
3627 }
3628 }
3629
3630 // we always process it
3631 return true;
3632 #endif // have owner drawn support in headers
3633
3634 case NM_CLICK:
3635 {
3636 DWORD pos = GetMessagePos();
3637 POINT point;
3638 point.x = LOWORD(pos);
3639 point.y = HIWORD(pos);
3640 ::MapWindowPoints(HWND_DESKTOP, GetHwnd(), &point, 1);
3641 int htFlags = 0;
3642 wxTreeItemId item = HitTest(wxPoint(point.x, point.y), htFlags);
3643
3644 if ( htFlags & wxTREE_HITTEST_ONITEMSTATEICON )
3645 {
3646 event.m_item = item;
3647 eventType = wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK;
3648 }
3649
3650 break;
3651 }
3652
3653 case NM_DBLCLK:
3654 case NM_RCLICK:
3655 {
3656 TV_HITTESTINFO tvhti;
3657 ::GetCursorPos(&tvhti.pt);
3658 ::ScreenToClient(GetHwnd(), &tvhti.pt);
3659 if ( TreeView_HitTest(GetHwnd(), &tvhti) )
3660 {
3661 if ( MSWIsOnItem(tvhti.flags) )
3662 {
3663 event.m_item = tvhti.hItem;
3664 eventType = (int)hdr->code == NM_DBLCLK
3665 ? wxEVT_COMMAND_TREE_ITEM_ACTIVATED
3666 : wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK;
3667
3668 event.m_pointDrag.x = tvhti.pt.x;
3669 event.m_pointDrag.y = tvhti.pt.y;
3670 }
3671
3672 break;
3673 }
3674 }
3675 // fall through
3676
3677 default:
3678 return wxControl::MSWOnNotify(idCtrl, lParam, result);
3679 }
3680
3681 event.SetEventType(eventType);
3682
3683 bool processed = HandleTreeEvent(event);
3684
3685 // post processing
3686 switch ( hdr->code )
3687 {
3688 case NM_DBLCLK:
3689 // we translate NM_DBLCLK into ACTIVATED event and if the user
3690 // handled the activation of the item we shouldn't proceed with
3691 // also using the same double click for toggling the item expanded
3692 // state -- but OTOH do let the user to expand/collapse the item by
3693 // double clicking on it if the activation is not handled specially
3694 *result = processed;
3695 break;
3696
3697 case NM_RCLICK:
3698 // prevent tree control from sending WM_CONTEXTMENU to our parent
3699 // (which it does if NM_RCLICK is not handled) because we want to
3700 // send it to the control itself
3701 *result =
3702 processed = true;
3703
3704 ::SendMessage(GetHwnd(), WM_CONTEXTMENU,
3705 (WPARAM)GetHwnd(), ::GetMessagePos());
3706 break;
3707
3708 case TVN_BEGINDRAG:
3709 case TVN_BEGINRDRAG:
3710 #if wxUSE_DRAGIMAGE
3711 if ( event.IsAllowed() )
3712 {
3713 // normally this is impossible because the m_dragImage is
3714 // deleted once the drag operation is over
3715 wxASSERT_MSG( !m_dragImage, wxT("starting to drag once again?") );
3716
3717 m_dragImage = new wxDragImage(*this, event.m_item);
3718 m_dragImage->BeginDrag(wxPoint(0,0), this);
3719 m_dragImage->Show();
3720
3721 m_dragStarted = true;
3722 }
3723 #endif // wxUSE_DRAGIMAGE
3724 break;
3725
3726 case TVN_DELETEITEM:
3727 {
3728 // NB: we might process this message using wxWidgets event
3729 // tables, but due to overhead of wxWin event system we
3730 // prefer to do it here ourself (otherwise deleting a tree
3731 // with many items is just too slow)
3732 NM_TREEVIEW *tv = (NM_TREEVIEW *)lParam;
3733
3734 wxTreeItemParam *param =
3735 (wxTreeItemParam *)tv->itemOld.lParam;
3736 delete param;
3737
3738 processed = true; // Make sure we don't get called twice
3739 }
3740 break;
3741
3742 case TVN_BEGINLABELEDIT:
3743 // return true to cancel label editing
3744 *result = !event.IsAllowed();
3745
3746 // set ES_WANTRETURN ( like we do in BeginLabelEdit )
3747 if ( event.IsAllowed() )
3748 {
3749 HWND hText = TreeView_GetEditControl(GetHwnd());
3750 if ( hText )
3751 {
3752 // MBN: if m_textCtrl already has an HWND, it is a stale
3753 // pointer from a previous edit (because the user
3754 // didn't modify the label before dismissing the control,
3755 // and TVN_ENDLABELEDIT was not sent), so delete it
3756 if ( m_textCtrl && m_textCtrl->GetHWND() )
3757 DeleteTextCtrl();
3758 if ( !m_textCtrl )
3759 m_textCtrl = new wxTextCtrl();
3760 m_textCtrl->SetParent(this);
3761 m_textCtrl->SetHWND((WXHWND)hText);
3762 m_textCtrl->SubclassWin((WXHWND)hText);
3763
3764 // set wxTE_PROCESS_ENTER style for the text control to
3765 // force it to process the Enter presses itself, otherwise
3766 // they could be stolen from it by the dialog
3767 // navigation code
3768 m_textCtrl->SetWindowStyle(m_textCtrl->GetWindowStyle()
3769 | wxTE_PROCESS_ENTER);
3770 }
3771 }
3772 else // we had set m_idEdited before
3773 {
3774 m_idEdited.Unset();
3775 }
3776 break;
3777
3778 case TVN_ENDLABELEDIT:
3779 // return true to set the label to the new string: note that we
3780 // also must pretend that we did process the message or it is going
3781 // to be passed to DefWindowProc() which will happily return false
3782 // cancelling the label change
3783 *result = event.IsAllowed();
3784 processed = true;
3785
3786 // ensure that we don't have the text ctrl which is going to be
3787 // deleted any more
3788 DeleteTextCtrl();
3789 break;
3790
3791 #ifndef __WXWINCE__
3792 #ifdef TVN_GETINFOTIP
3793 case TVN_GETINFOTIP:
3794 {
3795 // If the user permitted a tooltip change, change it
3796 if (event.IsAllowed())
3797 {
3798 SetToolTip(event.m_label);
3799 }
3800 }
3801 break;
3802 #endif
3803 #endif
3804
3805 case TVN_SELCHANGING:
3806 case TVN_ITEMEXPANDING:
3807 // return true to prevent the action from happening
3808 *result = !event.IsAllowed();
3809 break;
3810
3811 case TVN_ITEMEXPANDED:
3812 {
3813 NM_TREEVIEW *tv = (NM_TREEVIEW *)lParam;
3814 const wxTreeItemId id(tv->itemNew.hItem);
3815
3816 if ( tv->action == TVE_COLLAPSE )
3817 {
3818 if ( wxApp::GetComCtl32Version() >= 600 )
3819 {
3820 // for some reason the item selection rectangle depends
3821 // on whether it is expanded or collapsed (at least
3822 // with comctl32.dll v6): it is wider (by 3 pixels) in
3823 // the expanded state, so when the item collapses and
3824 // then is deselected the rightmost 3 pixels of the
3825 // previously drawn selection are left on the screen
3826 //
3827 // it's not clear if it's a bug in comctl32.dll or in
3828 // our code (because it does not happen in Explorer but
3829 // OTOH we don't do anything which could result in this
3830 // AFAICS) but we do need to work around it to avoid
3831 // ugly artifacts
3832 RefreshItem(id);
3833 }
3834 }
3835 else // expand
3836 {
3837 // the item is also not refreshed properly after expansion when
3838 // it has an image depending on the expanded/collapsed state:
3839 // again, it's not clear if the bug is in comctl32.dll or our
3840 // code...
3841 int image = GetItemImage(id, wxTreeItemIcon_Expanded);
3842 if ( image != -1 )
3843 {
3844 RefreshItem(id);
3845 }
3846 }
3847 }
3848 break;
3849
3850 case TVN_GETDISPINFO:
3851 // NB: so far the user can't set the image himself anyhow, so do it
3852 // anyway - but this may change later
3853 //if ( /* !processed && */ )
3854 {
3855 wxTreeItemId item = event.m_item;
3856 TV_DISPINFO *info = (TV_DISPINFO *)lParam;
3857
3858 const wxTreeItemParam * const param = GetItemParam(item);
3859 if ( !param )
3860 break;
3861
3862 if ( info->item.mask & TVIF_IMAGE )
3863 {
3864 info->item.iImage =
3865 param->GetImage
3866 (
3867 IsExpanded(item) ? wxTreeItemIcon_Expanded
3868 : wxTreeItemIcon_Normal
3869 );
3870 }
3871 if ( info->item.mask & TVIF_SELECTEDIMAGE )
3872 {
3873 info->item.iSelectedImage =
3874 param->GetImage
3875 (
3876 IsExpanded(item) ? wxTreeItemIcon_SelectedExpanded
3877 : wxTreeItemIcon_Selected
3878 );
3879 }
3880 }
3881 break;
3882
3883 //default:
3884 // for the other messages the return value is ignored and there is
3885 // nothing special to do
3886 }
3887 return processed;
3888 }
3889
3890 // ----------------------------------------------------------------------------
3891 // State control.
3892 // ----------------------------------------------------------------------------
3893
3894 // why do they define INDEXTOSTATEIMAGEMASK but not the inverse?
3895 #define STATEIMAGEMASKTOINDEX(state) (((state) & TVIS_STATEIMAGEMASK) >> 12)
3896
3897 int wxTreeCtrl::DoGetItemState(const wxTreeItemId& item) const
3898 {
3899 wxCHECK_MSG( item.IsOk(), wxTREE_ITEMSTATE_NONE, wxT("invalid tree item") );
3900
3901 // receive the desired information
3902 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_STATEIMAGEMASK);
3903 DoGetItem(&tvItem);
3904
3905 // state images are one-based
3906 return STATEIMAGEMASKTOINDEX(tvItem.state) - 1;
3907 }
3908
3909 void wxTreeCtrl::DoSetItemState(const wxTreeItemId& item, int state)
3910 {
3911 wxCHECK_RET( item.IsOk(), wxT("invalid tree item") );
3912
3913 wxTreeViewItem tvItem(item, TVIF_STATE, TVIS_STATEIMAGEMASK);
3914
3915 // state images are one-based
3916 // 0 if no state image display (wxTREE_ITEMSTATE_NONE = -1)
3917 tvItem.state = INDEXTOSTATEIMAGEMASK(state + 1);
3918
3919 DoSetItem(&tvItem);
3920 }
3921
3922 #endif // wxUSE_TREECTRL