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