don't duplicate the column reordering in generic wxHeaderCtrl and wxGrid, extract...
[wxWidgets.git] / src / generic / headerctrlg.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/generic/headerctrlg.cpp
3 // Purpose: generic wxHeaderCtrl implementation
4 // Author: Vadim Zeitlin
5 // Created: 2008-12-03
6 // RCS-ID: $Id$
7 // Copyright: (c) 2008 Vadim Zeitlin <vadim@wxwidgets.org>
8 // Licence: wxWindows licence
9 ///////////////////////////////////////////////////////////////////////////////
10
11 // ============================================================================
12 // declarations
13 // ============================================================================
14
15 // ----------------------------------------------------------------------------
16 // headers
17 // ----------------------------------------------------------------------------
18
19 // for compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
21
22 #ifdef __BORLANDC__
23 #pragma hdrstop
24 #endif
25
26 #ifndef WX_PRECOMP
27 #endif // WX_PRECOMP
28
29 #include "wx/headerctrl.h"
30
31 #ifdef wxHAS_GENERIC_HEADERCTRL
32
33 #include "wx/dcbuffer.h"
34 #include "wx/renderer.h"
35
36 // ----------------------------------------------------------------------------
37 // constants
38 // ----------------------------------------------------------------------------
39
40 namespace
41 {
42
43 const unsigned NO_SORT = (unsigned)-1;
44
45 const unsigned COL_NONE = (unsigned)-1;
46
47 } // anonymous namespace
48
49 // ============================================================================
50 // wxHeaderCtrl implementation
51 // ============================================================================
52
53 // ----------------------------------------------------------------------------
54 // wxHeaderCtrl creation
55 // ----------------------------------------------------------------------------
56
57 void wxHeaderCtrl::Init()
58 {
59 m_numColumns = 0;
60 m_hover =
61 m_colBeingResized =
62 m_colBeingReordered = COL_NONE;
63 m_dragOffset = 0;
64 m_scrollOffset = 0;
65 }
66
67 bool wxHeaderCtrl::Create(wxWindow *parent,
68 wxWindowID id,
69 const wxPoint& pos,
70 const wxSize& size,
71 long style,
72 const wxString& name)
73 {
74 if ( !wxHeaderCtrlBase::Create(parent, id, pos, size,
75 style, wxDefaultValidator, name) )
76 return false;
77
78 // tell the system to not paint the background at all to avoid flicker as
79 // we paint the entire window area in our OnPaint()
80 SetBackgroundStyle(wxBG_STYLE_CUSTOM);
81
82 return true;
83 }
84
85 wxHeaderCtrl::~wxHeaderCtrl()
86 {
87 }
88
89 // ----------------------------------------------------------------------------
90 // wxHeaderCtrl columns manipulation
91 // ----------------------------------------------------------------------------
92
93 void wxHeaderCtrl::DoSetCount(unsigned int count)
94 {
95 // update the column indices array if necessary
96 if ( count > m_numColumns )
97 {
98 // all new columns have default positions equal to their indices
99 for ( unsigned n = m_numColumns; n < count; n++ )
100 m_colIndices.push_back(n);
101 }
102 else if ( count < m_numColumns )
103 {
104 // filter out all the positions which are invalid now while keeping the
105 // order of the remaining ones
106 wxArrayInt colIndices;
107 for ( unsigned n = 0; n < m_numColumns; n++ )
108 {
109 const unsigned idx = m_colIndices[n];
110 if ( idx < count )
111 colIndices.push_back(idx);
112 }
113
114 wxASSERT_MSG( colIndices.size() == count, "logic error" );
115
116 m_colIndices = colIndices;
117 }
118
119 m_numColumns = count;
120
121 Refresh();
122 }
123
124 unsigned int wxHeaderCtrl::DoGetCount() const
125 {
126 return m_numColumns;
127 }
128
129 void wxHeaderCtrl::DoUpdate(unsigned int idx)
130 {
131 // we need to refresh not only this column but also the ones after it in
132 // case it was shown or hidden or its width changed -- it would be nice to
133 // avoid doing this unnecessary by storing the old column width (TODO)
134 RefreshColsAfter(idx);
135 }
136
137 // ----------------------------------------------------------------------------
138 // wxHeaderCtrl scrolling
139 // ----------------------------------------------------------------------------
140
141 void wxHeaderCtrl::DoScrollHorz(int dx)
142 {
143 m_scrollOffset += dx;
144
145 // don't call our own version which calls this function!
146 wxControl::ScrollWindow(dx, 0);
147 }
148
149 // ----------------------------------------------------------------------------
150 // wxHeaderCtrl geometry
151 // ----------------------------------------------------------------------------
152
153 wxSize wxHeaderCtrl::DoGetBestSize() const
154 {
155 // the vertical size is rather arbitrary but it looks better if we leave
156 // some space around the text
157 return wxSize(IsEmpty() ? wxHeaderCtrlBase::DoGetBestSize().x
158 : GetColEnd(GetColumnCount() - 1),
159 (7*GetCharHeight())/4);
160 }
161
162 int wxHeaderCtrl::GetColStart(unsigned int idx) const
163 {
164 wxHeaderCtrl * const self = const_cast<wxHeaderCtrl *>(this);
165
166 int pos = m_scrollOffset;
167 for ( unsigned n = 0; ; n++ )
168 {
169 const unsigned i = m_colIndices[n];
170 if ( i == idx )
171 break;
172
173 const wxHeaderColumn& col = self->GetColumn(i);
174 if ( col.IsShown() )
175 pos += col.GetWidth();
176 }
177
178 return pos;
179 }
180
181 int wxHeaderCtrl::GetColEnd(unsigned int idx) const
182 {
183 int x = GetColStart(idx);
184
185 return x + const_cast<wxHeaderCtrl *>(this)->GetColumn(idx).GetWidth();
186 }
187
188 unsigned int wxHeaderCtrl::FindColumnAtPoint(int x, bool *onSeparator) const
189 {
190 wxHeaderCtrl * const self = const_cast<wxHeaderCtrl *>(this);
191
192 int pos = 0;
193 const unsigned count = GetColumnCount();
194 for ( unsigned n = 0; n < count; n++ )
195 {
196 const unsigned idx = m_colIndices[n];
197 const wxHeaderColumn& col = self->GetColumn(idx);
198 if ( col.IsHidden() )
199 continue;
200
201 pos += col.GetWidth();
202
203 // if the column is resizeable, check if we're approximatively over the
204 // line separating it from the next column
205 //
206 // TODO: don't hardcode sensitivity
207 if ( col.IsResizeable() && abs(x - pos) < 8 )
208 {
209 if ( onSeparator )
210 *onSeparator = true;
211 return idx;
212 }
213
214 // inside this column?
215 if ( x < pos )
216 {
217 if ( onSeparator )
218 *onSeparator = false;
219 return idx;
220 }
221 }
222
223 return COL_NONE;
224 }
225
226 // ----------------------------------------------------------------------------
227 // wxHeaderCtrl repainting
228 // ----------------------------------------------------------------------------
229
230 void wxHeaderCtrl::RefreshCol(unsigned int idx)
231 {
232 wxRect rect = GetClientRect();
233 rect.x += GetColStart(idx);
234 rect.width = GetColumn(idx).GetWidth();
235
236 RefreshRect(rect);
237 }
238
239 void wxHeaderCtrl::RefreshColIfNotNone(unsigned int idx)
240 {
241 if ( idx != COL_NONE )
242 RefreshCol(idx);
243 }
244
245 void wxHeaderCtrl::RefreshColsAfter(unsigned int idx)
246 {
247 wxRect rect = GetClientRect();
248 const int ofs = GetColStart(idx);
249 rect.x += ofs;
250 rect.width -= ofs;
251
252 RefreshRect(rect);
253 }
254
255 // ----------------------------------------------------------------------------
256 // wxHeaderCtrl dragging/resizing/reordering
257 // ----------------------------------------------------------------------------
258
259 bool wxHeaderCtrl::IsResizing() const
260 {
261 return m_colBeingResized != COL_NONE;
262 }
263
264 bool wxHeaderCtrl::IsReordering() const
265 {
266 return m_colBeingReordered != COL_NONE;
267 }
268
269 void wxHeaderCtrl::ClearMarkers()
270 {
271 wxClientDC dc(this);
272
273 wxDCOverlay dcover(m_overlay, &dc);
274 dcover.Clear();
275 }
276
277 void wxHeaderCtrl::UpdateResizingMarker(int xPhysical)
278 {
279 wxClientDC dc(this);
280
281 wxDCOverlay dcover(m_overlay, &dc);
282 dcover.Clear();
283
284 // unfortunately drawing the marker over the parent window doesn't work as
285 // it's usually covered by another window (the main control view) so just
286 // draw the marker over the header itself, even if it makes it not very
287 // useful
288 dc.SetPen(*wxLIGHT_GREY_PEN);
289 dc.DrawLine(xPhysical, 0, xPhysical, GetClientSize().y);
290 }
291
292 void wxHeaderCtrl::EndDragging()
293 {
294 ClearMarkers();
295
296 m_overlay.Reset();
297
298 // don't use the special dragging cursor any more
299 SetCursor(wxNullCursor);
300 }
301
302 void wxHeaderCtrl::CancelDragging()
303 {
304 wxASSERT_MSG( IsDragging(),
305 "shouldn't be called if we're not dragging anything" );
306
307 EndDragging();
308
309 unsigned int& col = IsResizing() ? m_colBeingResized : m_colBeingReordered;
310
311 wxHeaderCtrlEvent event(wxEVT_COMMAND_HEADER_DRAGGING_CANCELLED, GetId());
312 event.SetEventObject(this);
313 event.SetColumn(col);
314
315 GetEventHandler()->ProcessEvent(event);
316
317 col = COL_NONE;
318 }
319
320 int wxHeaderCtrl::ConstrainByMinWidth(unsigned int col, int& xPhysical)
321 {
322 const int xStart = GetColStart(col);
323
324 // notice that GetMinWidth() returns 0 if there is no minimal width so it
325 // still makes sense to use it even in this case
326 const int xMinEnd = xStart + GetColumn(col).GetMinWidth();
327
328 if ( xPhysical < xMinEnd )
329 xPhysical = xMinEnd;
330
331 return xPhysical - xStart;
332 }
333
334 void wxHeaderCtrl::StartOrContinueResizing(unsigned int col, int xPhysical)
335 {
336 wxHeaderCtrlEvent event(IsResizing() ? wxEVT_COMMAND_HEADER_RESIZING
337 : wxEVT_COMMAND_HEADER_BEGIN_RESIZE,
338 GetId());
339 event.SetEventObject(this);
340 event.SetColumn(col);
341
342 event.SetWidth(ConstrainByMinWidth(col, xPhysical));
343
344 if ( GetEventHandler()->ProcessEvent(event) && !event.IsAllowed() )
345 {
346 if ( IsResizing() )
347 {
348 ReleaseMouse();
349 CancelDragging();
350 }
351 //else: nothing to do -- we just don't start to resize
352 }
353 else // go ahead with resizing
354 {
355 if ( !IsResizing() )
356 {
357 m_colBeingResized = col;
358 SetCursor(wxCursor(wxCURSOR_SIZEWE));
359 CaptureMouse();
360 }
361 //else: we had already done the above when we started
362
363 UpdateResizingMarker(xPhysical);
364 }
365 }
366
367 void wxHeaderCtrl::EndResizing(int xPhysical)
368 {
369 wxASSERT_MSG( IsResizing(), "shouldn't be called if we're not resizing" );
370
371 EndDragging();
372
373 ReleaseMouse();
374
375 wxHeaderCtrlEvent event(wxEVT_COMMAND_HEADER_END_RESIZE, GetId());
376 event.SetEventObject(this);
377 event.SetColumn(m_colBeingResized);
378 event.SetWidth(ConstrainByMinWidth(m_colBeingResized, xPhysical));
379
380 GetEventHandler()->ProcessEvent(event);
381
382 m_colBeingResized = COL_NONE;
383 }
384
385 void wxHeaderCtrl::UpdateReorderingMarker(int xPhysical)
386 {
387 wxClientDC dc(this);
388
389 wxDCOverlay dcover(m_overlay, &dc);
390 dcover.Clear();
391
392 dc.SetPen(*wxBLUE);
393 dc.SetBrush(*wxTRANSPARENT_BRUSH);
394
395 // draw the phantom position of the column being dragged
396 int x = xPhysical - m_dragOffset;
397 int y = GetClientSize().y;
398 dc.DrawRectangle(x, 0,
399 GetColumn(m_colBeingReordered).GetWidth(), y);
400
401 // and also a hint indicating where it is going to be inserted if it's
402 // dropped now
403 unsigned int col = FindColumnAtPoint(xPhysical);
404 if ( col != COL_NONE )
405 {
406 static const int DROP_MARKER_WIDTH = 4;
407
408 dc.SetBrush(*wxBLUE);
409 dc.DrawRectangle(GetColEnd(col) - DROP_MARKER_WIDTH/2, 0,
410 DROP_MARKER_WIDTH, y);
411 }
412 }
413
414 void wxHeaderCtrl::StartReordering(unsigned int col, int xPhysical)
415 {
416 wxHeaderCtrlEvent event(wxEVT_COMMAND_HEADER_BEGIN_REORDER, GetId());
417 event.SetEventObject(this);
418 event.SetColumn(col);
419
420 if ( GetEventHandler()->ProcessEvent(event) && !event.IsAllowed() )
421 {
422 // don't start dragging it, nothing to do otherwise
423 return;
424 }
425
426 m_dragOffset = xPhysical - GetColStart(col);
427
428 m_colBeingReordered = col;
429 SetCursor(wxCursor(wxCURSOR_HAND));
430 CaptureMouse();
431
432 UpdateReorderingMarker(xPhysical);
433 }
434
435 void wxHeaderCtrl::EndReordering(int xPhysical)
436 {
437 wxASSERT_MSG( IsReordering(), "shouldn't be called if we're not reordering" );
438
439 EndDragging();
440
441 ReleaseMouse();
442
443 wxHeaderCtrlEvent event(wxEVT_COMMAND_HEADER_END_REORDER, GetId());
444 event.SetEventObject(this);
445 event.SetColumn(m_colBeingReordered);
446
447 const unsigned pos = GetColumnPos(FindColumnAtPoint(xPhysical));
448 event.SetNewOrder(pos);
449
450 if ( !GetEventHandler()->ProcessEvent(event) || event.IsAllowed() )
451 {
452 // do reorder the columns
453 DoMoveCol(m_colBeingReordered, pos);
454 }
455
456 m_colBeingReordered = COL_NONE;
457 }
458
459 // ----------------------------------------------------------------------------
460 // wxHeaderCtrl column reordering
461 // ----------------------------------------------------------------------------
462
463 void wxHeaderCtrl::DoSetColumnsOrder(const wxArrayInt& order)
464 {
465 m_colIndices = order;
466 Refresh();
467 }
468
469 wxArrayInt wxHeaderCtrl::DoGetColumnsOrder() const
470 {
471 return m_colIndices;
472 }
473
474 void wxHeaderCtrl::DoMoveCol(unsigned int idx, unsigned int pos)
475 {
476 MoveColumnInOrderArray(m_colIndices, idx, pos);
477
478 Refresh();
479 }
480
481 // ----------------------------------------------------------------------------
482 // wxHeaderCtrl event handlers
483 // ----------------------------------------------------------------------------
484
485 BEGIN_EVENT_TABLE(wxHeaderCtrl, wxHeaderCtrlBase)
486 EVT_PAINT(wxHeaderCtrl::OnPaint)
487
488 EVT_MOUSE_EVENTS(wxHeaderCtrl::OnMouse)
489
490 EVT_MOUSE_CAPTURE_LOST(wxHeaderCtrl::OnCaptureLost)
491
492 EVT_KEY_DOWN(wxHeaderCtrl::OnKeyDown)
493 END_EVENT_TABLE()
494
495 void wxHeaderCtrl::OnPaint(wxPaintEvent& WXUNUSED(event))
496 {
497 int w, h;
498 GetClientSize(&w, &h);
499
500 wxAutoBufferedPaintDC dc(this);
501
502 dc.SetBackground(GetBackgroundColour());
503 dc.Clear();
504
505 // account for the horizontal scrollbar offset in the parent window
506 dc.SetDeviceOrigin(m_scrollOffset, 0);
507
508 const unsigned int count = m_numColumns;
509 int xpos = 0;
510 for ( unsigned int i = 0; i < count; i++ )
511 {
512 const unsigned idx = m_colIndices[i];
513 const wxHeaderColumn& col = GetColumn(idx);
514 if ( col.IsHidden() )
515 continue;
516
517 const int colWidth = col.GetWidth();
518
519 wxHeaderSortIconType sortArrow;
520 if ( col.IsSortKey() )
521 {
522 sortArrow = col.IsSortOrderAscending() ? wxHDR_SORT_ICON_UP
523 : wxHDR_SORT_ICON_DOWN;
524 }
525 else // not sorting by this column
526 {
527 sortArrow = wxHDR_SORT_ICON_NONE;
528 }
529
530 int state = 0;
531 if ( IsEnabled() )
532 {
533 if ( idx == m_hover )
534 state = wxCONTROL_CURRENT;
535 }
536 else // disabled
537 {
538 state = wxCONTROL_DISABLED;
539 }
540
541 wxHeaderButtonParams params;
542 params.m_labelText = col.GetTitle();
543 params.m_labelBitmap = col.GetBitmap();
544 params.m_labelAlignment = col.GetAlignment();
545
546 wxRendererNative::Get().DrawHeaderButton
547 (
548 this,
549 dc,
550 wxRect(xpos, 0, colWidth, h),
551 state,
552 sortArrow,
553 &params
554 );
555
556 xpos += colWidth;
557 }
558 }
559
560 void wxHeaderCtrl::OnCaptureLost(wxMouseCaptureLostEvent& WXUNUSED(event))
561 {
562 if ( IsDragging() )
563 CancelDragging();
564 }
565
566 void wxHeaderCtrl::OnKeyDown(wxKeyEvent& event)
567 {
568 if ( event.GetKeyCode() == WXK_ESCAPE )
569 {
570 if ( IsDragging() )
571 {
572 ReleaseMouse();
573 CancelDragging();
574
575 return;
576 }
577 }
578
579 event.Skip();
580 }
581
582 void wxHeaderCtrl::OnMouse(wxMouseEvent& mevent)
583 {
584 // do this in advance to allow simply returning if we're not interested,
585 // we'll undo it if we do handle the event below
586 mevent.Skip();
587
588
589 // account for the control displacement
590 const int xPhysical = mevent.GetX();
591 const int xLogical = xPhysical - m_scrollOffset;
592
593 // first deal with the [continuation of any] dragging operations in
594 // progress
595 if ( IsResizing() )
596 {
597 if ( mevent.LeftUp() )
598 EndResizing(xPhysical);
599 else // update the live separator position
600 StartOrContinueResizing(m_colBeingResized, xPhysical);
601
602 return;
603 }
604
605 if ( IsReordering() )
606 {
607 if ( mevent.LeftUp() )
608 EndReordering(xPhysical);
609 else // update the column position
610 UpdateReorderingMarker(xPhysical);
611
612 return;
613 }
614
615
616 // find if the event is over a column at all
617 bool onSeparator;
618 const unsigned col = mevent.Leaving()
619 ? (onSeparator = false, COL_NONE)
620 : FindColumnAtPoint(xLogical, &onSeparator);
621
622
623 // update the highlighted column if it changed
624 if ( col != m_hover )
625 {
626 const unsigned hoverOld = m_hover;
627 m_hover = col;
628
629 RefreshColIfNotNone(hoverOld);
630 RefreshColIfNotNone(m_hover);
631 }
632
633 // update mouse cursor as it moves around
634 if ( mevent.Moving() )
635 {
636 SetCursor(onSeparator ? wxCursor(wxCURSOR_SIZEWE) : wxNullCursor);
637 return;
638 }
639
640 // all the other events only make sense when they happen over a column
641 if ( col == COL_NONE )
642 return;
643
644
645 // enter various dragging modes on left mouse press
646 if ( mevent.LeftDown() )
647 {
648 if ( onSeparator )
649 {
650 // start resizing the column
651 wxASSERT_MSG( !IsResizing(), "reentering column resize mode?" );
652 StartOrContinueResizing(col, xPhysical);
653 }
654 else // on column itself
655 {
656 // start dragging the column
657 wxASSERT_MSG( !IsReordering(), "reentering column move mode?" );
658
659 StartReordering(col, xPhysical);
660 }
661
662 return;
663 }
664
665 // determine the type of header event corresponding to click events
666 wxEventType evtType = wxEVT_NULL;
667 const bool click = mevent.ButtonUp(),
668 dblclk = mevent.ButtonDClick();
669 if ( click || dblclk )
670 {
671 switch ( mevent.GetButton() )
672 {
673 case wxMOUSE_BTN_LEFT:
674 // treat left double clicks on separator specially
675 if ( onSeparator && dblclk )
676 {
677 evtType = wxEVT_COMMAND_HEADER_SEPARATOR_DCLICK;
678 }
679 else // not double click on separator
680 {
681 evtType = click ? wxEVT_COMMAND_HEADER_CLICK
682 : wxEVT_COMMAND_HEADER_DCLICK;
683 }
684 break;
685
686 case wxMOUSE_BTN_RIGHT:
687 evtType = click ? wxEVT_COMMAND_HEADER_RIGHT_CLICK
688 : wxEVT_COMMAND_HEADER_RIGHT_DCLICK;
689 break;
690
691 case wxMOUSE_BTN_MIDDLE:
692 evtType = click ? wxEVT_COMMAND_HEADER_MIDDLE_CLICK
693 : wxEVT_COMMAND_HEADER_MIDDLE_DCLICK;
694 break;
695
696 default:
697 // ignore clicks from other mouse buttons
698 ;
699 }
700 }
701
702 if ( evtType == wxEVT_NULL )
703 return;
704
705 wxHeaderCtrlEvent event(evtType, GetId());
706 event.SetEventObject(this);
707 event.SetColumn(col);
708
709 if ( GetEventHandler()->ProcessEvent(event) )
710 mevent.Skip(false);
711 }
712
713 #endif // wxHAS_GENERIC_HEADERCTRL