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 #ifndef HDM_SETBITMAPMARGIN
43 #define HDM_SETBITMAPMARGIN 0x1234
46 #ifndef Header_SetBitmapMargin
47 #define Header_SetBitmapMargin(hwnd, margin) \
48 ::SendMessage((hwnd), HDM_SETBITMAPMARGIN, (WPARAM)(margin), 0)
51 // from src/msw/listctrl.cpp
52 extern int WXDLLIMPEXP_CORE
wxMSWGetColumnClicked(NMHDR
*nmhdr
, POINT
*ptClick
);
54 // ============================================================================
55 // wxHeaderCtrl implementation
56 // ============================================================================
58 // ----------------------------------------------------------------------------
59 // wxHeaderCtrl construction/destruction
60 // ----------------------------------------------------------------------------
62 void wxHeaderCtrl::Init()
69 bool wxHeaderCtrl::Create(wxWindow
*parent
,
76 // notice that we don't need InitCommonControlsEx(ICC_LISTVIEW_CLASSES)
77 // here as we already call InitCommonControls() in wxApp initialization
78 // code which covers this
80 if ( !CreateControl(parent
, id
, pos
, size
, style
, wxDefaultValidator
, name
) )
83 if ( !MSWCreateControl(WC_HEADER
, wxT(""), pos
, size
) )
86 // special hack for margins when using comctl32.dll v6 or later: the
87 // default margin is too big and results in label truncation when the
88 // column width is just about right to show it together with the sort
89 // indicator, so reduce it to a smaller value (in principle we could even
90 // use 0 here but this starts to look ugly)
91 if ( wxApp::GetComCtl32Version() >= 600 )
93 Header_SetBitmapMargin(GetHwnd(), ::GetSystemMetrics(SM_CXEDGE
));
99 WXDWORD
wxHeaderCtrl::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
101 WXDWORD msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
103 if ( style
& wxHD_ALLOW_REORDER
)
104 msStyle
|= HDS_DRAGDROP
;
106 // the control looks nicer with these styles and there doesn't seem to be
107 // any reason to not use them so we always do (as for HDS_HORZ it is 0
108 // anyhow but include it for clarity)
109 // NOTE: don't use however HDS_FLAT because it makes the control look
110 // non-native when running WinXP in classic mode
111 msStyle
|= HDS_HORZ
| HDS_BUTTONS
| HDS_FULLDRAG
| HDS_HOTTRACK
;
116 wxHeaderCtrl::~wxHeaderCtrl()
121 // ----------------------------------------------------------------------------
122 // wxHeaderCtrl scrolling
123 // ----------------------------------------------------------------------------
125 void wxHeaderCtrl::DoSetSize(int x
, int y
,
129 wxHeaderCtrlBase::DoSetSize(x
+ m_scrollOffset
, y
, w
- m_scrollOffset
, h
,
133 void wxHeaderCtrl::DoScrollHorz(int dx
)
135 // as the native control doesn't support offsetting its contents, we use a
136 // hack here to make it appear correctly when the parent is scrolled:
137 // instead of scrolling or repainting we simply move the control window
138 // itself: to be precise, offset it by the scroll increment to the left and
139 // increment its width to still extend to the right boundary to compensate
140 // for it (notice that dx is negative when scrolling to the right)
141 m_scrollOffset
+= dx
;
143 wxHeaderCtrlBase::DoSetSize(GetPosition().x
+ dx
, -1,
144 GetSize().x
- dx
, -1,
145 wxSIZE_USE_EXISTING
);
148 // ----------------------------------------------------------------------------
149 // wxHeaderCtrl geometry calculation
150 // ----------------------------------------------------------------------------
152 wxSize
wxHeaderCtrl::DoGetBestSize() const
154 RECT rc
= wxGetClientRect(GetHwndOf(GetParent()));
156 HDLAYOUT layout
= { &rc
, &wpos
};
157 if ( !Header_Layout(GetHwnd(), &layout
) )
159 wxLogLastError(wxT("Header_Layout"));
160 return wxControl::DoGetBestSize();
163 return wxSize(wpos
.cx
, wpos
.cy
);
166 // ----------------------------------------------------------------------------
167 // wxHeaderCtrl columns managements
168 // ----------------------------------------------------------------------------
170 unsigned int wxHeaderCtrl::DoGetCount() const
172 // we can't use Header_GetItemCount() here because it doesn't take the
173 // hidden columns into account and we can't find the hidden columns after
174 // the last shown one in MSWFromNativeIdx() without knowing where to stop
175 // so we have to store the columns count internally
179 int wxHeaderCtrl::GetShownColumnsCount() const
181 const int numItems
= Header_GetItemCount(GetHwnd());
183 wxASSERT_MSG( numItems
>= 0 && (unsigned)numItems
<= m_numColumns
,
184 "unexpected number of items in the native control" );
189 void wxHeaderCtrl::DoSetCount(unsigned int count
)
193 // first delete all old columns
194 const unsigned countOld
= GetShownColumnsCount();
195 for ( n
= 0; n
< countOld
; n
++ )
197 if ( !Header_DeleteItem(GetHwnd(), 0) )
199 wxLogLastError(wxT("Header_DeleteItem"));
203 // update the column indices order array before changing m_numColumns
204 DoResizeColumnIndices(m_colIndices
, count
);
206 // and add the new ones
207 m_numColumns
= count
;
208 m_isHidden
.resize(m_numColumns
);
209 for ( n
= 0; n
< count
; n
++ )
211 const wxHeaderColumn
& col
= GetColumn(n
);
214 m_isHidden
[n
] = false;
216 DoInsertItem(col
, n
);
218 else // hidden initially
220 m_isHidden
[n
] = true;
225 void wxHeaderCtrl::DoUpdate(unsigned int idx
)
227 // the native control does provide Header_SetItem() but it's inconvenient
228 // to use it because it sends HDN_ITEMCHANGING messages and we'd have to
229 // arrange not to block setting the width from there and the logic would be
230 // more complicated as we'd have to reset the old values as well as setting
231 // the new ones -- so instead just recreate the column
233 const wxHeaderColumn
& col
= GetColumn(idx
);
234 if ( col
.IsHidden() )
236 // column is hidden now
237 if ( !m_isHidden
[idx
] )
239 // but it wasn't hidden before, so remove it
240 Header_DeleteItem(GetHwnd(), MSWToNativeIdx(idx
));
242 m_isHidden
[idx
] = true;
244 //else: nothing to do, updating hidden column doesn't have any effect
246 else // column is shown now
248 if ( m_isHidden
[idx
] )
250 m_isHidden
[idx
] = false;
252 else // and it was shown before as well
254 // we need to remove the old column
255 Header_DeleteItem(GetHwnd(), MSWToNativeIdx(idx
));
258 DoInsertItem(col
, idx
);
262 void wxHeaderCtrl::DoInsertItem(const wxHeaderColumn
& col
, unsigned int idx
)
264 wxASSERT_MSG( !col
.IsHidden(), "should only be called for shown columns" );
268 // notice that we need to store the string we use the pointer to until we
269 // pass it to the control
270 hdi
.mask
|= HDI_TEXT
;
271 wxWxCharBuffer buf
= col
.GetTitle().wx_str();
272 hdi
.pszText
= buf
.data();
273 hdi
.cchTextMax
= wxStrlen(buf
);
275 const wxBitmap bmp
= col
.GetBitmap();
278 hdi
.mask
|= HDI_IMAGE
;
282 const int bmpWidth
= bmp
.GetWidth(),
283 bmpHeight
= bmp
.GetHeight();
287 m_imageList
= new wxImageList(bmpWidth
, bmpHeight
);
288 Header_SetImageList(GetHwnd(), GetHimagelistOf(m_imageList
));
290 else // already have an image list
292 // check that all bitmaps we use have the same size
295 m_imageList
->GetSize(0, imageWidth
, imageHeight
);
297 wxASSERT_MSG( imageWidth
== bmpWidth
&& imageHeight
== bmpHeight
,
298 "all column bitmaps must have the same size" );
301 m_imageList
->Add(bmp
);
302 hdi
.iImage
= m_imageList
->GetImageCount() - 1;
304 else // no bitmap but we still need to update the item
306 hdi
.iImage
= I_IMAGENONE
;
310 if ( col
.GetAlignment() != wxALIGN_NOT
)
312 hdi
.mask
|= HDI_FORMAT
| HDF_LEFT
;
313 switch ( col
.GetAlignment() )
320 case wxALIGN_CENTER_HORIZONTAL
:
321 hdi
.fmt
|= HDF_CENTER
;
325 hdi
.fmt
|= HDF_RIGHT
;
329 wxFAIL_MSG( "invalid column header alignment" );
333 if ( col
.IsSortKey() )
335 hdi
.mask
|= HDI_FORMAT
;
336 hdi
.fmt
|= col
.IsSortOrderAscending() ? HDF_SORTUP
: HDF_SORTDOWN
;
339 if ( col
.GetWidth() != wxCOL_WIDTH_DEFAULT
)
341 hdi
.mask
|= HDI_WIDTH
;
342 hdi
.cxy
= col
.GetWidth();
345 hdi
.mask
|= HDI_ORDER
;
346 hdi
.iOrder
= MSWToNativeOrder(m_colIndices
.Index(idx
));
348 if ( ::SendMessage(GetHwnd(), HDM_INSERTITEM
,
349 MSWToNativeIdx(idx
), (LPARAM
)&hdi
) == -1 )
351 wxLogLastError(wxT("Header_InsertItem()"));
355 void wxHeaderCtrl::DoSetColumnsOrder(const wxArrayInt
& order
)
357 wxArrayInt orderShown
;
358 orderShown
.reserve(m_numColumns
);
360 for ( unsigned n
= 0; n
< m_numColumns
; n
++ )
362 const int idx
= order
[n
];
363 if ( GetColumn(idx
).IsShown() )
364 orderShown
.push_back(MSWToNativeIdx(idx
));
367 if ( !Header_SetOrderArray(GetHwnd(), orderShown
.size(), &orderShown
[0]) )
369 wxLogLastError(wxT("Header_GetOrderArray"));
372 m_colIndices
= order
;
375 wxArrayInt
wxHeaderCtrl::DoGetColumnsOrder() const
377 // we don't use Header_GetOrderArray() here because it doesn't return
378 // information about the hidden columns, instead we just save the columns
379 // order array in DoSetColumnsOrder() and update it when they're reordered
383 // ----------------------------------------------------------------------------
384 // wxHeaderCtrl indexes and positions translation
385 // ----------------------------------------------------------------------------
387 int wxHeaderCtrl::MSWToNativeIdx(int idx
)
389 // don't check for GetColumn(idx).IsShown() as it could have just became
390 // false and we may be called from DoUpdate() to delete the old column
391 wxASSERT_MSG( !m_isHidden
[idx
],
392 "column must be visible to have an "
393 "index in the native control" );
396 for ( int i
= 0; i
< idx
; i
++ )
398 if ( GetColumn(i
).IsHidden() )
399 item
--; // one less column the native control knows about
402 wxASSERT_MSG( item
>= 0 && item
<= GetShownColumnsCount(), "logic error" );
407 int wxHeaderCtrl::MSWFromNativeIdx(int item
)
409 wxASSERT_MSG( item
>= 0 && item
< GetShownColumnsCount(),
410 "column index out of range" );
412 // reverse the above function
415 for ( unsigned n
= 0; n
< m_numColumns
; n
++ )
420 if ( GetColumn(n
).IsHidden() )
424 wxASSERT_MSG( MSWToNativeIdx(idx
) == item
, "logic error" );
429 int wxHeaderCtrl::MSWToNativeOrder(int pos
)
431 wxASSERT_MSG( pos
>= 0 && static_cast<unsigned>(pos
) < m_numColumns
,
432 "column position out of range" );
435 for ( int n
= 0; n
< pos
; n
++ )
437 if ( GetColumn(m_colIndices
[n
]).IsHidden() )
441 wxASSERT_MSG( order
>= 0 && order
<= GetShownColumnsCount(), "logic error" );
446 int wxHeaderCtrl::MSWFromNativeOrder(int order
)
448 wxASSERT_MSG( order
>= 0 && order
< GetShownColumnsCount(),
449 "native column position out of range" );
451 unsigned pos
= order
;
452 for ( unsigned n
= 0; n
< m_numColumns
; n
++ )
457 if ( GetColumn(m_colIndices
[n
]).IsHidden() )
461 wxASSERT_MSG( MSWToNativeOrder(pos
) == order
, "logic error" );
466 // ----------------------------------------------------------------------------
467 // wxHeaderCtrl events
468 // ----------------------------------------------------------------------------
470 wxEventType
wxHeaderCtrl::GetClickEventType(bool dblclk
, int button
)
476 evtType
= dblclk
? wxEVT_COMMAND_HEADER_DCLICK
477 : wxEVT_COMMAND_HEADER_CLICK
;
481 evtType
= dblclk
? wxEVT_COMMAND_HEADER_RIGHT_DCLICK
482 : wxEVT_COMMAND_HEADER_RIGHT_CLICK
;
486 evtType
= dblclk
? wxEVT_COMMAND_HEADER_MIDDLE_DCLICK
487 : wxEVT_COMMAND_HEADER_MIDDLE_CLICK
;
491 wxFAIL_MSG( wxS("unexpected event type") );
492 evtType
= wxEVT_NULL
;
498 bool wxHeaderCtrl::MSWOnNotify(int idCtrl
, WXLPARAM lParam
, WXLPARAM
*result
)
500 NMHEADER
* const nmhdr
= (NMHEADER
*)lParam
;
502 wxEventType evtType
= wxEVT_NULL
;
506 const UINT code
= nmhdr
->hdr
.code
;
508 // we don't have the index for all events, e.g. not for NM_RELEASEDCAPTURE
509 // so only access for header control events (and yes, the direction of
510 // comparisons with FIRST/LAST is correct even if it seems inverted)
511 int idx
= code
<= HDN_FIRST
&& code
> HDN_LAST
? nmhdr
->iItem
: -1;
514 // we also get bogus HDN_BEGINDRAG with -1 index so don't call
515 // MSWFromNativeIdx() unconditionally for nmhdr->iItem
516 idx
= MSWFromNativeIdx(idx
);
525 case HDN_ITEMDBLCLICK
:
526 evtType
= GetClickEventType(code
== HDN_ITEMDBLCLICK
, nmhdr
->iButton
);
529 // although we should get the notifications about the right clicks
530 // via HDN_ITEM[DBL]CLICK too according to MSDN this simply doesn't
531 // happen in practice on any Windows system up to 2003
536 idx
= wxMSWGetColumnClicked(&nmhdr
->hdr
, &pt
);
537 if ( idx
!= wxNOT_FOUND
)
539 idx
= MSWFromNativeIdx(idx
);
541 // due to a bug in mingw32 headers NM_RDBLCLK is signed
542 // there so we need a cast to avoid warnings about signed/
543 // unsigned comparison
544 evtType
= GetClickEventType(
545 code
== static_cast<UINT
>(NM_RDBLCLK
), 1);
547 //else: ignore clicks outside any column
551 case HDN_DIVIDERDBLCLICK
:
552 evtType
= wxEVT_COMMAND_HEADER_SEPARATOR_DCLICK
;
556 // column resizing events
557 // ----------------------
559 // see comments in wxListCtrl::MSWOnNotify() for why we catch both
560 // ASCII and Unicode versions of this message
561 case HDN_BEGINTRACKA
:
562 case HDN_BEGINTRACKW
:
563 // non-resizeable columns can't be resized no matter what, don't
564 // even generate any events for them
565 if ( !GetColumn(idx
).IsResizeable() )
571 evtType
= wxEVT_COMMAND_HEADER_BEGIN_RESIZE
;
576 width
= nmhdr
->pitem
->cxy
;
578 if ( evtType
== wxEVT_NULL
)
580 evtType
= wxEVT_COMMAND_HEADER_END_RESIZE
;
582 // don't generate events with invalid width
583 const int minWidth
= GetColumn(idx
).GetMinWidth();
584 if ( width
< minWidth
)
589 case HDN_ITEMCHANGING
:
590 if ( nmhdr
->pitem
&& (nmhdr
->pitem
->mask
& HDI_WIDTH
) )
592 // prevent the column from being shrunk beneath its min width
593 width
= nmhdr
->pitem
->cxy
;
594 if ( width
< GetColumn(idx
).GetMinWidth() )
596 // don't generate any events and prevent the change from
600 else // width is acceptable
602 // generate the resizing event from here as we don't seem
603 // to be getting HDN_TRACK events at all, at least with
605 evtType
= wxEVT_COMMAND_HEADER_RESIZING
;
611 // column reordering events
612 // ------------------------
615 // Windows sometimes sends us events with invalid column indices
616 if ( nmhdr
->iItem
== -1 )
619 // column must have the appropriate flag to be draggable
620 if ( !GetColumn(idx
).IsReorderable() )
626 evtType
= wxEVT_COMMAND_HEADER_BEGIN_REORDER
;
630 wxASSERT_MSG( nmhdr
->pitem
->mask
& HDI_ORDER
, "should have order" );
631 order
= nmhdr
->pitem
->iOrder
;
633 // we also get messages with invalid order when column reordering
634 // is cancelled (e.g. by pressing Esc)
638 order
= MSWFromNativeOrder(order
);
640 evtType
= wxEVT_COMMAND_HEADER_END_REORDER
;
643 case NM_RELEASEDCAPTURE
:
644 evtType
= wxEVT_COMMAND_HEADER_DRAGGING_CANCELLED
;
649 // do generate the corresponding wx event
650 if ( evtType
!= wxEVT_NULL
)
652 wxHeaderCtrlEvent
event(evtType
, GetId());
653 event
.SetEventObject(this);
654 event
.SetColumn(idx
);
655 event
.SetWidth(width
);
657 event
.SetNewOrder(order
);
659 if ( GetEventHandler()->ProcessEvent(event
) )
661 if ( event
.IsAllowed() )
662 return true; // skip default message handling below
664 // we need to veto the default handling of this message, don't
665 // return to execute the code in the "if veto" branch below
668 else // not processed
670 // special post-processing for HDN_ENDDRAG: we need to update the
671 // internal column indices array if this is allowed to go ahead as
672 // the native control is going to reorder its columns now
673 if ( evtType
== wxEVT_COMMAND_HEADER_END_REORDER
)
674 MoveColumnInOrderArray(m_colIndices
, idx
, order
);
680 // all of HDN_BEGIN{DRAG,TRACK}, HDN_TRACK and HDN_ITEMCHANGING
681 // interpret TRUE return value as meaning to stop the control
682 // default handling of the message
688 return wxHeaderCtrlBase::MSWOnNotify(idCtrl
, lParam
, result
);
691 #endif // wxHAS_GENERIC_HEADERCTRL
693 #endif // wxUSE_HEADERCTRL