1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/headerctrl.cpp
3 // Purpose: implementation of wxHeaderCtrl for wxMSW
4 // Author: Vadim Zeitlin
7 // Copyright: (c) 2008 Vadim Zeitlin <vadim@wxwidgets.org>
8 // Licence: wxWindows licence
9 ///////////////////////////////////////////////////////////////////////////////
11 // ============================================================================
13 // ============================================================================
15 // ----------------------------------------------------------------------------
17 // ----------------------------------------------------------------------------
19 // for compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
33 #include "wx/headerctrl.h"
35 #ifndef wxHAS_GENERIC_HEADERCTRL
37 #include "wx/imaglist.h"
39 #include "wx/msw/wrapcctl.h"
40 #include "wx/msw/private.h"
42 // from src/msw/listctrl.cpp
43 extern int WXDLLIMPEXP_CORE
wxMSWGetColumnClicked(NMHDR
*nmhdr
, POINT
*ptClick
);
45 // ============================================================================
46 // wxHeaderCtrl implementation
47 // ============================================================================
49 // ----------------------------------------------------------------------------
50 // wxHeaderCtrl construction/destruction
51 // ----------------------------------------------------------------------------
53 void wxHeaderCtrl::Init()
60 bool wxHeaderCtrl::Create(wxWindow
*parent
,
67 // notice that we don't need InitCommonControlsEx(ICC_LISTVIEW_CLASSES)
68 // here as we already call InitCommonControls() in wxApp initialization
69 // code which covers this
71 if ( !CreateControl(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
) )
74 if ( !MSWCreateControl(WC_HEADER
, _T(""), pos
, size
) )
77 // special hack for margins when using comctl32.dll v6 or later: the
78 // default margin is too big and results in label truncation when the
79 // column width is just about right to show it together with the sort
80 // indicator, so reduce it to a smaller value (in principle we could even
81 // use 0 here but this starts to look ugly)
82 if ( wxApp::GetComCtl32Version() >= 600 )
84 Header_SetBitmapMargin(GetHwnd(), ::GetSystemMetrics(SM_CXEDGE
));
90 WXDWORD
wxHeaderCtrl::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
92 WXDWORD msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
94 if ( style
& wxHD_ALLOW_REORDER
)
95 msStyle
|= HDS_DRAGDROP
;
97 // the control looks nicer with these styles and there doesn't seem to be
98 // any reason to not use them so we always do (as for HDS_HORZ it is 0
99 // anyhow but include it for clarity)
100 msStyle
|= HDS_HORZ
| HDS_BUTTONS
| HDS_FLAT
| HDS_FULLDRAG
| HDS_HOTTRACK
;
105 wxHeaderCtrl::~wxHeaderCtrl()
110 // ----------------------------------------------------------------------------
111 // wxHeaderCtrl scrolling
112 // ----------------------------------------------------------------------------
114 void wxHeaderCtrl::DoSetSize(int x
, int y
,
118 wxHeaderCtrlBase::DoSetSize(x
+ m_scrollOffset
, y
, w
- m_scrollOffset
, h
,
122 void wxHeaderCtrl::DoScrollHorz(int dx
)
124 // as the native control doesn't support offsetting its contents, we use a
125 // hack here to make it appear correctly when the parent is scrolled:
126 // instead of scrolling or repainting we simply move the control window
127 // itself: to be precise, offset it by the scroll increment to the left and
128 // increment its width to still extend to the right boundary to compensate
129 // for it (notice that dx is negative when scrolling to the right)
130 m_scrollOffset
+= dx
;
132 wxHeaderCtrlBase::DoSetSize(GetPosition().x
+ dx
, -1,
133 GetSize().x
- dx
, -1,
134 wxSIZE_USE_EXISTING
);
137 // ----------------------------------------------------------------------------
138 // wxHeaderCtrl geometry calculation
139 // ----------------------------------------------------------------------------
141 wxSize
wxHeaderCtrl::DoGetBestSize() const
143 RECT rc
= wxGetClientRect(GetHwndOf(GetParent()));
145 HDLAYOUT layout
= { &rc
, &wpos
};
146 if ( !Header_Layout(GetHwnd(), &layout
) )
148 wxLogLastError(_T("Header_Layout"));
149 return wxControl::DoGetBestSize();
152 return wxSize(wpos
.cx
, wpos
.cy
);
155 // ----------------------------------------------------------------------------
156 // wxHeaderCtrl columns managements
157 // ----------------------------------------------------------------------------
159 unsigned int wxHeaderCtrl::DoGetCount() const
161 // we can't use Header_GetItemCount() here because it doesn't take the
162 // hidden columns into account and we can't find the hidden columns after
163 // the last shown one in MSWFromNativeIdx() without knowing where to stop
164 // so we have to store the columns count internally
168 int wxHeaderCtrl::GetShownColumnsCount() const
170 const int numItems
= Header_GetItemCount(GetHwnd());
172 wxASSERT_MSG( numItems
>= 0 && (unsigned)numItems
<= m_numColumns
,
173 "unexpected number of items in the native control" );
178 void wxHeaderCtrl::DoSetCount(unsigned int count
)
182 // first delete all old columns
183 const unsigned countOld
= GetShownColumnsCount();
184 for ( n
= 0; n
< countOld
; n
++ )
186 if ( !Header_DeleteItem(GetHwnd(), 0) )
188 wxLogLastError(_T("Header_DeleteItem"));
192 // update the column indices order array before changing m_numColumns
193 DoResizeColumnIndices(m_colIndices
, count
);
195 // and add the new ones
196 m_numColumns
= count
;
197 m_isHidden
.resize(m_numColumns
);
198 for ( n
= 0; n
< count
; n
++ )
200 const wxHeaderColumn
& col
= GetColumn(n
);
203 m_isHidden
[n
] = false;
205 DoInsertItem(col
, n
);
207 else // hidden initially
209 m_isHidden
[n
] = true;
214 void wxHeaderCtrl::DoUpdate(unsigned int idx
)
216 // the native control does provide Header_SetItem() but it's inconvenient
217 // to use it because it sends HDN_ITEMCHANGING messages and we'd have to
218 // arrange not to block setting the width from there and the logic would be
219 // more complicated as we'd have to reset the old values as well as setting
220 // the new ones -- so instead just recreate the column
222 const wxHeaderColumn
& col
= GetColumn(idx
);
223 if ( col
.IsHidden() )
225 // column is hidden now
226 if ( !m_isHidden
[idx
] )
228 // but it wasn't hidden before, so remove it
229 Header_DeleteItem(GetHwnd(), MSWToNativeIdx(idx
));
231 m_isHidden
[idx
] = true;
233 //else: nothing to do, updating hidden column doesn't have any effect
235 else // column is shown now
237 if ( m_isHidden
[idx
] )
239 m_isHidden
[idx
] = false;
241 else // and it was shown before as well
243 // we need to remove the old column
244 Header_DeleteItem(GetHwnd(), MSWToNativeIdx(idx
));
247 DoInsertItem(col
, idx
);
251 void wxHeaderCtrl::DoInsertItem(const wxHeaderColumn
& col
, unsigned int idx
)
253 wxASSERT_MSG( !col
.IsHidden(), "should only be called for shown columns" );
257 // notice that we need to store the string we use the pointer to until we
258 // pass it to the control
259 hdi
.mask
|= HDI_TEXT
;
260 wxWxCharBuffer buf
= col
.GetTitle().wx_str();
261 hdi
.pszText
= buf
.data();
262 hdi
.cchTextMax
= wxStrlen(buf
);
264 const wxBitmap bmp
= col
.GetBitmap();
267 hdi
.mask
|= HDI_IMAGE
;
271 const int bmpWidth
= bmp
.GetWidth(),
272 bmpHeight
= bmp
.GetHeight();
276 m_imageList
= new wxImageList(bmpWidth
, bmpHeight
);
277 Header_SetImageList(GetHwnd(), GetHimagelistOf(m_imageList
));
279 else // already have an image list
281 // check that all bitmaps we use have the same size
284 m_imageList
->GetSize(0, imageWidth
, imageHeight
);
286 wxASSERT_MSG( imageWidth
== bmpWidth
&& imageHeight
== bmpHeight
,
287 "all column bitmaps must have the same size" );
290 m_imageList
->Add(bmp
);
291 hdi
.iImage
= m_imageList
->GetImageCount() - 1;
293 else // no bitmap but we still need to update the item
295 hdi
.iImage
= I_IMAGENONE
;
299 if ( col
.GetAlignment() != wxALIGN_NOT
)
301 hdi
.mask
|= HDI_FORMAT
| HDF_LEFT
;
302 switch ( col
.GetAlignment() )
309 case wxALIGN_CENTER_HORIZONTAL
:
310 hdi
.fmt
|= HDF_CENTER
;
314 hdi
.fmt
|= HDF_RIGHT
;
318 wxFAIL_MSG( "invalid column header alignment" );
322 if ( col
.IsSortKey() )
324 hdi
.mask
|= HDI_FORMAT
;
325 hdi
.fmt
|= col
.IsSortOrderAscending() ? HDF_SORTUP
: HDF_SORTDOWN
;
328 if ( col
.GetWidth() != wxCOL_WIDTH_DEFAULT
)
330 hdi
.mask
|= HDI_WIDTH
;
331 hdi
.cxy
= col
.GetWidth();
334 hdi
.mask
|= HDI_ORDER
;
335 hdi
.iOrder
= MSWToNativeOrder(m_colIndices
.Index(idx
));
337 if ( ::SendMessage(GetHwnd(), HDM_INSERTITEM
,
338 MSWToNativeIdx(idx
), (LPARAM
)&hdi
) == -1 )
340 wxLogLastError(_T("Header_InsertItem()"));
344 void wxHeaderCtrl::DoSetColumnsOrder(const wxArrayInt
& order
)
346 wxArrayInt orderShown
;
347 orderShown
.reserve(m_numColumns
);
349 for ( unsigned n
= 0; n
< m_numColumns
; n
++ )
351 const int idx
= order
[n
];
352 if ( GetColumn(idx
).IsShown() )
353 orderShown
.push_back(MSWToNativeIdx(idx
));
356 if ( !Header_SetOrderArray(GetHwnd(), orderShown
.size(), &orderShown
[0]) )
358 wxLogLastError(_T("Header_GetOrderArray"));
361 m_colIndices
= order
;
364 wxArrayInt
wxHeaderCtrl::DoGetColumnsOrder() const
366 // we don't use Header_GetOrderArray() here because it doesn't return
367 // information about the hidden columns, instead we just save the columns
368 // order array in DoSetColumnsOrder() and update it when they're reordered
372 // ----------------------------------------------------------------------------
373 // wxHeaderCtrl indexes and positions translation
374 // ----------------------------------------------------------------------------
376 int wxHeaderCtrl::MSWToNativeIdx(int idx
)
378 // don't check for GetColumn(idx).IsShown() as it could have just became
379 // false and we may be called from DoUpdate() to delete the old column
380 wxASSERT_MSG( !m_isHidden
[idx
],
381 "column must be visible to have an "
382 "index in the native control" );
385 for ( int i
= 0; i
< idx
; i
++ )
387 if ( GetColumn(i
).IsHidden() )
388 item
--; // one less column the native control knows about
391 wxASSERT_MSG( item
>= 0 && item
<= GetShownColumnsCount(), "logic error" );
396 int wxHeaderCtrl::MSWFromNativeIdx(int item
)
398 wxASSERT_MSG( item
>= 0 && item
< GetShownColumnsCount(),
399 "column index out of range" );
401 // reverse the above function
404 for ( unsigned n
= 0; n
< m_numColumns
; n
++ )
409 if ( GetColumn(n
).IsHidden() )
413 wxASSERT_MSG( MSWToNativeIdx(idx
) == item
, "logic error" );
418 int wxHeaderCtrl::MSWToNativeOrder(int pos
)
420 wxASSERT_MSG( pos
>= 0 && static_cast<unsigned>(pos
) < m_numColumns
,
421 "column position out of range" );
424 for ( int n
= 0; n
< pos
; n
++ )
426 if ( GetColumn(m_colIndices
[n
]).IsHidden() )
430 wxASSERT_MSG( order
>= 0 && order
<= GetShownColumnsCount(), "logic error" );
435 int wxHeaderCtrl::MSWFromNativeOrder(int order
)
437 wxASSERT_MSG( order
>= 0 && order
< GetShownColumnsCount(),
438 "native column position out of range" );
440 unsigned pos
= order
;
441 for ( unsigned n
= 0; n
< m_numColumns
; n
++ )
446 if ( GetColumn(m_colIndices
[n
]).IsHidden() )
450 wxASSERT_MSG( MSWToNativeOrder(pos
) == order
, "logic error" );
455 // ----------------------------------------------------------------------------
456 // wxHeaderCtrl events
457 // ----------------------------------------------------------------------------
459 wxEventType
wxHeaderCtrl::GetClickEventType(bool dblclk
, int button
)
465 evtType
= dblclk
? wxEVT_COMMAND_HEADER_DCLICK
466 : wxEVT_COMMAND_HEADER_CLICK
;
470 evtType
= dblclk
? wxEVT_COMMAND_HEADER_RIGHT_DCLICK
471 : wxEVT_COMMAND_HEADER_RIGHT_CLICK
;
475 evtType
= dblclk
? wxEVT_COMMAND_HEADER_MIDDLE_DCLICK
476 : wxEVT_COMMAND_HEADER_MIDDLE_CLICK
;
480 wxFAIL_MSG( wxS("unexpected event type") );
481 evtType
= wxEVT_NULL
;
487 bool wxHeaderCtrl::MSWOnNotify(int idCtrl
, WXLPARAM lParam
, WXLPARAM
*result
)
489 NMHEADER
* const nmhdr
= (NMHEADER
*)lParam
;
491 wxEventType evtType
= wxEVT_NULL
;
495 const UINT code
= nmhdr
->hdr
.code
;
497 // we don't have the index for all events, e.g. not for NM_RELEASEDCAPTURE
498 // so only access for header control events (and yes, the direction of
499 // comparisons with FIRST/LAST is correct even if it seems inverted)
500 int idx
= code
<= HDN_FIRST
&& code
> HDN_LAST
? nmhdr
->iItem
: -1;
503 // we also get bogus HDN_BEGINDRAG with -1 index so don't call
504 // MSWFromNativeIdx() unconditionally for nmhdr->iItem
505 idx
= MSWFromNativeIdx(idx
);
514 case HDN_ITEMDBLCLICK
:
515 evtType
= GetClickEventType(code
== HDN_ITEMDBLCLICK
, nmhdr
->iButton
);
518 // although we should get the notifications about the right clicks
519 // via HDN_ITEM[DBL]CLICK too according to MSDN this simply doesn't
520 // happen in practice on any Windows system up to 2003
525 idx
= wxMSWGetColumnClicked(&nmhdr
->hdr
, &pt
);
526 if ( idx
!= wxNOT_FOUND
)
528 idx
= MSWFromNativeIdx(idx
);
529 evtType
= GetClickEventType(code
== NM_RDBLCLK
, 1);
531 //else: ignore clicks outside any column
535 case HDN_DIVIDERDBLCLICK
:
536 evtType
= wxEVT_COMMAND_HEADER_SEPARATOR_DCLICK
;
540 // column resizing events
541 // ----------------------
543 // see comments in wxListCtrl::MSWOnNotify() for why we catch both
544 // ASCII and Unicode versions of this message
545 case HDN_BEGINTRACKA
:
546 case HDN_BEGINTRACKW
:
547 // non-resizeable columns can't be resized no matter what, don't
548 // even generate any events for them
549 if ( !GetColumn(idx
).IsResizeable() )
555 evtType
= wxEVT_COMMAND_HEADER_BEGIN_RESIZE
;
560 width
= nmhdr
->pitem
->cxy
;
562 if ( evtType
== wxEVT_NULL
)
564 evtType
= wxEVT_COMMAND_HEADER_END_RESIZE
;
566 // don't generate events with invalid width
567 const int minWidth
= GetColumn(idx
).GetMinWidth();
568 if ( width
< minWidth
)
573 case HDN_ITEMCHANGING
:
574 if ( nmhdr
->pitem
&& (nmhdr
->pitem
->mask
& HDI_WIDTH
) )
576 // prevent the column from being shrunk beneath its min width
577 width
= nmhdr
->pitem
->cxy
;
578 if ( width
< GetColumn(idx
).GetMinWidth() )
580 // don't generate any events and prevent the change from
584 else // width is acceptable
586 // generate the resizing event from here as we don't seem
587 // to be getting HDN_TRACK events at all, at least with
589 evtType
= wxEVT_COMMAND_HEADER_RESIZING
;
595 // column reordering events
596 // ------------------------
599 // Windows sometimes sends us events with invalid column indices
600 if ( nmhdr
->iItem
== -1 )
603 // column must have the appropriate flag to be draggable
604 if ( !GetColumn(idx
).IsReorderable() )
610 evtType
= wxEVT_COMMAND_HEADER_BEGIN_REORDER
;
614 wxASSERT_MSG( nmhdr
->pitem
->mask
& HDI_ORDER
, "should have order" );
615 order
= nmhdr
->pitem
->iOrder
;
617 // we also get messages with invalid order when column reordering
618 // is cancelled (e.g. by pressing Esc)
622 order
= MSWFromNativeOrder(order
);
624 evtType
= wxEVT_COMMAND_HEADER_END_REORDER
;
627 case NM_RELEASEDCAPTURE
:
628 evtType
= wxEVT_COMMAND_HEADER_DRAGGING_CANCELLED
;
633 // do generate the corresponding wx event
634 if ( evtType
!= wxEVT_NULL
)
636 wxHeaderCtrlEvent
event(evtType
, GetId());
637 event
.SetEventObject(this);
638 event
.SetColumn(idx
);
639 event
.SetWidth(width
);
641 event
.SetNewOrder(order
);
643 if ( GetEventHandler()->ProcessEvent(event
) )
645 if ( event
.IsAllowed() )
646 return true; // skip default message handling below
648 // we need to veto the default handling of this message, don't
649 // return to execute the code in the "if veto" branch below
652 else // not processed
654 // special post-processing for HDN_ENDDRAG: we need to update the
655 // internal column indices array if this is allowed to go ahead as
656 // the native control is going to reorder its columns now
657 if ( evtType
== wxEVT_COMMAND_HEADER_END_REORDER
)
658 MoveColumnInOrderArray(m_colIndices
, idx
, order
);
664 // all of HDN_BEGIN{DRAG,TRACK}, HDN_TRACK and HDN_ITEMCHANGING
665 // interpret TRUE return value as meaning to stop the control
666 // default handling of the message
672 return wxHeaderCtrlBase::MSWOnNotify(idCtrl
, lParam
, result
);
675 #endif // wxHAS_GENERIC_HEADERCTRL
677 #endif // wxUSE_HEADERCTRL