]> git.saurik.com Git - wxWidgets.git/blob - src/generic/datavgen.cpp
Reset sorting column in generic wxDataViewCtrl properly.
[wxWidgets.git] / src / generic / datavgen.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/generic/datavgen.cpp
3 // Purpose: wxDataViewCtrl generic implementation
4 // Author: Robert Roebling
5 // Modified by: Francesco Montorsi, Guru Kathiresan, Bo Yang
6 // Id: $Id$
7 // Copyright: (c) 1998 Robert Roebling
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10
11 // For compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
13
14 #ifdef __BORLANDC__
15 #pragma hdrstop
16 #endif
17
18 #if wxUSE_DATAVIEWCTRL
19
20 #include "wx/dataview.h"
21
22 #ifdef wxUSE_GENERICDATAVIEWCTRL
23
24 #ifndef WX_PRECOMP
25 #ifdef __WXMSW__
26 #include "wx/msw/private.h"
27 #include "wx/msw/wrapwin.h"
28 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
29 #endif
30 #include "wx/sizer.h"
31 #include "wx/log.h"
32 #include "wx/dcclient.h"
33 #include "wx/timer.h"
34 #include "wx/settings.h"
35 #include "wx/msgdlg.h"
36 #include "wx/dcscreen.h"
37 #include "wx/frame.h"
38 #endif
39
40 #include "wx/stockitem.h"
41 #include "wx/popupwin.h"
42 #include "wx/renderer.h"
43 #include "wx/dcbuffer.h"
44 #include "wx/icon.h"
45 #include "wx/list.h"
46 #include "wx/listimpl.cpp"
47 #include "wx/imaglist.h"
48 #include "wx/headerctrl.h"
49 #include "wx/dnd.h"
50 #include "wx/stopwatch.h"
51 #include "wx/weakref.h"
52
53 //-----------------------------------------------------------------------------
54 // classes
55 //-----------------------------------------------------------------------------
56
57 class wxDataViewColumn;
58 class wxDataViewHeaderWindow;
59 class wxDataViewCtrl;
60
61 //-----------------------------------------------------------------------------
62 // classes
63 //-----------------------------------------------------------------------------
64
65 static const int SCROLL_UNIT_X = 15;
66
67 // the cell padding on the left/right
68 static const int PADDING_RIGHTLEFT = 3;
69
70 // the expander space margin
71 static const int EXPANDER_MARGIN = 4;
72
73 #ifdef __WXMSW__
74 static const int EXPANDER_OFFSET = 4;
75 #else
76 static const int EXPANDER_OFFSET = 1;
77 #endif
78
79 // Below is the compare stuff.
80 // For the generic implementation, both the leaf nodes and the nodes are sorted for
81 // fast search when needed
82 static wxDataViewModel* g_model;
83
84 // The column is either the index of the column to be used for sorting or one
85 // of the special values in this enum:
86 enum
87 {
88 // Sort when we're thawed later.
89 SortColumn_OnThaw = -3,
90
91 // Don't sort at all.
92 SortColumn_None = -2,
93
94 // Sort using the model default sort order.
95 SortColumn_Default = -1
96 };
97
98 static int g_column = SortColumn_None;
99 static bool g_asending = true;
100
101 // ----------------------------------------------------------------------------
102 // helper functions
103 // ----------------------------------------------------------------------------
104
105 namespace
106 {
107
108 // Return the expander column or, if it is not set, the first column and also
109 // set it as the expander one for the future.
110 wxDataViewColumn* GetExpanderColumnOrFirstOne(wxDataViewCtrl* dataview)
111 {
112 wxDataViewColumn* expander = dataview->GetExpanderColumn();
113 if (!expander)
114 {
115 // TODO-RTL: last column for RTL support
116 expander = dataview->GetColumnAt( 0 );
117 dataview->SetExpanderColumn(expander);
118 }
119
120 return expander;
121 }
122
123 } // anonymous namespace
124
125 //-----------------------------------------------------------------------------
126 // wxDataViewColumn
127 //-----------------------------------------------------------------------------
128
129 void wxDataViewColumn::Init(int width, wxAlignment align, int flags)
130 {
131 m_width = width;
132 m_minWidth = 0;
133 m_align = align;
134 m_flags = flags;
135 m_sort = false;
136 m_sortAscending = true;
137 }
138
139 int wxDataViewColumn::GetWidth() const
140 {
141 switch ( m_width )
142 {
143 case wxCOL_WIDTH_DEFAULT:
144 return wxDVC_DEFAULT_WIDTH;
145
146 case wxCOL_WIDTH_AUTOSIZE:
147 wxCHECK_MSG( m_owner, wxDVC_DEFAULT_WIDTH, "no owner control" );
148 return m_owner->GetBestColumnWidth(m_owner->GetColumnIndex(this));
149
150 default:
151 return m_width;
152 }
153 }
154
155 void wxDataViewColumn::UpdateDisplay()
156 {
157 if (m_owner)
158 {
159 int idx = m_owner->GetColumnIndex( this );
160 m_owner->OnColumnChange( idx );
161 }
162 }
163
164 void wxDataViewColumn::UnsetAsSortKey()
165 {
166 m_sort = false;
167
168 if ( m_owner )
169 m_owner->SetSortingColumnIndex(wxNOT_FOUND);
170
171 UpdateDisplay();
172 }
173
174 void wxDataViewColumn::SetSortOrder(bool ascending)
175 {
176 if ( !m_owner )
177 return;
178
179 // First unset the old sort column if any.
180 int oldSortKey = m_owner->GetSortingColumnIndex();
181 if ( oldSortKey != wxNOT_FOUND )
182 {
183 m_owner->GetColumn(oldSortKey)->UnsetAsSortKey();
184 }
185
186 // Now set this one as the new sort column.
187 const int idx = m_owner->GetColumnIndex(this);
188 m_owner->SetSortingColumnIndex(idx);
189
190 m_sort = true;
191 m_sortAscending = ascending;
192
193 // Call this directly instead of using UpdateDisplay() as we already have
194 // the column index, no need to look it up again.
195 m_owner->OnColumnChange(idx);
196 }
197
198 //-----------------------------------------------------------------------------
199 // wxDataViewHeaderWindow
200 //-----------------------------------------------------------------------------
201
202 class wxDataViewHeaderWindow : public wxHeaderCtrl
203 {
204 public:
205 wxDataViewHeaderWindow(wxDataViewCtrl *parent)
206 : wxHeaderCtrl(parent)
207 {
208 }
209
210 wxDataViewCtrl *GetOwner() const
211 { return static_cast<wxDataViewCtrl *>(GetParent()); }
212
213 protected:
214 // implement/override wxHeaderCtrl functions by forwarding them to the main
215 // control
216 virtual const wxHeaderColumn& GetColumn(unsigned int idx) const
217 {
218 return *(GetOwner()->GetColumn(idx));
219 }
220
221 virtual bool UpdateColumnWidthToFit(unsigned int idx, int widthTitle)
222 {
223 wxDataViewCtrl * const owner = GetOwner();
224
225 int widthContents = owner->GetBestColumnWidth(idx);
226 owner->GetColumn(idx)->SetWidth(wxMax(widthTitle, widthContents));
227 owner->OnColumnChange(idx);
228
229 return true;
230 }
231
232 private:
233 bool SendEvent(wxEventType type, unsigned int n)
234 {
235 wxDataViewCtrl * const owner = GetOwner();
236 wxDataViewEvent event(type, owner->GetId());
237
238 event.SetEventObject(owner);
239 event.SetColumn(n);
240 event.SetDataViewColumn(owner->GetColumn(n));
241 event.SetModel(owner->GetModel());
242
243 // for events created by wxDataViewHeaderWindow the
244 // row / value fields are not valid
245 return owner->ProcessWindowEvent(event);
246 }
247
248 void OnClick(wxHeaderCtrlEvent& event)
249 {
250 const unsigned idx = event.GetColumn();
251
252 if ( SendEvent(wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_CLICK, idx) )
253 return;
254
255 // default handling for the column click is to sort by this column or
256 // toggle its sort order
257 wxDataViewCtrl * const owner = GetOwner();
258 wxDataViewColumn * const col = owner->GetColumn(idx);
259 if ( !col->IsSortable() )
260 {
261 // no default handling for non-sortable columns
262 event.Skip();
263 return;
264 }
265
266 if ( col->IsSortKey() )
267 {
268 // already using this column for sorting, just change the order
269 col->ToggleSortOrder();
270 }
271 else // not using this column for sorting yet
272 {
273 col->SetSortOrder(true);
274 }
275
276 wxDataViewModel * const model = owner->GetModel();
277 if ( model )
278 model->Resort();
279
280 owner->OnColumnChange(idx);
281
282 SendEvent(wxEVT_COMMAND_DATAVIEW_COLUMN_SORTED, idx);
283 }
284
285 void OnRClick(wxHeaderCtrlEvent& event)
286 {
287 if ( !SendEvent(wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK,
288 event.GetColumn()) )
289 event.Skip();
290 }
291
292 void OnResize(wxHeaderCtrlEvent& event)
293 {
294 wxDataViewCtrl * const owner = GetOwner();
295
296 const unsigned col = event.GetColumn();
297 owner->GetColumn(col)->SetWidth(event.GetWidth());
298 GetOwner()->OnColumnChange(col);
299 }
300
301 void OnEndReorder(wxHeaderCtrlEvent& event)
302 {
303 wxDataViewCtrl * const owner = GetOwner();
304 owner->ColumnMoved(owner->GetColumn(event.GetColumn()),
305 event.GetNewOrder());
306 }
307
308 DECLARE_EVENT_TABLE()
309 wxDECLARE_NO_COPY_CLASS(wxDataViewHeaderWindow);
310 };
311
312 BEGIN_EVENT_TABLE(wxDataViewHeaderWindow, wxHeaderCtrl)
313 EVT_HEADER_CLICK(wxID_ANY, wxDataViewHeaderWindow::OnClick)
314 EVT_HEADER_RIGHT_CLICK(wxID_ANY, wxDataViewHeaderWindow::OnRClick)
315
316 EVT_HEADER_RESIZING(wxID_ANY, wxDataViewHeaderWindow::OnResize)
317 EVT_HEADER_END_RESIZE(wxID_ANY, wxDataViewHeaderWindow::OnResize)
318
319 EVT_HEADER_END_REORDER(wxID_ANY, wxDataViewHeaderWindow::OnEndReorder)
320 END_EVENT_TABLE()
321
322 //-----------------------------------------------------------------------------
323 // wxDataViewRenameTimer
324 //-----------------------------------------------------------------------------
325
326 class wxDataViewRenameTimer: public wxTimer
327 {
328 private:
329 wxDataViewMainWindow *m_owner;
330
331 public:
332 wxDataViewRenameTimer( wxDataViewMainWindow *owner );
333 void Notify();
334 };
335
336 //-----------------------------------------------------------------------------
337 // wxDataViewTreeNode
338 //-----------------------------------------------------------------------------
339
340 class wxDataViewTreeNode;
341 WX_DEFINE_ARRAY( wxDataViewTreeNode *, wxDataViewTreeNodes );
342
343 int LINKAGEMODE wxGenericTreeModelNodeCmp( wxDataViewTreeNode ** node1,
344 wxDataViewTreeNode ** node2);
345
346 class wxDataViewTreeNode
347 {
348 public:
349 wxDataViewTreeNode(wxDataViewTreeNode *parent, const wxDataViewItem& item)
350 : m_parent(parent),
351 m_item(item),
352 m_branchData(NULL)
353 {
354 }
355
356 ~wxDataViewTreeNode()
357 {
358 if ( m_branchData )
359 {
360 wxDataViewTreeNodes& nodes = m_branchData->children;
361 for ( wxDataViewTreeNodes::iterator i = nodes.begin();
362 i != nodes.end();
363 ++i )
364 {
365 delete *i;
366 }
367
368 delete m_branchData;
369 }
370 }
371
372 static wxDataViewTreeNode* CreateRootNode()
373 {
374 wxDataViewTreeNode *n = new wxDataViewTreeNode(NULL, wxDataViewItem());
375 n->m_branchData = new BranchNodeData;
376 n->m_branchData->open = true;
377 return n;
378 }
379
380 wxDataViewTreeNode * GetParent() const { return m_parent; }
381
382 const wxDataViewTreeNodes& GetChildNodes() const
383 {
384 wxASSERT( m_branchData != NULL );
385 return m_branchData->children;
386 }
387
388 void InsertChild(wxDataViewTreeNode *node, unsigned index)
389 {
390 if ( !m_branchData )
391 m_branchData = new BranchNodeData;
392
393 m_branchData->children.Insert(node, index);
394
395 // TODO: insert into sorted array directly in O(log n) instead of resorting in O(n log n)
396 if (g_column >= -1)
397 m_branchData->children.Sort( &wxGenericTreeModelNodeCmp );
398 }
399
400 void RemoveChild(wxDataViewTreeNode *node)
401 {
402 wxCHECK_RET( m_branchData != NULL, "leaf node doesn't have children" );
403 m_branchData->children.Remove(node);
404 }
405
406 // returns position of child node for given item in children list or wxNOT_FOUND
407 int FindChildByItem(const wxDataViewItem& item) const
408 {
409 if ( !m_branchData )
410 return wxNOT_FOUND;
411
412 const wxDataViewTreeNodes& nodes = m_branchData->children;
413 const int len = nodes.size();
414 for ( int i = 0; i < len; i++ )
415 {
416 if ( nodes[i]->m_item == item )
417 return i;
418 }
419 return wxNOT_FOUND;
420 }
421
422 const wxDataViewItem & GetItem() const { return m_item; }
423 void SetItem( const wxDataViewItem & item ) { m_item = item; }
424
425 int GetIndentLevel() const
426 {
427 int ret = 0;
428 const wxDataViewTreeNode * node = this;
429 while( node->GetParent()->GetParent() != NULL )
430 {
431 node = node->GetParent();
432 ret ++;
433 }
434 return ret;
435 }
436
437 bool IsOpen() const
438 {
439 return m_branchData && m_branchData->open;
440 }
441
442 void ToggleOpen()
443 {
444 // We do not allow the (invisible) root node to be collapsed because
445 // there is no way to expand it again.
446 if ( !m_parent )
447 return;
448
449 wxCHECK_RET( m_branchData != NULL, "can't open leaf node" );
450
451 int sum = 0;
452
453 const wxDataViewTreeNodes& nodes = m_branchData->children;
454 const int len = nodes.GetCount();
455 for ( int i = 0;i < len; i ++)
456 sum += 1 + nodes[i]->GetSubTreeCount();
457
458 if (m_branchData->open)
459 {
460 ChangeSubTreeCount(-sum);
461 m_branchData->open = !m_branchData->open;
462 }
463 else
464 {
465 m_branchData->open = !m_branchData->open;
466 ChangeSubTreeCount(+sum);
467 }
468 }
469
470 // "HasChildren" property corresponds to model's IsContainer(). Note that it may be true
471 // even if GetChildNodes() is empty; see below.
472 bool HasChildren() const
473 {
474 return m_branchData != NULL;
475 }
476
477 void SetHasChildren(bool has)
478 {
479 // The invisible root item always has children, so ignore any attempts
480 // to change this.
481 if ( !m_parent )
482 return;
483
484 if ( !has )
485 {
486 wxDELETE(m_branchData);
487 }
488 else if ( m_branchData == NULL )
489 {
490 m_branchData = new BranchNodeData;
491 }
492 }
493
494 int GetSubTreeCount() const
495 {
496 return m_branchData ? m_branchData->subTreeCount : 0;
497 }
498
499 void ChangeSubTreeCount( int num )
500 {
501 wxASSERT( m_branchData != NULL );
502
503 if( !m_branchData->open )
504 return;
505
506 m_branchData->subTreeCount += num;
507 wxASSERT( m_branchData->subTreeCount >= 0 );
508
509 if( m_parent )
510 m_parent->ChangeSubTreeCount(num);
511 }
512
513 void Resort()
514 {
515 if ( !m_branchData )
516 return;
517
518 if (g_column >= -1)
519 {
520 wxDataViewTreeNodes& nodes = m_branchData->children;
521
522 nodes.Sort( &wxGenericTreeModelNodeCmp );
523 int len = nodes.GetCount();
524 for (int i = 0; i < len; i ++)
525 {
526 if ( nodes[i]->HasChildren() )
527 nodes[i]->Resort();
528 }
529 }
530 }
531
532
533 private:
534 wxDataViewTreeNode *m_parent;
535
536 // Corresponding model item.
537 wxDataViewItem m_item;
538
539 // Data specific to non-leaf (branch, inner) nodes. They are kept in a
540 // separate struct in order to conserve memory.
541 struct BranchNodeData
542 {
543 BranchNodeData()
544 : open(false),
545 subTreeCount(0)
546 {
547 }
548
549 // Child nodes. Note that this may be empty even if m_hasChildren in
550 // case this branch of the tree wasn't expanded and realized yet.
551 wxDataViewTreeNodes children;
552
553 // Is the branch node currently open (expanded)?
554 bool open;
555
556 // Total count of expanded (i.e. visible with the help of some
557 // scrolling) items in the subtree, but excluding this node. I.e. it is
558 // 0 for leaves and is the number of rows the subtree occupies for
559 // branch nodes.
560 int subTreeCount;
561 };
562
563 BranchNodeData *m_branchData;
564 };
565
566
567 int LINKAGEMODE wxGenericTreeModelNodeCmp( wxDataViewTreeNode ** node1,
568 wxDataViewTreeNode ** node2)
569 {
570 return g_model->Compare( (*node1)->GetItem(), (*node2)->GetItem(), g_column, g_asending );
571 }
572
573
574 //-----------------------------------------------------------------------------
575 // wxDataViewMainWindow
576 //-----------------------------------------------------------------------------
577
578 WX_DEFINE_SORTED_ARRAY_SIZE_T(unsigned int, wxDataViewSelection);
579
580 class wxDataViewMainWindow: public wxWindow
581 {
582 public:
583 wxDataViewMainWindow( wxDataViewCtrl *parent,
584 wxWindowID id,
585 const wxPoint &pos = wxDefaultPosition,
586 const wxSize &size = wxDefaultSize,
587 const wxString &name = wxT("wxdataviewctrlmainwindow") );
588 virtual ~wxDataViewMainWindow();
589
590 bool IsList() const { return GetModel()->IsListModel(); }
591 bool IsVirtualList() const { return m_root == NULL; }
592
593 // notifications from wxDataViewModel
594 bool ItemAdded( const wxDataViewItem &parent, const wxDataViewItem &item );
595 bool ItemDeleted( const wxDataViewItem &parent, const wxDataViewItem &item );
596 bool ItemChanged( const wxDataViewItem &item );
597 bool ValueChanged( const wxDataViewItem &item, unsigned int model_column );
598 bool Cleared();
599 void Resort()
600 {
601 if (!IsVirtualList())
602 {
603 SortPrepare();
604 m_root->Resort();
605 }
606 UpdateDisplay();
607 }
608
609 // Override the base class method to resort if needed, i.e. if
610 // SortPrepare() was called -- and ignored -- while we were frozen.
611 virtual void DoThaw()
612 {
613 if ( g_column == SortColumn_OnThaw )
614 {
615 Resort();
616 g_column = SortColumn_None;
617 }
618
619 wxWindow::DoThaw();
620 }
621
622 void SortPrepare()
623 {
624 g_model = GetModel();
625
626 wxDataViewColumn* col = GetOwner()->GetSortingColumn();
627 if( !col )
628 {
629 if (g_model->HasDefaultCompare())
630 {
631 // See below for the explanation of IsFrozen() test.
632 if ( IsFrozen() )
633 g_column = SortColumn_OnThaw;
634 else
635 g_column = SortColumn_Default;
636 }
637 else
638 g_column = SortColumn_None;
639
640 g_asending = true;
641 return;
642 }
643
644 // Avoid sorting while the window is frozen, this allows to quickly add
645 // many items without resorting after each addition and only resort
646 // them all at once when the window is finally thawed, see above.
647 if ( IsFrozen() )
648 {
649 g_column = SortColumn_OnThaw;
650 return;
651 }
652
653 g_column = col->GetModelColumn();
654 g_asending = col->IsSortOrderAscending();
655 }
656
657 void SetOwner( wxDataViewCtrl* owner ) { m_owner = owner; }
658 wxDataViewCtrl *GetOwner() { return m_owner; }
659 const wxDataViewCtrl *GetOwner() const { return m_owner; }
660
661 wxDataViewModel* GetModel() { return GetOwner()->GetModel(); }
662 const wxDataViewModel* GetModel() const { return GetOwner()->GetModel(); }
663
664 #if wxUSE_DRAG_AND_DROP
665 wxBitmap CreateItemBitmap( unsigned int row, int &indent );
666 #endif // wxUSE_DRAG_AND_DROP
667 void OnPaint( wxPaintEvent &event );
668 void OnCharHook( wxKeyEvent &event );
669 void OnChar( wxKeyEvent &event );
670 void OnVerticalNavigation(int delta, const wxKeyEvent& event);
671 void OnLeftKey();
672 void OnRightKey();
673 void OnMouse( wxMouseEvent &event );
674 void OnSetFocus( wxFocusEvent &event );
675 void OnKillFocus( wxFocusEvent &event );
676
677 void UpdateDisplay();
678 void RecalculateDisplay();
679 void OnInternalIdle();
680
681 void OnRenameTimer();
682
683 void ScrollWindow( int dx, int dy, const wxRect *rect = NULL );
684 void ScrollTo( int rows, int column );
685
686 unsigned GetCurrentRow() const { return m_currentRow; }
687 bool HasCurrentRow() { return m_currentRow != (unsigned int)-1; }
688 void ChangeCurrentRow( unsigned int row );
689 bool TryAdvanceCurrentColumn(wxDataViewTreeNode *node, bool forward);
690
691 wxDataViewColumn *GetCurrentColumn() const { return m_currentCol; }
692 void ClearCurrentColumn() { m_currentCol = NULL; }
693
694 bool IsSingleSel() const { return !GetParent()->HasFlag(wxDV_MULTIPLE); }
695 bool IsEmpty() { return GetRowCount() == 0; }
696
697 int GetCountPerPage() const;
698 int GetEndOfLastCol() const;
699 unsigned int GetFirstVisibleRow() const;
700
701 // I change this method to un const because in the tree view,
702 // the displaying number of the tree are changing along with the
703 // expanding/collapsing of the tree nodes
704 unsigned int GetLastVisibleRow();
705 unsigned int GetRowCount() const;
706
707 const wxDataViewSelection& GetSelections() const { return m_selection; }
708 void SetSelections( const wxDataViewSelection & sel )
709 { m_selection = sel; UpdateDisplay(); }
710 void Select( const wxArrayInt& aSelections );
711 void SelectAllRows( bool on );
712 void SelectRow( unsigned int row, bool on );
713 void SelectRows( unsigned int from, unsigned int to, bool on );
714 void ReverseRowSelection( unsigned int row );
715 bool IsRowSelected( unsigned int row );
716 void SendSelectionChangedEvent( const wxDataViewItem& item);
717
718 void RefreshRow( unsigned int row );
719 void RefreshRows( unsigned int from, unsigned int to );
720 void RefreshRowsAfter( unsigned int firstRow );
721
722 // returns the colour to be used for drawing the rules
723 wxColour GetRuleColour() const
724 {
725 return wxSystemSettings::GetColour(wxSYS_COLOUR_3DLIGHT);
726 }
727
728 wxRect GetLineRect( unsigned int row ) const;
729
730 int GetLineStart( unsigned int row ) const; // row * m_lineHeight in fixed mode
731 int GetLineHeight( unsigned int row ) const; // m_lineHeight in fixed mode
732 int GetLineAt( unsigned int y ) const; // y / m_lineHeight in fixed mode
733
734 void SetRowHeight( int lineHeight ) { m_lineHeight = lineHeight; }
735 int GetRowHeight() const { return m_lineHeight; }
736 int GetDefaultRowHeight() const;
737
738 // Some useful functions for row and item mapping
739 wxDataViewItem GetItemByRow( unsigned int row ) const;
740 int GetRowByItem( const wxDataViewItem & item ) const;
741
742 wxDataViewTreeNode * GetTreeNodeByRow( unsigned int row ) const;
743 // We did not need this temporarily
744 // wxDataViewTreeNode * GetTreeNodeByItem( const wxDataViewItem & item );
745
746 // Methods for building the mapping tree
747 void BuildTree( wxDataViewModel * model );
748 void DestroyTree();
749 void HitTest( const wxPoint & point, wxDataViewItem & item, wxDataViewColumn* &column );
750 wxRect GetItemRect( const wxDataViewItem & item, const wxDataViewColumn* column );
751
752 void Expand( unsigned int row );
753 void Collapse( unsigned int row );
754 bool IsExpanded( unsigned int row ) const;
755 bool HasChildren( unsigned int row ) const;
756
757 #if wxUSE_DRAG_AND_DROP
758 bool EnableDragSource( const wxDataFormat &format );
759 bool EnableDropTarget( const wxDataFormat &format );
760
761 void RemoveDropHint();
762 wxDragResult OnDragOver( wxDataFormat format, wxCoord x, wxCoord y, wxDragResult def );
763 bool OnDrop( wxDataFormat format, wxCoord x, wxCoord y );
764 wxDragResult OnData( wxDataFormat format, wxCoord x, wxCoord y, wxDragResult def );
765 void OnLeave();
766 #endif // wxUSE_DRAG_AND_DROP
767
768 void OnColumnsCountChanged();
769
770 // Called by wxDataViewCtrl and our own OnRenameTimer() to start edit the
771 // specified item in the given column.
772 void StartEditing(const wxDataViewItem& item, const wxDataViewColumn* col);
773
774 private:
775 int RecalculateCount() const;
776
777 // Return false only if the event was vetoed by its handler.
778 bool SendExpanderEvent(wxEventType type, const wxDataViewItem& item);
779
780 wxDataViewTreeNode * FindNode( const wxDataViewItem & item );
781
782 wxDataViewColumn *FindColumnForEditing(const wxDataViewItem& item, wxDataViewCellMode mode);
783
784 bool IsCellEditableInMode(const wxDataViewItem& item, const wxDataViewColumn *col, wxDataViewCellMode mode) const;
785
786 void DrawCellBackground( wxDataViewRenderer* cell, wxDC& dc, const wxRect& rect );
787
788 private:
789 wxDataViewCtrl *m_owner;
790 int m_lineHeight;
791 bool m_dirty;
792
793 wxDataViewColumn *m_currentCol;
794 unsigned int m_currentRow;
795 wxDataViewSelection m_selection;
796
797 wxDataViewRenameTimer *m_renameTimer;
798 bool m_lastOnSame;
799
800 bool m_hasFocus;
801 bool m_useCellFocus;
802 bool m_currentColSetByKeyboard;
803
804 #if wxUSE_DRAG_AND_DROP
805 int m_dragCount;
806 wxPoint m_dragStart;
807
808 bool m_dragEnabled;
809 wxDataFormat m_dragFormat;
810
811 bool m_dropEnabled;
812 wxDataFormat m_dropFormat;
813 bool m_dropHint;
814 unsigned int m_dropHintLine;
815 #endif // wxUSE_DRAG_AND_DROP
816
817 // for double click logic
818 unsigned int m_lineLastClicked,
819 m_lineBeforeLastClicked,
820 m_lineSelectSingleOnUp;
821
822 // the pen used to draw horiz/vertical rules
823 wxPen m_penRule;
824
825 // the pen used to draw the expander and the lines
826 wxPen m_penExpander;
827
828 // This is the tree structure of the model
829 wxDataViewTreeNode * m_root;
830 int m_count;
831
832 // This is the tree node under the cursor
833 wxDataViewTreeNode * m_underMouse;
834
835 // The control used for editing or NULL.
836 wxWeakRef<wxWindow> m_editorCtrl;
837
838 // Id m_editorCtrl is non-NULL, pointer to the associated renderer.
839 wxDataViewRenderer* m_editorRenderer;
840
841 private:
842 DECLARE_DYNAMIC_CLASS(wxDataViewMainWindow)
843 DECLARE_EVENT_TABLE()
844 };
845
846 // ---------------------------------------------------------
847 // wxGenericDataViewModelNotifier
848 // ---------------------------------------------------------
849
850 class wxGenericDataViewModelNotifier: public wxDataViewModelNotifier
851 {
852 public:
853 wxGenericDataViewModelNotifier( wxDataViewMainWindow *mainWindow )
854 { m_mainWindow = mainWindow; }
855
856 virtual bool ItemAdded( const wxDataViewItem & parent, const wxDataViewItem & item )
857 { return m_mainWindow->ItemAdded( parent , item ); }
858 virtual bool ItemDeleted( const wxDataViewItem &parent, const wxDataViewItem &item )
859 { return m_mainWindow->ItemDeleted( parent, item ); }
860 virtual bool ItemChanged( const wxDataViewItem & item )
861 { return m_mainWindow->ItemChanged(item); }
862 virtual bool ValueChanged( const wxDataViewItem & item , unsigned int col )
863 { return m_mainWindow->ValueChanged( item, col ); }
864 virtual bool Cleared()
865 { return m_mainWindow->Cleared(); }
866 virtual void Resort()
867 { m_mainWindow->Resort(); }
868
869 wxDataViewMainWindow *m_mainWindow;
870 };
871
872 // ---------------------------------------------------------
873 // wxDataViewRenderer
874 // ---------------------------------------------------------
875
876 IMPLEMENT_ABSTRACT_CLASS(wxDataViewRenderer, wxDataViewRendererBase)
877
878 wxDataViewRenderer::wxDataViewRenderer( const wxString &varianttype,
879 wxDataViewCellMode mode,
880 int align) :
881 wxDataViewCustomRendererBase( varianttype, mode, align )
882 {
883 m_align = align;
884 m_mode = mode;
885 m_ellipsizeMode = wxELLIPSIZE_MIDDLE;
886 m_dc = NULL;
887 }
888
889 wxDataViewRenderer::~wxDataViewRenderer()
890 {
891 delete m_dc;
892 }
893
894 wxDC *wxDataViewRenderer::GetDC()
895 {
896 if (m_dc == NULL)
897 {
898 if (GetOwner() == NULL)
899 return NULL;
900 if (GetOwner()->GetOwner() == NULL)
901 return NULL;
902 m_dc = new wxClientDC( GetOwner()->GetOwner() );
903 }
904
905 return m_dc;
906 }
907
908 void wxDataViewRenderer::SetAlignment( int align )
909 {
910 m_align=align;
911 }
912
913 int wxDataViewRenderer::GetAlignment() const
914 {
915 return m_align;
916 }
917
918 // ---------------------------------------------------------
919 // wxDataViewCustomRenderer
920 // ---------------------------------------------------------
921
922 IMPLEMENT_ABSTRACT_CLASS(wxDataViewCustomRenderer, wxDataViewRenderer)
923
924 wxDataViewCustomRenderer::wxDataViewCustomRenderer( const wxString &varianttype,
925 wxDataViewCellMode mode, int align ) :
926 wxDataViewRenderer( varianttype, mode, align )
927 {
928 }
929
930 // ---------------------------------------------------------
931 // wxDataViewTextRenderer
932 // ---------------------------------------------------------
933
934 IMPLEMENT_CLASS(wxDataViewTextRenderer, wxDataViewRenderer)
935
936 wxDataViewTextRenderer::wxDataViewTextRenderer( const wxString &varianttype,
937 wxDataViewCellMode mode, int align ) :
938 wxDataViewRenderer( varianttype, mode, align )
939 {
940 }
941
942 bool wxDataViewTextRenderer::SetValue( const wxVariant &value )
943 {
944 m_text = value.GetString();
945
946 return true;
947 }
948
949 bool wxDataViewTextRenderer::GetValue( wxVariant& WXUNUSED(value) ) const
950 {
951 return false;
952 }
953
954 bool wxDataViewTextRenderer::HasEditorCtrl() const
955 {
956 return true;
957 }
958
959 wxWindow* wxDataViewTextRenderer::CreateEditorCtrl( wxWindow *parent,
960 wxRect labelRect, const wxVariant &value )
961 {
962 wxTextCtrl* ctrl = new wxTextCtrl( parent, wxID_ANY, value,
963 wxPoint(labelRect.x,labelRect.y),
964 wxSize(labelRect.width,labelRect.height),
965 wxTE_PROCESS_ENTER );
966
967 // select the text in the control an place the cursor at the end
968 ctrl->SetInsertionPointEnd();
969 ctrl->SelectAll();
970
971 return ctrl;
972 }
973
974 bool wxDataViewTextRenderer::GetValueFromEditorCtrl( wxWindow *editor, wxVariant &value )
975 {
976 wxTextCtrl *text = (wxTextCtrl*) editor;
977 value = text->GetValue();
978 return true;
979 }
980
981 bool wxDataViewTextRenderer::Render(wxRect rect, wxDC *dc, int state)
982 {
983 RenderText(m_text, 0, rect, dc, state);
984 return true;
985 }
986
987 wxSize wxDataViewTextRenderer::GetSize() const
988 {
989 if (!m_text.empty())
990 return GetTextExtent(m_text);
991 else
992 return wxSize(wxDVC_DEFAULT_RENDERER_SIZE,wxDVC_DEFAULT_RENDERER_SIZE);
993 }
994
995 // ---------------------------------------------------------
996 // wxDataViewBitmapRenderer
997 // ---------------------------------------------------------
998
999 IMPLEMENT_CLASS(wxDataViewBitmapRenderer, wxDataViewRenderer)
1000
1001 wxDataViewBitmapRenderer::wxDataViewBitmapRenderer( const wxString &varianttype,
1002 wxDataViewCellMode mode, int align ) :
1003 wxDataViewRenderer( varianttype, mode, align )
1004 {
1005 }
1006
1007 bool wxDataViewBitmapRenderer::SetValue( const wxVariant &value )
1008 {
1009 if (value.GetType() == wxT("wxBitmap"))
1010 m_bitmap << value;
1011 if (value.GetType() == wxT("wxIcon"))
1012 m_icon << value;
1013
1014 return true;
1015 }
1016
1017 bool wxDataViewBitmapRenderer::GetValue( wxVariant& WXUNUSED(value) ) const
1018 {
1019 return false;
1020 }
1021
1022 bool wxDataViewBitmapRenderer::Render( wxRect cell, wxDC *dc, int WXUNUSED(state) )
1023 {
1024 if (m_bitmap.IsOk())
1025 dc->DrawBitmap( m_bitmap, cell.x, cell.y );
1026 else if (m_icon.IsOk())
1027 dc->DrawIcon( m_icon, cell.x, cell.y );
1028
1029 return true;
1030 }
1031
1032 wxSize wxDataViewBitmapRenderer::GetSize() const
1033 {
1034 if (m_bitmap.IsOk())
1035 return wxSize( m_bitmap.GetWidth(), m_bitmap.GetHeight() );
1036 else if (m_icon.IsOk())
1037 return wxSize( m_icon.GetWidth(), m_icon.GetHeight() );
1038
1039 return wxSize(wxDVC_DEFAULT_RENDERER_SIZE,wxDVC_DEFAULT_RENDERER_SIZE);
1040 }
1041
1042 // ---------------------------------------------------------
1043 // wxDataViewToggleRenderer
1044 // ---------------------------------------------------------
1045
1046 IMPLEMENT_ABSTRACT_CLASS(wxDataViewToggleRenderer, wxDataViewRenderer)
1047
1048 wxDataViewToggleRenderer::wxDataViewToggleRenderer( const wxString &varianttype,
1049 wxDataViewCellMode mode, int align ) :
1050 wxDataViewRenderer( varianttype, mode, align )
1051 {
1052 m_toggle = false;
1053 }
1054
1055 bool wxDataViewToggleRenderer::SetValue( const wxVariant &value )
1056 {
1057 m_toggle = value.GetBool();
1058
1059 return true;
1060 }
1061
1062 bool wxDataViewToggleRenderer::GetValue( wxVariant &WXUNUSED(value) ) const
1063 {
1064 return false;
1065 }
1066
1067 bool wxDataViewToggleRenderer::Render( wxRect cell, wxDC *dc, int WXUNUSED(state) )
1068 {
1069 int flags = 0;
1070 if (m_toggle)
1071 flags |= wxCONTROL_CHECKED;
1072 if (GetMode() != wxDATAVIEW_CELL_ACTIVATABLE ||
1073 GetEnabled() == false)
1074 flags |= wxCONTROL_DISABLED;
1075
1076 // Ensure that the check boxes always have at least the minimal required
1077 // size, otherwise DrawCheckBox() doesn't really work well. If this size is
1078 // greater than the cell size, the checkbox will be truncated but this is a
1079 // lesser evil.
1080 wxSize size = cell.GetSize();
1081 size.IncTo(GetSize());
1082 cell.SetSize(size);
1083
1084 wxRendererNative::Get().DrawCheckBox(
1085 GetOwner()->GetOwner(),
1086 *dc,
1087 cell,
1088 flags );
1089
1090 return true;
1091 }
1092
1093 bool wxDataViewToggleRenderer::WXActivateCell(const wxRect& WXUNUSED(cell),
1094 wxDataViewModel *model,
1095 const wxDataViewItem& item,
1096 unsigned int col,
1097 const wxMouseEvent *mouseEvent)
1098 {
1099 if ( mouseEvent )
1100 {
1101 // only react to clicks directly on the checkbox, not elsewhere in the same cell:
1102 if ( !wxRect(GetSize()).Contains(mouseEvent->GetPosition()) )
1103 return false;
1104 }
1105
1106 model->ChangeValue(!m_toggle, item, col);
1107 return true;
1108 }
1109
1110 wxSize wxDataViewToggleRenderer::GetSize() const
1111 {
1112 // the window parameter is not used by GetCheckBoxSize() so it's
1113 // safe to pass NULL
1114 return wxRendererNative::Get().GetCheckBoxSize(NULL);
1115 }
1116
1117 // ---------------------------------------------------------
1118 // wxDataViewProgressRenderer
1119 // ---------------------------------------------------------
1120
1121 IMPLEMENT_ABSTRACT_CLASS(wxDataViewProgressRenderer, wxDataViewRenderer)
1122
1123 wxDataViewProgressRenderer::wxDataViewProgressRenderer( const wxString &label,
1124 const wxString &varianttype, wxDataViewCellMode mode, int align ) :
1125 wxDataViewRenderer( varianttype, mode, align )
1126 {
1127 m_label = label;
1128 m_value = 0;
1129 }
1130
1131 bool wxDataViewProgressRenderer::SetValue( const wxVariant &value )
1132 {
1133 m_value = (long) value;
1134
1135 if (m_value < 0) m_value = 0;
1136 if (m_value > 100) m_value = 100;
1137
1138 return true;
1139 }
1140
1141 bool wxDataViewProgressRenderer::GetValue( wxVariant &value ) const
1142 {
1143 value = (long) m_value;
1144 return true;
1145 }
1146
1147 bool
1148 wxDataViewProgressRenderer::Render(wxRect rect, wxDC *dc, int WXUNUSED(state))
1149 {
1150 // deflate the rect to leave a small border between bars in adjacent rows
1151 wxRect bar = rect.Deflate(0, 1);
1152
1153 dc->SetBrush( *wxTRANSPARENT_BRUSH );
1154 dc->SetPen( *wxBLACK_PEN );
1155 dc->DrawRectangle( bar );
1156
1157 bar.width = (int)(bar.width * m_value / 100.);
1158 dc->SetPen( *wxTRANSPARENT_PEN );
1159
1160 const wxDataViewItemAttr& attr = GetAttr();
1161 dc->SetBrush( attr.HasColour() ? wxBrush(attr.GetColour())
1162 : *wxBLUE_BRUSH );
1163 dc->DrawRectangle( bar );
1164
1165 return true;
1166 }
1167
1168 wxSize wxDataViewProgressRenderer::GetSize() const
1169 {
1170 return wxSize(40,12);
1171 }
1172
1173 // ---------------------------------------------------------
1174 // wxDataViewIconTextRenderer
1175 // ---------------------------------------------------------
1176
1177 IMPLEMENT_CLASS(wxDataViewIconTextRenderer, wxDataViewRenderer)
1178
1179 wxDataViewIconTextRenderer::wxDataViewIconTextRenderer(
1180 const wxString &varianttype, wxDataViewCellMode mode, int align ) :
1181 wxDataViewRenderer( varianttype, mode, align )
1182 {
1183 SetMode(mode);
1184 SetAlignment(align);
1185 }
1186
1187 bool wxDataViewIconTextRenderer::SetValue( const wxVariant &value )
1188 {
1189 m_value << value;
1190 return true;
1191 }
1192
1193 bool wxDataViewIconTextRenderer::GetValue( wxVariant& WXUNUSED(value) ) const
1194 {
1195 return false;
1196 }
1197
1198 bool wxDataViewIconTextRenderer::Render(wxRect rect, wxDC *dc, int state)
1199 {
1200 int xoffset = 0;
1201
1202 const wxIcon& icon = m_value.GetIcon();
1203 if ( icon.IsOk() )
1204 {
1205 dc->DrawIcon(icon, rect.x, rect.y + (rect.height - icon.GetHeight())/2);
1206 xoffset = icon.GetWidth()+4;
1207 }
1208
1209 RenderText(m_value.GetText(), xoffset, rect, dc, state);
1210
1211 return true;
1212 }
1213
1214 wxSize wxDataViewIconTextRenderer::GetSize() const
1215 {
1216 if (!m_value.GetText().empty())
1217 {
1218 wxSize size = GetTextExtent(m_value.GetText());
1219
1220 if (m_value.GetIcon().IsOk())
1221 size.x += m_value.GetIcon().GetWidth() + 4;
1222 return size;
1223 }
1224 return wxSize(80,20);
1225 }
1226
1227 wxWindow* wxDataViewIconTextRenderer::CreateEditorCtrl(wxWindow *parent, wxRect labelRect, const wxVariant& value)
1228 {
1229 wxDataViewIconText iconText;
1230 iconText << value;
1231
1232 wxString text = iconText.GetText();
1233
1234 // adjust the label rect to take the width of the icon into account
1235 if (iconText.GetIcon().IsOk())
1236 {
1237 int w = iconText.GetIcon().GetWidth() + 4;
1238 labelRect.x += w;
1239 labelRect.width -= w;
1240 }
1241
1242 wxTextCtrl* ctrl = new wxTextCtrl( parent, wxID_ANY, text,
1243 wxPoint(labelRect.x,labelRect.y),
1244 wxSize(labelRect.width,labelRect.height),
1245 wxTE_PROCESS_ENTER );
1246
1247 // select the text in the control an place the cursor at the end
1248 ctrl->SetInsertionPointEnd();
1249 ctrl->SelectAll();
1250
1251 return ctrl;
1252 }
1253
1254 bool wxDataViewIconTextRenderer::GetValueFromEditorCtrl( wxWindow *editor, wxVariant& value )
1255 {
1256 wxTextCtrl *text = (wxTextCtrl*) editor;
1257
1258 // The icon can't be edited so get its old value and reuse it.
1259 wxVariant valueOld;
1260 wxDataViewColumn* const col = GetOwner();
1261 GetView()->GetModel()->GetValue(valueOld, m_item, col->GetModelColumn());
1262
1263 wxDataViewIconText iconText;
1264 iconText << valueOld;
1265
1266 // But replace the text with the value entered by user.
1267 iconText.SetText(text->GetValue());
1268
1269 value << iconText;
1270 return true;
1271 }
1272
1273 //-----------------------------------------------------------------------------
1274 // wxDataViewDropTarget
1275 //-----------------------------------------------------------------------------
1276
1277 #if wxUSE_DRAG_AND_DROP
1278
1279 class wxBitmapCanvas: public wxWindow
1280 {
1281 public:
1282 wxBitmapCanvas( wxWindow *parent, const wxBitmap &bitmap, const wxSize &size ) :
1283 wxWindow( parent, wxID_ANY, wxPoint(0,0), size )
1284 {
1285 m_bitmap = bitmap;
1286 Connect( wxEVT_PAINT, wxPaintEventHandler(wxBitmapCanvas::OnPaint) );
1287 }
1288
1289 void OnPaint( wxPaintEvent &WXUNUSED(event) )
1290 {
1291 wxPaintDC dc(this);
1292 dc.DrawBitmap( m_bitmap, 0, 0);
1293 }
1294
1295 wxBitmap m_bitmap;
1296 };
1297
1298 class wxDataViewDropSource: public wxDropSource
1299 {
1300 public:
1301 wxDataViewDropSource( wxDataViewMainWindow *win, unsigned int row ) :
1302 wxDropSource( win )
1303 {
1304 m_win = win;
1305 m_row = row;
1306 m_hint = NULL;
1307 }
1308
1309 ~wxDataViewDropSource()
1310 {
1311 delete m_hint;
1312 }
1313
1314 virtual bool GiveFeedback( wxDragResult WXUNUSED(effect) )
1315 {
1316 wxPoint pos = wxGetMousePosition();
1317
1318 if (!m_hint)
1319 {
1320 int liney = m_win->GetLineStart( m_row );
1321 int linex = 0;
1322 m_win->GetOwner()->CalcUnscrolledPosition( 0, liney, NULL, &liney );
1323 m_win->ClientToScreen( &linex, &liney );
1324 m_dist_x = pos.x - linex;
1325 m_dist_y = pos.y - liney;
1326
1327 int indent = 0;
1328 wxBitmap ib = m_win->CreateItemBitmap( m_row, indent );
1329 m_dist_x -= indent;
1330 m_hint = new wxFrame( m_win->GetParent(), wxID_ANY, wxEmptyString,
1331 wxPoint(pos.x - m_dist_x, pos.y + 5 ),
1332 ib.GetSize(),
1333 wxFRAME_TOOL_WINDOW |
1334 wxFRAME_FLOAT_ON_PARENT |
1335 wxFRAME_NO_TASKBAR |
1336 wxNO_BORDER );
1337 new wxBitmapCanvas( m_hint, ib, ib.GetSize() );
1338 m_hint->Show();
1339 }
1340 else
1341 {
1342 m_hint->Move( pos.x - m_dist_x, pos.y + 5 );
1343 m_hint->SetTransparent( 128 );
1344 }
1345
1346 return false;
1347 }
1348
1349 wxDataViewMainWindow *m_win;
1350 unsigned int m_row;
1351 wxFrame *m_hint;
1352 int m_dist_x,m_dist_y;
1353 };
1354
1355
1356 class wxDataViewDropTarget: public wxDropTarget
1357 {
1358 public:
1359 wxDataViewDropTarget( wxDataObject *obj, wxDataViewMainWindow *win ) :
1360 wxDropTarget( obj )
1361 {
1362 m_win = win;
1363 }
1364
1365 virtual wxDragResult OnDragOver( wxCoord x, wxCoord y, wxDragResult def )
1366 {
1367 wxDataFormat format = GetMatchingPair();
1368 if (format == wxDF_INVALID)
1369 return wxDragNone;
1370 return m_win->OnDragOver( format, x, y, def);
1371 }
1372
1373 virtual bool OnDrop( wxCoord x, wxCoord y )
1374 {
1375 wxDataFormat format = GetMatchingPair();
1376 if (format == wxDF_INVALID)
1377 return false;
1378 return m_win->OnDrop( format, x, y );
1379 }
1380
1381 virtual wxDragResult OnData( wxCoord x, wxCoord y, wxDragResult def )
1382 {
1383 wxDataFormat format = GetMatchingPair();
1384 if (format == wxDF_INVALID)
1385 return wxDragNone;
1386 if (!GetData())
1387 return wxDragNone;
1388 return m_win->OnData( format, x, y, def );
1389 }
1390
1391 virtual void OnLeave()
1392 { m_win->OnLeave(); }
1393
1394 wxDataViewMainWindow *m_win;
1395 };
1396
1397 #endif // wxUSE_DRAG_AND_DROP
1398
1399 //-----------------------------------------------------------------------------
1400 // wxDataViewRenameTimer
1401 //-----------------------------------------------------------------------------
1402
1403 wxDataViewRenameTimer::wxDataViewRenameTimer( wxDataViewMainWindow *owner )
1404 {
1405 m_owner = owner;
1406 }
1407
1408 void wxDataViewRenameTimer::Notify()
1409 {
1410 m_owner->OnRenameTimer();
1411 }
1412
1413 //-----------------------------------------------------------------------------
1414 // wxDataViewMainWindow
1415 //-----------------------------------------------------------------------------
1416
1417 // The tree building helper, declared firstly
1418 static void BuildTreeHelper( const wxDataViewModel * model, const wxDataViewItem & item,
1419 wxDataViewTreeNode * node);
1420
1421 int LINKAGEMODE wxDataViewSelectionCmp( unsigned int row1, unsigned int row2 )
1422 {
1423 if (row1 > row2) return 1;
1424 if (row1 == row2) return 0;
1425 return -1;
1426 }
1427
1428 IMPLEMENT_ABSTRACT_CLASS(wxDataViewMainWindow, wxWindow)
1429
1430 BEGIN_EVENT_TABLE(wxDataViewMainWindow,wxWindow)
1431 EVT_PAINT (wxDataViewMainWindow::OnPaint)
1432 EVT_MOUSE_EVENTS (wxDataViewMainWindow::OnMouse)
1433 EVT_SET_FOCUS (wxDataViewMainWindow::OnSetFocus)
1434 EVT_KILL_FOCUS (wxDataViewMainWindow::OnKillFocus)
1435 EVT_CHAR_HOOK (wxDataViewMainWindow::OnCharHook)
1436 EVT_CHAR (wxDataViewMainWindow::OnChar)
1437 END_EVENT_TABLE()
1438
1439 wxDataViewMainWindow::wxDataViewMainWindow( wxDataViewCtrl *parent, wxWindowID id,
1440 const wxPoint &pos, const wxSize &size, const wxString &name ) :
1441 wxWindow( parent, id, pos, size, wxWANTS_CHARS|wxBORDER_NONE, name ),
1442 m_selection( wxDataViewSelectionCmp )
1443
1444 {
1445 SetOwner( parent );
1446
1447 m_editorRenderer = NULL;
1448
1449 m_lastOnSame = false;
1450 m_renameTimer = new wxDataViewRenameTimer( this );
1451
1452 // TODO: user better initial values/nothing selected
1453 m_currentCol = NULL;
1454 m_currentColSetByKeyboard = false;
1455 m_useCellFocus = false;
1456 m_currentRow = (unsigned)-1;
1457 m_lineHeight = GetDefaultRowHeight();
1458
1459 #if wxUSE_DRAG_AND_DROP
1460 m_dragCount = 0;
1461 m_dragStart = wxPoint(0,0);
1462
1463 m_dragEnabled = false;
1464 m_dropEnabled = false;
1465 m_dropHint = false;
1466 m_dropHintLine = (unsigned int) -1;
1467 #endif // wxUSE_DRAG_AND_DROP
1468
1469 m_lineLastClicked = (unsigned int) -1;
1470 m_lineBeforeLastClicked = (unsigned int) -1;
1471 m_lineSelectSingleOnUp = (unsigned int) -1;
1472
1473 m_hasFocus = false;
1474
1475 SetBackgroundColour( *wxWHITE );
1476
1477 SetBackgroundStyle(wxBG_STYLE_CUSTOM);
1478
1479 m_penRule = wxPen(GetRuleColour());
1480
1481 // compose a pen whichcan draw black lines
1482 // TODO: maybe there is something system colour to use
1483 m_penExpander = wxPen(wxColour(0,0,0));
1484
1485 m_root = wxDataViewTreeNode::CreateRootNode();
1486
1487 // Make m_count = -1 will cause the class recaculate the real displaying number of rows.
1488 m_count = -1;
1489 m_underMouse = NULL;
1490 UpdateDisplay();
1491 }
1492
1493 wxDataViewMainWindow::~wxDataViewMainWindow()
1494 {
1495 DestroyTree();
1496 delete m_renameTimer;
1497 }
1498
1499
1500 int wxDataViewMainWindow::GetDefaultRowHeight() const
1501 {
1502 #ifdef __WXMSW__
1503 // We would like to use the same line height that Explorer uses. This is
1504 // different from standard ListView control since Vista.
1505 if ( wxGetWinVersion() >= wxWinVersion_Vista )
1506 return wxMax(16, GetCharHeight()) + 6; // 16 = mini icon height
1507 else
1508 #endif // __WXMSW__
1509 return wxMax(16, GetCharHeight()) + 1; // 16 = mini icon height
1510 }
1511
1512
1513
1514 #if wxUSE_DRAG_AND_DROP
1515 bool wxDataViewMainWindow::EnableDragSource( const wxDataFormat &format )
1516 {
1517 m_dragFormat = format;
1518 m_dragEnabled = format != wxDF_INVALID;
1519
1520 return true;
1521 }
1522
1523 bool wxDataViewMainWindow::EnableDropTarget( const wxDataFormat &format )
1524 {
1525 m_dropFormat = format;
1526 m_dropEnabled = format != wxDF_INVALID;
1527
1528 if (m_dropEnabled)
1529 SetDropTarget( new wxDataViewDropTarget( new wxCustomDataObject( format ), this ) );
1530
1531 return true;
1532 }
1533
1534 void wxDataViewMainWindow::RemoveDropHint()
1535 {
1536 if (m_dropHint)
1537 {
1538 m_dropHint = false;
1539 RefreshRow( m_dropHintLine );
1540 m_dropHintLine = (unsigned int) -1;
1541 }
1542 }
1543
1544 wxDragResult wxDataViewMainWindow::OnDragOver( wxDataFormat format, wxCoord x,
1545 wxCoord y, wxDragResult def )
1546 {
1547 int xx = x;
1548 int yy = y;
1549 m_owner->CalcUnscrolledPosition( xx, yy, &xx, &yy );
1550 unsigned int row = GetLineAt( yy );
1551
1552 if ((row >= GetRowCount()) || (xx > GetEndOfLastCol()))
1553 {
1554 RemoveDropHint();
1555 return wxDragNone;
1556 }
1557
1558 wxDataViewItem item = GetItemByRow( row );
1559
1560 wxDataViewModel *model = GetModel();
1561
1562 wxDataViewEvent event( wxEVT_COMMAND_DATAVIEW_ITEM_DROP_POSSIBLE, m_owner->GetId() );
1563 event.SetEventObject( m_owner );
1564 event.SetItem( item );
1565 event.SetModel( model );
1566 event.SetDataFormat( format );
1567 event.SetDropEffect( def );
1568 if (!m_owner->HandleWindowEvent( event ))
1569 {
1570 RemoveDropHint();
1571 return wxDragNone;
1572 }
1573
1574 if (!event.IsAllowed())
1575 {
1576 RemoveDropHint();
1577 return wxDragNone;
1578 }
1579
1580
1581 if (m_dropHint && (row != m_dropHintLine))
1582 RefreshRow( m_dropHintLine );
1583 m_dropHint = true;
1584 m_dropHintLine = row;
1585 RefreshRow( row );
1586
1587 return def;
1588 }
1589
1590 bool wxDataViewMainWindow::OnDrop( wxDataFormat format, wxCoord x, wxCoord y )
1591 {
1592 RemoveDropHint();
1593
1594 int xx = x;
1595 int yy = y;
1596 m_owner->CalcUnscrolledPosition( xx, yy, &xx, &yy );
1597 unsigned int row = GetLineAt( yy );
1598
1599 if ((row >= GetRowCount()) || (xx > GetEndOfLastCol()))
1600 return false;
1601
1602 wxDataViewItem item = GetItemByRow( row );
1603
1604 wxDataViewModel *model = GetModel();
1605
1606 wxDataViewEvent event( wxEVT_COMMAND_DATAVIEW_ITEM_DROP_POSSIBLE, m_owner->GetId() );
1607 event.SetEventObject( m_owner );
1608 event.SetItem( item );
1609 event.SetModel( model );
1610 event.SetDataFormat( format );
1611 if (!m_owner->HandleWindowEvent( event ))
1612 return false;
1613
1614 if (!event.IsAllowed())
1615 return false;
1616
1617 return true;
1618 }
1619
1620 wxDragResult wxDataViewMainWindow::OnData( wxDataFormat format, wxCoord x, wxCoord y,
1621 wxDragResult def )
1622 {
1623 int xx = x;
1624 int yy = y;
1625 m_owner->CalcUnscrolledPosition( xx, yy, &xx, &yy );
1626 unsigned int row = GetLineAt( yy );
1627
1628 if ((row >= GetRowCount()) || (xx > GetEndOfLastCol()))
1629 return wxDragNone;
1630
1631 wxDataViewItem item = GetItemByRow( row );
1632
1633 wxDataViewModel *model = GetModel();
1634
1635 wxCustomDataObject *obj = (wxCustomDataObject *) GetDropTarget()->GetDataObject();
1636
1637 wxDataViewEvent event( wxEVT_COMMAND_DATAVIEW_ITEM_DROP, m_owner->GetId() );
1638 event.SetEventObject( m_owner );
1639 event.SetItem( item );
1640 event.SetModel( model );
1641 event.SetDataFormat( format );
1642 event.SetDataSize( obj->GetSize() );
1643 event.SetDataBuffer( obj->GetData() );
1644 event.SetDropEffect( def );
1645 if (!m_owner->HandleWindowEvent( event ))
1646 return wxDragNone;
1647
1648 if (!event.IsAllowed())
1649 return wxDragNone;
1650
1651 return def;
1652 }
1653
1654 void wxDataViewMainWindow::OnLeave()
1655 {
1656 RemoveDropHint();
1657 }
1658
1659 wxBitmap wxDataViewMainWindow::CreateItemBitmap( unsigned int row, int &indent )
1660 {
1661 int height = GetLineHeight( row );
1662 int width = 0;
1663 unsigned int cols = GetOwner()->GetColumnCount();
1664 unsigned int col;
1665 for (col = 0; col < cols; col++)
1666 {
1667 wxDataViewColumn *column = GetOwner()->GetColumnAt(col);
1668 if (column->IsHidden())
1669 continue; // skip it!
1670 width += column->GetWidth();
1671 }
1672
1673 indent = 0;
1674 if (!IsList())
1675 {
1676 wxDataViewTreeNode *node = GetTreeNodeByRow(row);
1677 indent = GetOwner()->GetIndent() * node->GetIndentLevel();
1678 indent = indent + m_lineHeight;
1679 // try to use the m_lineHeight as the expander space
1680 }
1681 width -= indent;
1682
1683 wxBitmap bitmap( width, height );
1684 wxMemoryDC dc( bitmap );
1685 dc.SetFont( GetFont() );
1686 dc.SetPen( *wxBLACK_PEN );
1687 dc.SetBrush( *wxWHITE_BRUSH );
1688 dc.DrawRectangle( 0,0,width,height );
1689
1690 wxDataViewModel *model = m_owner->GetModel();
1691
1692 wxDataViewColumn * const
1693 expander = GetExpanderColumnOrFirstOne(GetOwner());
1694
1695 int x = 0;
1696 for (col = 0; col < cols; col++)
1697 {
1698 wxDataViewColumn *column = GetOwner()->GetColumnAt( col );
1699 wxDataViewRenderer *cell = column->GetRenderer();
1700
1701 if (column->IsHidden())
1702 continue; // skip it!
1703
1704 width = column->GetWidth();
1705
1706 if (column == expander)
1707 width -= indent;
1708
1709 wxDataViewItem item = GetItemByRow( row );
1710 cell->PrepareForItem(model, item, column->GetModelColumn());
1711
1712 wxRect item_rect(x, 0, width, height);
1713 item_rect.Deflate(PADDING_RIGHTLEFT, 0);
1714
1715 // dc.SetClippingRegion( item_rect );
1716 cell->WXCallRender(item_rect, &dc, 0);
1717 // dc.DestroyClippingRegion();
1718
1719 x += width;
1720 }
1721
1722 return bitmap;
1723 }
1724
1725 #endif // wxUSE_DRAG_AND_DROP
1726
1727
1728 // Draw focus rect for individual cell. Unlike native focus rect, we render
1729 // this in foreground text color (typically white) to enhance contrast and
1730 // make it visible.
1731 static void DrawSelectedCellFocusRect(wxDC& dc, const wxRect& rect)
1732 {
1733 // (This code is based on wxRendererGeneric::DrawFocusRect and modified.)
1734
1735 // draw the pixels manually because the "dots" in wxPen with wxDOT style
1736 // may be short traits and not really dots
1737 //
1738 // note that to behave in the same manner as DrawRect(), we must exclude
1739 // the bottom and right borders from the rectangle
1740 wxCoord x1 = rect.GetLeft(),
1741 y1 = rect.GetTop(),
1742 x2 = rect.GetRight(),
1743 y2 = rect.GetBottom();
1744
1745 wxDCPenChanger pen(dc, wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT));
1746
1747 wxCoord z;
1748 for ( z = x1 + 1; z < x2; z += 2 )
1749 dc.DrawPoint(z, rect.GetTop());
1750
1751 wxCoord shift = z == x2 ? 0 : 1;
1752 for ( z = y1 + shift; z < y2; z += 2 )
1753 dc.DrawPoint(x2, z);
1754
1755 shift = z == y2 ? 0 : 1;
1756 for ( z = x2 - shift; z > x1; z -= 2 )
1757 dc.DrawPoint(z, y2);
1758
1759 shift = z == x1 ? 0 : 1;
1760 for ( z = y2 - shift; z > y1; z -= 2 )
1761 dc.DrawPoint(x1, z);
1762 }
1763
1764
1765 void wxDataViewMainWindow::OnPaint( wxPaintEvent &WXUNUSED(event) )
1766 {
1767 wxDataViewModel *model = GetModel();
1768 wxAutoBufferedPaintDC dc( this );
1769
1770 dc.SetBrush(GetOwner()->GetBackgroundColour());
1771 dc.SetPen( *wxTRANSPARENT_PEN );
1772 dc.DrawRectangle(GetClientSize());
1773
1774 if ( IsEmpty() )
1775 {
1776 // No items to draw.
1777 return;
1778 }
1779
1780 // prepare the DC
1781 GetOwner()->PrepareDC( dc );
1782 dc.SetFont( GetFont() );
1783
1784 wxRect update = GetUpdateRegion().GetBox();
1785 m_owner->CalcUnscrolledPosition( update.x, update.y, &update.x, &update.y );
1786
1787 // compute which items needs to be redrawn
1788 unsigned int item_start = GetLineAt( wxMax(0,update.y) );
1789 unsigned int item_count =
1790 wxMin( (int)( GetLineAt( wxMax(0,update.y+update.height) ) - item_start + 1),
1791 (int)(GetRowCount( ) - item_start));
1792 unsigned int item_last = item_start + item_count;
1793
1794 // Send the event to wxDataViewCtrl itself.
1795 wxWindow * const parent = GetParent();
1796 wxDataViewEvent cache_event(wxEVT_COMMAND_DATAVIEW_CACHE_HINT, parent->GetId());
1797 cache_event.SetEventObject(parent);
1798 cache_event.SetCache(item_start, item_last - 1);
1799 parent->ProcessWindowEvent(cache_event);
1800
1801 // compute which columns needs to be redrawn
1802 unsigned int cols = GetOwner()->GetColumnCount();
1803 if ( !cols )
1804 {
1805 // we assume that we have at least one column below and painting an
1806 // empty control is unnecessary anyhow
1807 return;
1808 }
1809
1810 unsigned int col_start = 0;
1811 unsigned int x_start;
1812 for (x_start = 0; col_start < cols; col_start++)
1813 {
1814 wxDataViewColumn *col = GetOwner()->GetColumnAt(col_start);
1815 if (col->IsHidden())
1816 continue; // skip it!
1817
1818 unsigned int w = col->GetWidth();
1819 if (x_start+w >= (unsigned int)update.x)
1820 break;
1821
1822 x_start += w;
1823 }
1824
1825 unsigned int col_last = col_start;
1826 unsigned int x_last = x_start;
1827 for (; col_last < cols; col_last++)
1828 {
1829 wxDataViewColumn *col = GetOwner()->GetColumnAt(col_last);
1830 if (col->IsHidden())
1831 continue; // skip it!
1832
1833 if (x_last > (unsigned int)update.GetRight())
1834 break;
1835
1836 x_last += col->GetWidth();
1837 }
1838
1839 // Draw background of alternate rows specially if required
1840 if ( m_owner->HasFlag(wxDV_ROW_LINES) )
1841 {
1842 wxColour altRowColour = m_owner->m_alternateRowColour;
1843 if ( !altRowColour.IsOk() )
1844 {
1845 // Determine the alternate rows colour automatically from the
1846 // background colour.
1847 const wxColour bgColour = m_owner->GetBackgroundColour();
1848
1849 // Depending on the background, alternate row color
1850 // will be 3% more dark or 50% brighter.
1851 int alpha = bgColour.GetRGB() > 0x808080 ? 97 : 150;
1852 altRowColour = bgColour.ChangeLightness(alpha);
1853 }
1854
1855 dc.SetPen(*wxTRANSPARENT_PEN);
1856 dc.SetBrush(wxBrush(altRowColour));
1857
1858 for (unsigned int item = item_start; item < item_last; item++)
1859 {
1860 if ( item % 2 )
1861 {
1862 dc.DrawRectangle(x_start,
1863 GetLineStart(item),
1864 GetClientSize().GetWidth(),
1865 GetLineHeight(item));
1866 }
1867 }
1868 }
1869
1870 // Draw horizontal rules if required
1871 if ( m_owner->HasFlag(wxDV_HORIZ_RULES) )
1872 {
1873 dc.SetPen(m_penRule);
1874 dc.SetBrush(*wxTRANSPARENT_BRUSH);
1875
1876 for (unsigned int i = item_start; i <= item_last; i++)
1877 {
1878 int y = GetLineStart( i );
1879 dc.DrawLine(x_start, y, x_last, y);
1880 }
1881 }
1882
1883 // Draw vertical rules if required
1884 if ( m_owner->HasFlag(wxDV_VERT_RULES) )
1885 {
1886 dc.SetPen(m_penRule);
1887 dc.SetBrush(*wxTRANSPARENT_BRUSH);
1888
1889 // NB: Vertical rules are drawn in the last pixel of a column so that
1890 // they align perfectly with native MSW wxHeaderCtrl as well as for
1891 // consistency with MSW native list control. There's no vertical
1892 // rule at the most-left side of the control.
1893
1894 int x = x_start - 1;
1895 for (unsigned int i = col_start; i < col_last; i++)
1896 {
1897 wxDataViewColumn *col = GetOwner()->GetColumnAt(i);
1898 if (col->IsHidden())
1899 continue; // skip it
1900
1901 x += col->GetWidth();
1902
1903 dc.DrawLine(x, GetLineStart( item_start ),
1904 x, GetLineStart( item_last ) );
1905 }
1906 }
1907
1908 // redraw the background for the items which are selected/current
1909 for (unsigned int item = item_start; item < item_last; item++)
1910 {
1911 bool selected = m_selection.Index( item ) != wxNOT_FOUND;
1912
1913 if (selected || item == m_currentRow)
1914 {
1915 wxRect rect( x_start, GetLineStart( item ),
1916 x_last - x_start, GetLineHeight( item ) );
1917
1918 // draw selection and whole-item focus:
1919 if ( selected )
1920 {
1921 int flags = wxCONTROL_SELECTED;
1922 if (m_hasFocus)
1923 flags |= wxCONTROL_FOCUSED;
1924
1925 wxRendererNative::Get().DrawItemSelectionRect
1926 (
1927 this,
1928 dc,
1929 rect,
1930 flags
1931 );
1932 }
1933
1934 // draw keyboard focus rect if applicable
1935 if ( item == m_currentRow && m_hasFocus )
1936 {
1937 bool renderColumnFocus = false;
1938
1939 if ( m_useCellFocus && m_currentCol && m_currentColSetByKeyboard )
1940 {
1941 renderColumnFocus = true;
1942
1943 // If this is container node without columns, render full-row focus:
1944 if ( !IsList() )
1945 {
1946 wxDataViewTreeNode *node = GetTreeNodeByRow(item);
1947 if ( node->HasChildren() && !model->HasContainerColumns(node->GetItem()) )
1948 renderColumnFocus = false;
1949 }
1950 }
1951
1952 if ( renderColumnFocus )
1953 {
1954 for ( unsigned int i = col_start; i < col_last; i++ )
1955 {
1956 wxDataViewColumn *col = GetOwner()->GetColumnAt(i);
1957 if ( col->IsHidden() )
1958 continue;
1959
1960 rect.width = col->GetWidth();
1961
1962 if ( col == m_currentCol )
1963 {
1964 // make the rect more visible by adding a small
1965 // margin around it:
1966 rect.Deflate(1, 1);
1967
1968 if ( selected )
1969 {
1970 // DrawFocusRect() uses XOR and is all but
1971 // invisible against dark-blue background. Use
1972 // the same color used for selected text.
1973 DrawSelectedCellFocusRect(dc, rect);
1974 }
1975 else
1976 {
1977 wxRendererNative::Get().DrawFocusRect
1978 (
1979 this,
1980 dc,
1981 rect,
1982 0
1983 );
1984 }
1985 break;
1986 }
1987
1988 rect.x += rect.width;
1989 }
1990 }
1991 else
1992 {
1993 // render focus rectangle for the whole row
1994 wxRendererNative::Get().DrawFocusRect
1995 (
1996 this,
1997 dc,
1998 rect,
1999 selected ? (int)wxCONTROL_SELECTED : 0
2000 );
2001 }
2002 }
2003 }
2004 }
2005
2006 #if wxUSE_DRAG_AND_DROP
2007 if (m_dropHint)
2008 {
2009 wxRect rect( x_start, GetLineStart( m_dropHintLine ),
2010 x_last - x_start, GetLineHeight( m_dropHintLine ) );
2011 dc.SetPen( *wxBLACK_PEN );
2012 dc.SetBrush( *wxTRANSPARENT_BRUSH );
2013 dc.DrawRectangle( rect );
2014 }
2015 #endif // wxUSE_DRAG_AND_DROP
2016
2017 wxDataViewColumn * const
2018 expander = GetExpanderColumnOrFirstOne(GetOwner());
2019
2020 // redraw all cells for all rows which must be repainted and all columns
2021 wxRect cell_rect;
2022 cell_rect.x = x_start;
2023 for (unsigned int i = col_start; i < col_last; i++)
2024 {
2025 wxDataViewColumn *col = GetOwner()->GetColumnAt( i );
2026 wxDataViewRenderer *cell = col->GetRenderer();
2027 cell_rect.width = col->GetWidth();
2028
2029 if ( col->IsHidden() || cell_rect.width <= 0 )
2030 continue; // skip it!
2031
2032 for (unsigned int item = item_start; item < item_last; item++)
2033 {
2034 // get the cell value and set it into the renderer
2035 wxDataViewTreeNode *node = NULL;
2036 wxDataViewItem dataitem;
2037
2038 if (!IsVirtualList())
2039 {
2040 node = GetTreeNodeByRow(item);
2041 if( node == NULL )
2042 continue;
2043
2044 dataitem = node->GetItem();
2045
2046 // Skip all columns of "container" rows except the expander
2047 // column itself unless HasContainerColumns() overrides this.
2048 if ( col != expander &&
2049 model->IsContainer(dataitem) &&
2050 !model->HasContainerColumns(dataitem) )
2051 continue;
2052 }
2053 else
2054 {
2055 dataitem = wxDataViewItem( wxUIntToPtr(item+1) );
2056 }
2057
2058 cell->PrepareForItem(model, dataitem, col->GetModelColumn());
2059
2060 // update cell_rect
2061 cell_rect.y = GetLineStart( item );
2062 cell_rect.height = GetLineHeight( item );
2063
2064 // draw the background
2065 bool selected = m_selection.Index( item ) != wxNOT_FOUND;
2066 if ( !selected )
2067 DrawCellBackground( cell, dc, cell_rect );
2068
2069 // deal with the expander
2070 int indent = 0;
2071 if ((!IsList()) && (col == expander))
2072 {
2073 // Calculate the indent first
2074 indent = GetOwner()->GetIndent() * node->GetIndentLevel();
2075
2076 // we reserve m_lineHeight of horizontal space for the expander
2077 // but leave EXPANDER_MARGIN around the expander itself
2078 int exp_x = cell_rect.x + indent + EXPANDER_MARGIN;
2079
2080 indent += m_lineHeight;
2081
2082 // draw expander if needed and visible
2083 if ( node->HasChildren() && exp_x < cell_rect.GetRight() )
2084 {
2085 dc.SetPen( m_penExpander );
2086 dc.SetBrush( wxNullBrush );
2087
2088 int exp_size = m_lineHeight - 2*EXPANDER_MARGIN;
2089 int exp_y = cell_rect.y + (cell_rect.height - exp_size)/2
2090 + EXPANDER_MARGIN - EXPANDER_OFFSET;
2091
2092 const wxRect rect(exp_x, exp_y, exp_size, exp_size);
2093
2094 int flag = 0;
2095 if ( m_underMouse == node )
2096 flag |= wxCONTROL_CURRENT;
2097 if ( node->IsOpen() )
2098 flag |= wxCONTROL_EXPANDED;
2099
2100 // ensure that we don't overflow the cell (which might
2101 // happen if the column is very narrow)
2102 wxDCClipper clip(dc, cell_rect);
2103
2104 wxRendererNative::Get().DrawTreeItemButton( this, dc, rect, flag);
2105 }
2106
2107 // force the expander column to left-center align
2108 cell->SetAlignment( wxALIGN_CENTER_VERTICAL );
2109 }
2110
2111 wxRect item_rect = cell_rect;
2112 item_rect.Deflate(PADDING_RIGHTLEFT, 0);
2113
2114 // account for the tree indent (harmless if we're not indented)
2115 item_rect.x += indent;
2116 item_rect.width -= indent;
2117
2118 if ( item_rect.width <= 0 )
2119 continue;
2120
2121 int state = 0;
2122 if (m_hasFocus && selected)
2123 state |= wxDATAVIEW_CELL_SELECTED;
2124
2125 // TODO: it would be much more efficient to create a clipping
2126 // region for the entire column being rendered (in the OnPaint
2127 // of wxDataViewMainWindow) instead of a single clip region for
2128 // each cell. However it would mean that each renderer should
2129 // respect the given wxRect's top & bottom coords, eventually
2130 // violating only the left & right coords - however the user can
2131 // make its own renderer and thus we cannot be sure of that.
2132 wxDCClipper clip(dc, item_rect);
2133
2134 cell->WXCallRender(item_rect, &dc, state);
2135 }
2136
2137 cell_rect.x += cell_rect.width;
2138 }
2139 }
2140
2141
2142 void wxDataViewMainWindow::DrawCellBackground( wxDataViewRenderer* cell, wxDC& dc, const wxRect& rect )
2143 {
2144 wxRect rectBg( rect );
2145
2146 // don't overlap the horizontal rules
2147 if ( m_owner->HasFlag(wxDV_HORIZ_RULES) )
2148 {
2149 rectBg.x++;
2150 rectBg.width--;
2151 }
2152
2153 // don't overlap the vertical rules
2154 if ( m_owner->HasFlag(wxDV_VERT_RULES) )
2155 {
2156 rectBg.y++;
2157 rectBg.height--;
2158 }
2159
2160 cell->RenderBackground(&dc, rectBg);
2161 }
2162
2163 void wxDataViewMainWindow::OnRenameTimer()
2164 {
2165 // We have to call this here because changes may just have
2166 // been made and no screen update taken place.
2167 if ( m_dirty )
2168 {
2169 // TODO: use wxTheApp->SafeYieldFor(NULL, wxEVT_CATEGORY_UI) instead
2170 // (needs to be tested!)
2171 wxSafeYield();
2172 }
2173
2174 wxDataViewItem item = GetItemByRow( m_currentRow );
2175
2176 StartEditing( item, m_currentCol );
2177 }
2178
2179 void
2180 wxDataViewMainWindow::StartEditing(const wxDataViewItem& item,
2181 const wxDataViewColumn* col)
2182 {
2183 wxDataViewRenderer* renderer = col->GetRenderer();
2184 if ( !IsCellEditableInMode(item, col, wxDATAVIEW_CELL_EDITABLE) )
2185 return;
2186
2187 const wxRect itemRect = GetItemRect(item, col);
2188 if ( renderer->StartEditing(item, itemRect) )
2189 {
2190 // Save the renderer to be able to finish/cancel editing it later and
2191 // save the control to be able to detect if we're still editing it.
2192 m_editorRenderer = renderer;
2193 m_editorCtrl = renderer->GetEditorCtrl();
2194 }
2195 }
2196
2197 //-----------------------------------------------------------------------------
2198 // Helper class for do operation on the tree node
2199 //-----------------------------------------------------------------------------
2200 class DoJob
2201 {
2202 public:
2203 DoJob() { }
2204 virtual ~DoJob() { }
2205
2206 // The return value control how the tree-walker tranverse the tree
2207 enum
2208 {
2209 DONE, // Job done, stop traversing and return
2210 SKIP_SUBTREE, // Ignore the current node's subtree and continue
2211 CONTINUE // Job not done, continue
2212 };
2213
2214 virtual int operator() ( wxDataViewTreeNode * node ) = 0;
2215 };
2216
2217 bool Walker( wxDataViewTreeNode * node, DoJob & func )
2218 {
2219 wxCHECK_MSG( node, false, "can't walk NULL node" );
2220
2221 switch( func( node ) )
2222 {
2223 case DoJob::DONE:
2224 return true;
2225 case DoJob::SKIP_SUBTREE:
2226 return false;
2227 case DoJob::CONTINUE:
2228 break;
2229 }
2230
2231 if ( node->HasChildren() )
2232 {
2233 const wxDataViewTreeNodes& nodes = node->GetChildNodes();
2234
2235 for ( wxDataViewTreeNodes::const_iterator i = nodes.begin();
2236 i != nodes.end();
2237 ++i )
2238 {
2239 if ( Walker(*i, func) )
2240 return true;
2241 }
2242 }
2243
2244 return false;
2245 }
2246
2247 bool wxDataViewMainWindow::ItemAdded(const wxDataViewItem & parent, const wxDataViewItem & item)
2248 {
2249 if (IsVirtualList())
2250 {
2251 wxDataViewVirtualListModel *list_model =
2252 (wxDataViewVirtualListModel*) GetModel();
2253 m_count = list_model->GetCount();
2254 }
2255 else
2256 {
2257 SortPrepare();
2258
2259 wxDataViewTreeNode *parentNode = FindNode(parent);
2260
2261 if ( !parentNode )
2262 return false;
2263
2264 wxDataViewItemArray modelSiblings;
2265 GetModel()->GetChildren(parent, modelSiblings);
2266 const int modelSiblingsSize = modelSiblings.size();
2267
2268 int posInModel = modelSiblings.Index(item, /*fromEnd=*/true);
2269 wxCHECK_MSG( posInModel != wxNOT_FOUND, false, "adding non-existent item?" );
2270
2271 wxDataViewTreeNode *itemNode = new wxDataViewTreeNode(parentNode, item);
2272 itemNode->SetHasChildren(GetModel()->IsContainer(item));
2273
2274 parentNode->SetHasChildren(true);
2275
2276 const wxDataViewTreeNodes& nodeSiblings = parentNode->GetChildNodes();
2277 const int nodeSiblingsSize = nodeSiblings.size();
2278
2279 int nodePos = 0;
2280
2281 if ( posInModel == modelSiblingsSize - 1 )
2282 {
2283 nodePos = nodeSiblingsSize;
2284 }
2285 else if ( modelSiblingsSize == nodeSiblingsSize + 1 )
2286 {
2287 // This is the simple case when our node tree already matches the
2288 // model and only this one item is missing.
2289 nodePos = posInModel;
2290 }
2291 else
2292 {
2293 // It's possible that a larger discrepancy between the model and
2294 // our realization exists. This can happen e.g. when adding a bunch
2295 // of items to the model and then calling ItemsAdded() just once
2296 // afterwards. In this case, we must find the right position by
2297 // looking at sibling items.
2298
2299 // append to the end if we won't find a better position:
2300 nodePos = nodeSiblingsSize;
2301
2302 for ( int nextItemPos = posInModel + 1;
2303 nextItemPos < modelSiblingsSize;
2304 nextItemPos++ )
2305 {
2306 int nextNodePos = parentNode->FindChildByItem(modelSiblings[nextItemPos]);
2307 if ( nextNodePos != wxNOT_FOUND )
2308 {
2309 nodePos = nextNodePos;
2310 break;
2311 }
2312 }
2313 }
2314
2315 parentNode->ChangeSubTreeCount(+1);
2316 parentNode->InsertChild(itemNode, nodePos);
2317
2318 m_count = -1;
2319 }
2320
2321 GetOwner()->InvalidateColBestWidths();
2322 UpdateDisplay();
2323
2324 return true;
2325 }
2326
2327 bool wxDataViewMainWindow::ItemDeleted(const wxDataViewItem& parent,
2328 const wxDataViewItem& item)
2329 {
2330 if (IsVirtualList())
2331 {
2332 wxDataViewVirtualListModel *list_model =
2333 (wxDataViewVirtualListModel*) GetModel();
2334 m_count = list_model->GetCount();
2335
2336 if ( !m_selection.empty() )
2337 {
2338 const int row = GetRowByItem(item);
2339
2340 int rowIndexInSelection = wxNOT_FOUND;
2341
2342 const size_t selCount = m_selection.size();
2343 for ( size_t i = 0; i < selCount; i++ )
2344 {
2345 if ( m_selection[i] == (unsigned)row )
2346 rowIndexInSelection = i;
2347 else if ( m_selection[i] > (unsigned)row )
2348 m_selection[i]--;
2349 }
2350
2351 if ( rowIndexInSelection != wxNOT_FOUND )
2352 m_selection.RemoveAt(rowIndexInSelection);
2353 }
2354
2355 }
2356 else // general case
2357 {
2358 wxDataViewTreeNode *parentNode = FindNode(parent);
2359
2360 // Notice that it is possible that the item being deleted is not in the
2361 // tree at all, for example we could be deleting a never shown (because
2362 // collapsed) item in a tree model. So it's not an error if we don't know
2363 // about this item, just return without doing anything then.
2364 if ( !parentNode )
2365 return true;
2366
2367 wxCHECK_MSG( parentNode->HasChildren(), false, "parent node doesn't have children?" );
2368 const wxDataViewTreeNodes& parentsChildren = parentNode->GetChildNodes();
2369
2370 // We can't use FindNode() to find 'item', because it was already
2371 // removed from the model by the time ItemDeleted() is called, so we
2372 // have to do it manually. We keep track of its position as well for
2373 // later use.
2374 int itemPosInNode = 0;
2375 wxDataViewTreeNode *itemNode = NULL;
2376 for ( wxDataViewTreeNodes::const_iterator i = parentsChildren.begin();
2377 i != parentsChildren.end();
2378 ++i, ++itemPosInNode )
2379 {
2380 if( (*i)->GetItem() == item )
2381 {
2382 itemNode = *i;
2383 break;
2384 }
2385 }
2386
2387 // If the parent wasn't expanded, it's possible that we didn't have a
2388 // node corresponding to 'item' and so there's nothing left to do.
2389 if ( !itemNode )
2390 {
2391 // If this was the last child to be removed, it's possible the parent
2392 // node became a leaf. Let's ask the model about it.
2393 if ( parentNode->GetChildNodes().empty() )
2394 parentNode->SetHasChildren(GetModel()->IsContainer(parent));
2395
2396 return true;
2397 }
2398
2399 // Delete the item from wxDataViewTreeNode representation:
2400 const int itemsDeleted = 1 + itemNode->GetSubTreeCount();
2401
2402 parentNode->RemoveChild(itemNode);
2403 delete itemNode;
2404 parentNode->ChangeSubTreeCount(-itemsDeleted);
2405
2406 // Make the row number invalid and get a new valid one when user call GetRowCount
2407 m_count = -1;
2408
2409 // If this was the last child to be removed, it's possible the parent
2410 // node became a leaf. Let's ask the model about it.
2411 if ( parentNode->GetChildNodes().empty() )
2412 {
2413 bool isContainer = GetModel()->IsContainer(parent);
2414 parentNode->SetHasChildren(isContainer);
2415 if ( isContainer )
2416 {
2417 // If it's still a container, make sure we show "+" icon for it
2418 // and not "-" one as there is nothing to collapse any more.
2419 if ( parentNode->IsOpen() )
2420 parentNode->ToggleOpen();
2421 }
2422 }
2423
2424 // Update selection by removing 'item' and its entire children tree from the selection.
2425 if ( !m_selection.empty() )
2426 {
2427 // we can't call GetRowByItem() on 'item', as it's already deleted, so compute it from
2428 // the parent ('parentNode') and position in its list of children
2429 int itemRow;
2430 if ( itemPosInNode == 0 )
2431 {
2432 // 1st child, row number is that of the parent parentNode + 1
2433 itemRow = GetRowByItem(parentNode->GetItem()) + 1;
2434 }
2435 else
2436 {
2437 // row number is that of the sibling above 'item' + its subtree if any + 1
2438 const wxDataViewTreeNode *siblingNode = parentNode->GetChildNodes()[itemPosInNode - 1];
2439
2440 itemRow = GetRowByItem(siblingNode->GetItem()) +
2441 siblingNode->GetSubTreeCount() +
2442 1;
2443 }
2444
2445 wxDataViewSelection newsel(wxDataViewSelectionCmp);
2446
2447 const size_t numSelections = m_selection.size();
2448 for ( size_t i = 0; i < numSelections; ++i )
2449 {
2450 const int s = m_selection[i];
2451 if ( s < itemRow )
2452 newsel.push_back(s);
2453 else if ( s >= itemRow + itemsDeleted )
2454 newsel.push_back(s - itemsDeleted);
2455 // else: deleted item, remove from selection
2456 }
2457
2458 m_selection = newsel;
2459 }
2460 }
2461
2462 // Change the current row to the last row if the current exceed the max row number
2463 if ( m_currentRow >= GetRowCount() )
2464 ChangeCurrentRow(m_count - 1);
2465
2466 GetOwner()->InvalidateColBestWidths();
2467 UpdateDisplay();
2468
2469 return true;
2470 }
2471
2472 bool wxDataViewMainWindow::ItemChanged(const wxDataViewItem & item)
2473 {
2474 SortPrepare();
2475 g_model->Resort();
2476
2477 GetOwner()->InvalidateColBestWidths();
2478
2479 // Send event
2480 wxWindow *parent = GetParent();
2481 wxDataViewEvent le(wxEVT_COMMAND_DATAVIEW_ITEM_VALUE_CHANGED, parent->GetId());
2482 le.SetEventObject(parent);
2483 le.SetModel(GetModel());
2484 le.SetItem(item);
2485 parent->ProcessWindowEvent(le);
2486
2487 return true;
2488 }
2489
2490 bool wxDataViewMainWindow::ValueChanged( const wxDataViewItem & item, unsigned int model_column )
2491 {
2492 int view_column = -1;
2493 unsigned int n_col = m_owner->GetColumnCount();
2494 for (unsigned i = 0; i < n_col; i++)
2495 {
2496 wxDataViewColumn *column = m_owner->GetColumn( i );
2497 if (column->GetModelColumn() == model_column)
2498 {
2499 view_column = (int) i;
2500 break;
2501 }
2502 }
2503 if (view_column == -1)
2504 return false;
2505
2506 // NOTE: to be valid, we cannot use e.g. INT_MAX - 1
2507 /*#define MAX_VIRTUAL_WIDTH 100000
2508
2509 wxRect rect( 0, row*m_lineHeight, MAX_VIRTUAL_WIDTH, m_lineHeight );
2510 m_owner->CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
2511 Refresh( true, &rect );
2512
2513 return true;
2514 */
2515 SortPrepare();
2516 g_model->Resort();
2517
2518 GetOwner()->InvalidateColBestWidth(view_column);
2519
2520 // Send event
2521 wxWindow *parent = GetParent();
2522 wxDataViewEvent le(wxEVT_COMMAND_DATAVIEW_ITEM_VALUE_CHANGED, parent->GetId());
2523 le.SetEventObject(parent);
2524 le.SetModel(GetModel());
2525 le.SetItem(item);
2526 le.SetColumn(view_column);
2527 le.SetDataViewColumn(GetOwner()->GetColumn(view_column));
2528 parent->ProcessWindowEvent(le);
2529
2530 return true;
2531 }
2532
2533 bool wxDataViewMainWindow::Cleared()
2534 {
2535 DestroyTree();
2536 m_selection.Clear();
2537 m_currentRow = (unsigned)-1;
2538
2539 if (GetModel())
2540 {
2541 SortPrepare();
2542 BuildTree( GetModel() );
2543 }
2544 else
2545 {
2546 m_count = 0;
2547 }
2548
2549 GetOwner()->InvalidateColBestWidths();
2550 UpdateDisplay();
2551
2552 return true;
2553 }
2554
2555 void wxDataViewMainWindow::UpdateDisplay()
2556 {
2557 m_dirty = true;
2558 m_underMouse = NULL;
2559 }
2560
2561 void wxDataViewMainWindow::OnInternalIdle()
2562 {
2563 wxWindow::OnInternalIdle();
2564
2565 if (m_dirty)
2566 {
2567 RecalculateDisplay();
2568 m_dirty = false;
2569 }
2570 }
2571
2572 void wxDataViewMainWindow::RecalculateDisplay()
2573 {
2574 wxDataViewModel *model = GetModel();
2575 if (!model)
2576 {
2577 Refresh();
2578 return;
2579 }
2580
2581 int width = GetEndOfLastCol();
2582 int height = GetLineStart( GetRowCount() );
2583
2584 SetVirtualSize( width, height );
2585 GetOwner()->SetScrollRate( 10, m_lineHeight );
2586
2587 Refresh();
2588 }
2589
2590 void wxDataViewMainWindow::ScrollWindow( int dx, int dy, const wxRect *rect )
2591 {
2592 m_underMouse = NULL;
2593
2594 wxWindow::ScrollWindow( dx, dy, rect );
2595
2596 if (GetOwner()->m_headerArea)
2597 GetOwner()->m_headerArea->ScrollWindow( dx, 0 );
2598 }
2599
2600 void wxDataViewMainWindow::ScrollTo( int rows, int column )
2601 {
2602 m_underMouse = NULL;
2603
2604 int x, y;
2605 m_owner->GetScrollPixelsPerUnit( &x, &y );
2606 int sy = GetLineStart( rows )/y;
2607 int sx = -1;
2608 if( column != -1 )
2609 {
2610 wxRect rect = GetClientRect();
2611 int colnum = 0;
2612 int x_start, w = 0;
2613 int xx, yy, xe;
2614 m_owner->CalcUnscrolledPosition( rect.x, rect.y, &xx, &yy );
2615 for (x_start = 0; colnum < column; colnum++)
2616 {
2617 wxDataViewColumn *col = GetOwner()->GetColumnAt(colnum);
2618 if (col->IsHidden())
2619 continue; // skip it!
2620
2621 w = col->GetWidth();
2622 x_start += w;
2623 }
2624
2625 int x_end = x_start + w;
2626 xe = xx + rect.width;
2627 if( x_end > xe )
2628 {
2629 sx = ( xx + x_end - xe )/x;
2630 }
2631 if( x_start < xx )
2632 {
2633 sx = x_start/x;
2634 }
2635 }
2636 m_owner->Scroll( sx, sy );
2637 }
2638
2639 int wxDataViewMainWindow::GetCountPerPage() const
2640 {
2641 wxSize size = GetClientSize();
2642 return size.y / m_lineHeight;
2643 }
2644
2645 int wxDataViewMainWindow::GetEndOfLastCol() const
2646 {
2647 int width = 0;
2648 unsigned int i;
2649 for (i = 0; i < GetOwner()->GetColumnCount(); i++)
2650 {
2651 const wxDataViewColumn *c =
2652 const_cast<wxDataViewCtrl*>(GetOwner())->GetColumnAt( i );
2653
2654 if (!c->IsHidden())
2655 width += c->GetWidth();
2656 }
2657 return width;
2658 }
2659
2660 unsigned int wxDataViewMainWindow::GetFirstVisibleRow() const
2661 {
2662 int x = 0;
2663 int y = 0;
2664 m_owner->CalcUnscrolledPosition( x, y, &x, &y );
2665
2666 return GetLineAt( y );
2667 }
2668
2669 unsigned int wxDataViewMainWindow::GetLastVisibleRow()
2670 {
2671 wxSize client_size = GetClientSize();
2672 m_owner->CalcUnscrolledPosition( client_size.x, client_size.y,
2673 &client_size.x, &client_size.y );
2674
2675 // we should deal with the pixel here
2676 unsigned int row = GetLineAt(client_size.y) - 1;
2677
2678 return wxMin( GetRowCount()-1, row );
2679 }
2680
2681 unsigned int wxDataViewMainWindow::GetRowCount() const
2682 {
2683 if ( m_count == -1 )
2684 {
2685 wxDataViewMainWindow* const
2686 self = const_cast<wxDataViewMainWindow*>(this);
2687 self->m_count = RecalculateCount();
2688 self->UpdateDisplay();
2689 }
2690 return m_count;
2691 }
2692
2693 void wxDataViewMainWindow::ChangeCurrentRow( unsigned int row )
2694 {
2695 m_currentRow = row;
2696
2697 // send event
2698 }
2699
2700 void wxDataViewMainWindow::SelectAllRows( bool on )
2701 {
2702 if (IsEmpty())
2703 return;
2704
2705 if (on)
2706 {
2707 m_selection.Clear();
2708 for (unsigned int i = 0; i < GetRowCount(); i++)
2709 m_selection.Add( i );
2710 Refresh();
2711 }
2712 else
2713 {
2714 unsigned int first_visible = GetFirstVisibleRow();
2715 unsigned int last_visible = GetLastVisibleRow();
2716 unsigned int i;
2717 for (i = 0; i < m_selection.GetCount(); i++)
2718 {
2719 unsigned int row = m_selection[i];
2720 if ((row >= first_visible) && (row <= last_visible))
2721 RefreshRow( row );
2722 }
2723 m_selection.Clear();
2724 }
2725 }
2726
2727 void wxDataViewMainWindow::SelectRow( unsigned int row, bool on )
2728 {
2729 if (m_selection.Index( row ) == wxNOT_FOUND)
2730 {
2731 if (on)
2732 {
2733 m_selection.Add( row );
2734 RefreshRow( row );
2735 }
2736 }
2737 else
2738 {
2739 if (!on)
2740 {
2741 m_selection.Remove( row );
2742 RefreshRow( row );
2743 }
2744 }
2745 }
2746
2747 void wxDataViewMainWindow::SelectRows( unsigned int from, unsigned int to, bool on )
2748 {
2749 if (from > to)
2750 {
2751 unsigned int tmp = from;
2752 from = to;
2753 to = tmp;
2754 }
2755
2756 unsigned int i;
2757 for (i = from; i <= to; i++)
2758 {
2759 if (m_selection.Index( i ) == wxNOT_FOUND)
2760 {
2761 if (on)
2762 m_selection.Add( i );
2763 }
2764 else
2765 {
2766 if (!on)
2767 m_selection.Remove( i );
2768 }
2769 }
2770 RefreshRows( from, to );
2771 }
2772
2773 void wxDataViewMainWindow::Select( const wxArrayInt& aSelections )
2774 {
2775 for (size_t i=0; i < aSelections.GetCount(); i++)
2776 {
2777 int n = aSelections[i];
2778
2779 m_selection.Add( n );
2780 RefreshRow( n );
2781 }
2782 }
2783
2784 void wxDataViewMainWindow::ReverseRowSelection( unsigned int row )
2785 {
2786 if (m_selection.Index( row ) == wxNOT_FOUND)
2787 m_selection.Add( row );
2788 else
2789 m_selection.Remove( row );
2790 RefreshRow( row );
2791 }
2792
2793 bool wxDataViewMainWindow::IsRowSelected( unsigned int row )
2794 {
2795 return (m_selection.Index( row ) != wxNOT_FOUND);
2796 }
2797
2798 void wxDataViewMainWindow::SendSelectionChangedEvent( const wxDataViewItem& item)
2799 {
2800 wxWindow *parent = GetParent();
2801 wxDataViewEvent le(wxEVT_COMMAND_DATAVIEW_SELECTION_CHANGED, parent->GetId());
2802
2803 le.SetEventObject(parent);
2804 le.SetModel(GetModel());
2805 le.SetItem( item );
2806
2807 parent->ProcessWindowEvent(le);
2808 }
2809
2810 void wxDataViewMainWindow::RefreshRow( unsigned int row )
2811 {
2812 wxRect rect( 0, GetLineStart( row ), GetEndOfLastCol(), GetLineHeight( row ) );
2813 m_owner->CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
2814
2815 wxSize client_size = GetClientSize();
2816 wxRect client_rect( 0, 0, client_size.x, client_size.y );
2817 wxRect intersect_rect = client_rect.Intersect( rect );
2818 if (intersect_rect.width > 0)
2819 Refresh( true, &intersect_rect );
2820 }
2821
2822 void wxDataViewMainWindow::RefreshRows( unsigned int from, unsigned int to )
2823 {
2824 if (from > to)
2825 {
2826 unsigned int tmp = to;
2827 to = from;
2828 from = tmp;
2829 }
2830
2831 wxRect rect( 0, GetLineStart( from ), GetEndOfLastCol(), GetLineStart( (to-from+1) ) );
2832 m_owner->CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
2833
2834 wxSize client_size = GetClientSize();
2835 wxRect client_rect( 0, 0, client_size.x, client_size.y );
2836 wxRect intersect_rect = client_rect.Intersect( rect );
2837 if (intersect_rect.width > 0)
2838 Refresh( true, &intersect_rect );
2839 }
2840
2841 void wxDataViewMainWindow::RefreshRowsAfter( unsigned int firstRow )
2842 {
2843 wxSize client_size = GetClientSize();
2844 int start = GetLineStart( firstRow );
2845 m_owner->CalcScrolledPosition( start, 0, &start, NULL );
2846 if (start > client_size.y) return;
2847
2848 wxRect rect( 0, start, client_size.x, client_size.y - start );
2849
2850 Refresh( true, &rect );
2851 }
2852
2853 wxRect wxDataViewMainWindow::GetLineRect( unsigned int row ) const
2854 {
2855 wxRect rect;
2856 rect.x = 0;
2857 rect.y = GetLineStart( row );
2858 rect.width = GetEndOfLastCol();
2859 rect.height = GetLineHeight( row );
2860
2861 return rect;
2862 }
2863
2864 int wxDataViewMainWindow::GetLineStart( unsigned int row ) const
2865 {
2866 const wxDataViewModel *model = GetModel();
2867
2868 if (GetOwner()->GetWindowStyle() & wxDV_VARIABLE_LINE_HEIGHT)
2869 {
2870 // TODO make more efficient
2871
2872 int start = 0;
2873
2874 unsigned int r;
2875 for (r = 0; r < row; r++)
2876 {
2877 const wxDataViewTreeNode* node = GetTreeNodeByRow(r);
2878 if (!node) return start;
2879
2880 wxDataViewItem item = node->GetItem();
2881
2882 unsigned int cols = GetOwner()->GetColumnCount();
2883 unsigned int col;
2884 int height = m_lineHeight;
2885 for (col = 0; col < cols; col++)
2886 {
2887 const wxDataViewColumn *column = GetOwner()->GetColumn(col);
2888 if (column->IsHidden())
2889 continue; // skip it!
2890
2891 if ((col != 0) &&
2892 model->IsContainer(item) &&
2893 !model->HasContainerColumns(item))
2894 continue; // skip it!
2895
2896 wxDataViewRenderer *renderer =
2897 const_cast<wxDataViewRenderer*>(column->GetRenderer());
2898 renderer->PrepareForItem(model, item, column->GetModelColumn());
2899
2900 height = wxMax( height, renderer->GetSize().y );
2901 }
2902
2903 start += height;
2904 }
2905
2906 return start;
2907 }
2908 else
2909 {
2910 return row * m_lineHeight;
2911 }
2912 }
2913
2914 int wxDataViewMainWindow::GetLineAt( unsigned int y ) const
2915 {
2916 const wxDataViewModel *model = GetModel();
2917
2918 // check for the easy case first
2919 if ( !GetOwner()->HasFlag(wxDV_VARIABLE_LINE_HEIGHT) )
2920 return y / m_lineHeight;
2921
2922 // TODO make more efficient
2923 unsigned int row = 0;
2924 unsigned int yy = 0;
2925 for (;;)
2926 {
2927 const wxDataViewTreeNode* node = GetTreeNodeByRow(row);
2928 if (!node)
2929 {
2930 // not really correct...
2931 return row + ((y-yy) / m_lineHeight);
2932 }
2933
2934 wxDataViewItem item = node->GetItem();
2935
2936 unsigned int cols = GetOwner()->GetColumnCount();
2937 unsigned int col;
2938 int height = m_lineHeight;
2939 for (col = 0; col < cols; col++)
2940 {
2941 const wxDataViewColumn *column = GetOwner()->GetColumn(col);
2942 if (column->IsHidden())
2943 continue; // skip it!
2944
2945 if ((col != 0) &&
2946 model->IsContainer(item) &&
2947 !model->HasContainerColumns(item))
2948 continue; // skip it!
2949
2950 wxDataViewRenderer *renderer =
2951 const_cast<wxDataViewRenderer*>(column->GetRenderer());
2952 renderer->PrepareForItem(model, item, column->GetModelColumn());
2953
2954 height = wxMax( height, renderer->GetSize().y );
2955 }
2956
2957 yy += height;
2958 if (y < yy)
2959 return row;
2960
2961 row++;
2962 }
2963 }
2964
2965 int wxDataViewMainWindow::GetLineHeight( unsigned int row ) const
2966 {
2967 const wxDataViewModel *model = GetModel();
2968
2969 if (GetOwner()->GetWindowStyle() & wxDV_VARIABLE_LINE_HEIGHT)
2970 {
2971 wxASSERT( !IsVirtualList() );
2972
2973 const wxDataViewTreeNode* node = GetTreeNodeByRow(row);
2974 // wxASSERT( node );
2975 if (!node) return m_lineHeight;
2976
2977 wxDataViewItem item = node->GetItem();
2978
2979 int height = m_lineHeight;
2980
2981 unsigned int cols = GetOwner()->GetColumnCount();
2982 unsigned int col;
2983 for (col = 0; col < cols; col++)
2984 {
2985 const wxDataViewColumn *column = GetOwner()->GetColumn(col);
2986 if (column->IsHidden())
2987 continue; // skip it!
2988
2989 if ((col != 0) &&
2990 model->IsContainer(item) &&
2991 !model->HasContainerColumns(item))
2992 continue; // skip it!
2993
2994 wxDataViewRenderer *renderer =
2995 const_cast<wxDataViewRenderer*>(column->GetRenderer());
2996 renderer->PrepareForItem(model, item, column->GetModelColumn());
2997
2998 height = wxMax( height, renderer->GetSize().y );
2999 }
3000
3001 return height;
3002 }
3003 else
3004 {
3005 return m_lineHeight;
3006 }
3007 }
3008
3009
3010 class RowToTreeNodeJob: public DoJob
3011 {
3012 public:
3013 RowToTreeNodeJob( unsigned int row , int current, wxDataViewTreeNode * node )
3014 {
3015 this->row = row;
3016 this->current = current;
3017 ret = NULL;
3018 parent = node;
3019 }
3020
3021 virtual int operator() ( wxDataViewTreeNode * node )
3022 {
3023 current ++;
3024 if( current == static_cast<int>(row))
3025 {
3026 ret = node;
3027 return DoJob::DONE;
3028 }
3029
3030 if( node->GetSubTreeCount() + current < static_cast<int>(row) )
3031 {
3032 current += node->GetSubTreeCount();
3033 return DoJob::SKIP_SUBTREE;
3034 }
3035 else
3036 {
3037 parent = node;
3038
3039 // If the current node has only leaf children, we can find the
3040 // desired node directly. This can speed up finding the node
3041 // in some cases, and will have a very good effect for list views.
3042 if ( node->HasChildren() &&
3043 (int)node->GetChildNodes().size() == node->GetSubTreeCount() )
3044 {
3045 const int index = static_cast<int>(row) - current - 1;
3046 ret = node->GetChildNodes()[index];
3047 return DoJob::DONE;
3048 }
3049
3050 return DoJob::CONTINUE;
3051 }
3052 }
3053
3054 wxDataViewTreeNode * GetResult() const
3055 { return ret; }
3056
3057 private:
3058 unsigned int row;
3059 int current;
3060 wxDataViewTreeNode * ret;
3061 wxDataViewTreeNode * parent;
3062 };
3063
3064 wxDataViewTreeNode * wxDataViewMainWindow::GetTreeNodeByRow(unsigned int row) const
3065 {
3066 wxASSERT( !IsVirtualList() );
3067
3068 if ( row == (unsigned)-1 )
3069 return NULL;
3070
3071 RowToTreeNodeJob job( row , -2, m_root );
3072 Walker( m_root , job );
3073 return job.GetResult();
3074 }
3075
3076 wxDataViewItem wxDataViewMainWindow::GetItemByRow(unsigned int row) const
3077 {
3078 wxDataViewItem item;
3079 if (IsVirtualList())
3080 {
3081 if ( row < GetRowCount() )
3082 item = wxDataViewItem(wxUIntToPtr(row+1));
3083 }
3084 else
3085 {
3086 wxDataViewTreeNode *node = GetTreeNodeByRow(row);
3087 if ( node )
3088 item = node->GetItem();
3089 }
3090
3091 return item;
3092 }
3093
3094 bool
3095 wxDataViewMainWindow::SendExpanderEvent(wxEventType type,
3096 const wxDataViewItem& item)
3097 {
3098 wxWindow *parent = GetParent();
3099 wxDataViewEvent le(type, parent->GetId());
3100
3101 le.SetEventObject(parent);
3102 le.SetModel(GetModel());
3103 le.SetItem( item );
3104
3105 return !parent->ProcessWindowEvent(le) || le.IsAllowed();
3106 }
3107
3108 bool wxDataViewMainWindow::IsExpanded( unsigned int row ) const
3109 {
3110 if (IsList())
3111 return false;
3112
3113 wxDataViewTreeNode * node = GetTreeNodeByRow(row);
3114 if (!node)
3115 return false;
3116
3117 if (!node->HasChildren())
3118 return false;
3119
3120 return node->IsOpen();
3121 }
3122
3123 bool wxDataViewMainWindow::HasChildren( unsigned int row ) const
3124 {
3125 if (IsList())
3126 return false;
3127
3128 wxDataViewTreeNode * node = GetTreeNodeByRow(row);
3129 if (!node)
3130 return false;
3131
3132 if (!node->HasChildren())
3133 return false;
3134
3135 return true;
3136 }
3137
3138 void wxDataViewMainWindow::Expand( unsigned int row )
3139 {
3140 if (IsList())
3141 return;
3142
3143 wxDataViewTreeNode * node = GetTreeNodeByRow(row);
3144 if (!node)
3145 return;
3146
3147 if (!node->HasChildren())
3148 return;
3149
3150 if (!node->IsOpen())
3151 {
3152 if ( !SendExpanderEvent(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDING, node->GetItem()) )
3153 {
3154 // Vetoed by the event handler.
3155 return;
3156 }
3157
3158 node->ToggleOpen();
3159
3160 // build the children of current node
3161 if( node->GetChildNodes().empty() )
3162 {
3163 SortPrepare();
3164 ::BuildTreeHelper(GetModel(), node->GetItem(), node);
3165 }
3166
3167 // By expanding the node all row indices that are currently in the selection list
3168 // and are greater than our node have become invalid. So we have to correct that now.
3169 const unsigned rowAdjustment = node->GetSubTreeCount();
3170 for(unsigned i=0; i<m_selection.size(); ++i)
3171 {
3172 const unsigned testRow = m_selection[i];
3173 // all rows above us are not affected, so skip them
3174 if(testRow <= row)
3175 continue;
3176
3177 m_selection[i] += rowAdjustment;
3178 }
3179
3180 if(m_currentRow > row)
3181 ChangeCurrentRow(m_currentRow + rowAdjustment);
3182
3183 m_count = -1;
3184 UpdateDisplay();
3185 // Send the expanded event
3186 SendExpanderEvent(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDED,node->GetItem());
3187 }
3188 }
3189
3190 void wxDataViewMainWindow::Collapse(unsigned int row)
3191 {
3192 if (IsList())
3193 return;
3194
3195 wxDataViewTreeNode *node = GetTreeNodeByRow(row);
3196 if (!node)
3197 return;
3198
3199 if (!node->HasChildren())
3200 return;
3201
3202 if (node->IsOpen())
3203 {
3204 if ( !SendExpanderEvent(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSING,node->GetItem()) )
3205 {
3206 // Vetoed by the event handler.
3207 return;
3208 }
3209
3210 // Find out if there are selected items below the current node.
3211 bool selectCollapsingRow = false;
3212 const unsigned rowAdjustment = node->GetSubTreeCount();
3213 unsigned maxRowToBeTested = row + rowAdjustment;
3214 for(unsigned i=0; i<m_selection.size(); ++i)
3215 {
3216 const unsigned testRow = m_selection[i];
3217 if(testRow > row && testRow <= maxRowToBeTested)
3218 {
3219 selectCollapsingRow = true;
3220 // get out as soon as we have found a node that is selected
3221 break;
3222 }
3223 }
3224
3225 node->ToggleOpen();
3226
3227 // If the node to be closed has selected items the user won't see those any longer.
3228 // We select the collapsing node in this case.
3229 if(selectCollapsingRow)
3230 {
3231 SelectAllRows(false);
3232 ChangeCurrentRow(row);
3233 SelectRow(row, true);
3234 SendSelectionChangedEvent(GetItemByRow(row));
3235 }
3236 else
3237 {
3238 // if there were no selected items below our node we still need to "fix" the
3239 // selection list to adjust for the changing of the row indices.
3240 // We actually do the opposite of what we are doing in Expand().
3241 for(unsigned i=0; i<m_selection.size(); ++i)
3242 {
3243 const unsigned testRow = m_selection[i];
3244 // all rows above us are not affected, so skip them
3245 if(testRow <= row)
3246 continue;
3247
3248 m_selection[i] -= rowAdjustment;
3249 }
3250
3251 // if the "current row" is being collapsed away we change it to the current row ;-)
3252 if(m_currentRow > row && m_currentRow <= maxRowToBeTested)
3253 ChangeCurrentRow(row);
3254 else if(m_currentRow > row)
3255 ChangeCurrentRow(m_currentRow - rowAdjustment);
3256 }
3257
3258 m_count = -1;
3259 UpdateDisplay();
3260 SendExpanderEvent(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSED,node->GetItem());
3261 }
3262 }
3263
3264 wxDataViewTreeNode * wxDataViewMainWindow::FindNode( const wxDataViewItem & item )
3265 {
3266 const wxDataViewModel * model = GetModel();
3267 if( model == NULL )
3268 return NULL;
3269
3270 if (!item.IsOk())
3271 return m_root;
3272
3273 // Compose the parent-chain for the item we are looking for
3274 wxVector<wxDataViewItem> parentChain;
3275 wxDataViewItem it( item );
3276 while( it.IsOk() )
3277 {
3278 parentChain.push_back(it);
3279 it = model->GetParent(it);
3280 }
3281
3282 // Find the item along the parent-chain.
3283 // This algorithm is designed to speed up the node-finding method
3284 wxDataViewTreeNode* node = m_root;
3285 for( unsigned iter = parentChain.size()-1; ; --iter )
3286 {
3287 if( node->HasChildren() )
3288 {
3289 if( node->GetChildNodes().empty() )
3290 {
3291 // Even though the item is a container, it doesn't have any
3292 // child nodes in the control's representation yet. We have
3293 // to realize its subtree now.
3294 SortPrepare();
3295 ::BuildTreeHelper(model, node->GetItem(), node);
3296 }
3297
3298 const wxDataViewTreeNodes& nodes = node->GetChildNodes();
3299 bool found = false;
3300
3301 for (unsigned i = 0; i < nodes.GetCount(); ++i)
3302 {
3303 wxDataViewTreeNode* currentNode = nodes[i];
3304 if (currentNode->GetItem() == parentChain[iter])
3305 {
3306 if (currentNode->GetItem() == item)
3307 return currentNode;
3308
3309 node = currentNode;
3310 found = true;
3311 break;
3312 }
3313 }
3314 if (!found)
3315 return NULL;
3316 }
3317 else
3318 return NULL;
3319
3320 if ( !iter )
3321 break;
3322 }
3323 return NULL;
3324 }
3325
3326 void wxDataViewMainWindow::HitTest( const wxPoint & point, wxDataViewItem & item,
3327 wxDataViewColumn* &column )
3328 {
3329 wxDataViewColumn *col = NULL;
3330 unsigned int cols = GetOwner()->GetColumnCount();
3331 unsigned int colnum = 0;
3332 int x, y;
3333 m_owner->CalcUnscrolledPosition( point.x, point.y, &x, &y );
3334 for (unsigned x_start = 0; colnum < cols; colnum++)
3335 {
3336 col = GetOwner()->GetColumnAt(colnum);
3337 if (col->IsHidden())
3338 continue; // skip it!
3339
3340 unsigned int w = col->GetWidth();
3341 if (x_start+w >= (unsigned int)x)
3342 break;
3343
3344 x_start += w;
3345 }
3346
3347 column = col;
3348 item = GetItemByRow( GetLineAt( y ) );
3349 }
3350
3351 wxRect wxDataViewMainWindow::GetItemRect( const wxDataViewItem & item,
3352 const wxDataViewColumn* column )
3353 {
3354 int xpos = 0;
3355 int width = 0;
3356
3357 unsigned int cols = GetOwner()->GetColumnCount();
3358 // If column is null the loop will compute the combined width of all columns.
3359 // Otherwise, it will compute the x position of the column we are looking for.
3360 for (unsigned int i = 0; i < cols; i++)
3361 {
3362 wxDataViewColumn* col = GetOwner()->GetColumnAt( i );
3363
3364 if (col == column)
3365 break;
3366
3367 if (col->IsHidden())
3368 continue; // skip it!
3369
3370 xpos += col->GetWidth();
3371 width += col->GetWidth();
3372 }
3373
3374 if(column != 0)
3375 {
3376 // If we have a column, we need can get its width directly.
3377 if(column->IsHidden())
3378 width = 0;
3379 else
3380 width = column->GetWidth();
3381
3382 }
3383 else
3384 {
3385 // If we have no column, we reset the x position back to zero.
3386 xpos = 0;
3387 }
3388
3389 // we have to take an expander column into account and compute its indentation
3390 // to get the correct x position where the actual text is
3391 int indent = 0;
3392 int row = GetRowByItem(item);
3393 if (!IsList() &&
3394 (column == 0 || GetExpanderColumnOrFirstOne(GetOwner()) == column) )
3395 {
3396 wxDataViewTreeNode* node = GetTreeNodeByRow(row);
3397 indent = GetOwner()->GetIndent() * node->GetIndentLevel();
3398 indent = indent + m_lineHeight; // use m_lineHeight as the width of the expander
3399 }
3400
3401 wxRect itemRect( xpos + indent,
3402 GetLineStart( row ),
3403 width - indent,
3404 GetLineHeight( row ) );
3405
3406 GetOwner()->CalcScrolledPosition( itemRect.x, itemRect.y,
3407 &itemRect.x, &itemRect.y );
3408
3409 return itemRect;
3410 }
3411
3412 int wxDataViewMainWindow::RecalculateCount() const
3413 {
3414 if (IsVirtualList())
3415 {
3416 wxDataViewVirtualListModel *list_model =
3417 (wxDataViewVirtualListModel*) GetModel();
3418
3419 return list_model->GetCount();
3420 }
3421 else
3422 {
3423 return m_root->GetSubTreeCount();
3424 }
3425 }
3426
3427 class ItemToRowJob : public DoJob
3428 {
3429 public:
3430 ItemToRowJob(const wxDataViewItem& item_, wxVector<wxDataViewItem>::reverse_iterator iter)
3431 : m_iter(iter),
3432 item(item_)
3433 {
3434 ret = -1;
3435 }
3436
3437 // Maybe binary search will help to speed up this process
3438 virtual int operator() ( wxDataViewTreeNode * node)
3439 {
3440 ret ++;
3441 if( node->GetItem() == item )
3442 {
3443 return DoJob::DONE;
3444 }
3445
3446 if( node->GetItem() == *m_iter )
3447 {
3448 m_iter++;
3449 return DoJob::CONTINUE;
3450 }
3451 else
3452 {
3453 ret += node->GetSubTreeCount();
3454 return DoJob::SKIP_SUBTREE;
3455 }
3456
3457 }
3458
3459 // the row number is begin from zero
3460 int GetResult() const
3461 { return ret -1; }
3462
3463 private:
3464 wxVector<wxDataViewItem>::reverse_iterator m_iter;
3465 wxDataViewItem item;
3466 int ret;
3467
3468 };
3469
3470 int wxDataViewMainWindow::GetRowByItem(const wxDataViewItem & item) const
3471 {
3472 const wxDataViewModel * model = GetModel();
3473 if( model == NULL )
3474 return -1;
3475
3476 if (IsVirtualList())
3477 {
3478 return wxPtrToUInt( item.GetID() ) -1;
3479 }
3480 else
3481 {
3482 if( !item.IsOk() )
3483 return -1;
3484
3485 // Compose the parent-chain of the item we are looking for
3486 wxVector<wxDataViewItem> parentChain;
3487 wxDataViewItem it( item );
3488 while( it.IsOk() )
3489 {
3490 parentChain.push_back(it);
3491 it = model->GetParent(it);
3492 }
3493
3494 // add an 'invalid' item to represent our 'invisible' root node
3495 parentChain.push_back(wxDataViewItem());
3496
3497 // the parent chain was created by adding the deepest parent first.
3498 // so if we want to start at the root node, we have to iterate backwards through the vector
3499 ItemToRowJob job( item, parentChain.rbegin() );
3500 Walker( m_root, job );
3501 return job.GetResult();
3502 }
3503 }
3504
3505 static void BuildTreeHelper( const wxDataViewModel * model, const wxDataViewItem & item,
3506 wxDataViewTreeNode * node)
3507 {
3508 if( !model->IsContainer( item ) )
3509 return;
3510
3511 wxDataViewItemArray children;
3512 unsigned int num = model->GetChildren( item, children);
3513
3514 for ( unsigned int index = 0; index < num; index++ )
3515 {
3516 wxDataViewTreeNode *n = new wxDataViewTreeNode(node, children[index]);
3517
3518 if( model->IsContainer(children[index]) )
3519 n->SetHasChildren( true );
3520
3521 node->InsertChild(n, index);
3522 }
3523
3524 wxASSERT( node->IsOpen() );
3525 node->ChangeSubTreeCount(+num);
3526 }
3527
3528 void wxDataViewMainWindow::BuildTree(wxDataViewModel * model)
3529 {
3530 DestroyTree();
3531
3532 if (GetModel()->IsVirtualListModel())
3533 {
3534 m_count = -1;
3535 return;
3536 }
3537
3538 m_root = wxDataViewTreeNode::CreateRootNode();
3539
3540 // First we define a invalid item to fetch the top-level elements
3541 wxDataViewItem item;
3542 SortPrepare();
3543 BuildTreeHelper( model, item, m_root);
3544 m_count = -1;
3545 }
3546
3547 void wxDataViewMainWindow::DestroyTree()
3548 {
3549 if (!IsVirtualList())
3550 {
3551 wxDELETE(m_root);
3552 m_count = 0;
3553 }
3554 }
3555
3556 wxDataViewColumn*
3557 wxDataViewMainWindow::FindColumnForEditing(const wxDataViewItem& item, wxDataViewCellMode mode)
3558 {
3559 // Edit the current column editable in 'mode'. If no column is focused
3560 // (typically because the user has full row selected), try to find the
3561 // first editable column (this would typically be a checkbox for
3562 // wxDATAVIEW_CELL_ACTIVATABLE and we don't want to force the user to set
3563 // focus on the checkbox column; or on the only editable text column).
3564
3565 wxDataViewColumn *candidate = m_currentCol;
3566
3567 if ( candidate &&
3568 !IsCellEditableInMode(item, candidate, mode) &&
3569 !m_currentColSetByKeyboard )
3570 {
3571 // If current column was set by mouse to something not editable (in
3572 // 'mode') and the user pressed Space/F2 to edit it, treat the
3573 // situation as if there was whole-row focus, because that's what is
3574 // visually indicated and the mouse click could very well be targeted
3575 // on the row rather than on an individual cell.
3576 //
3577 // But if it was done by keyboard, respect that even if the column
3578 // isn't editable, because focus is visually on that column and editing
3579 // something else would be surprising.
3580 candidate = NULL;
3581 }
3582
3583 if ( !candidate )
3584 {
3585 const unsigned cols = GetOwner()->GetColumnCount();
3586 for ( unsigned i = 0; i < cols; i++ )
3587 {
3588 wxDataViewColumn *c = GetOwner()->GetColumnAt(i);
3589 if ( c->IsHidden() )
3590 continue;
3591
3592 if ( IsCellEditableInMode(item, c, mode) )
3593 {
3594 candidate = c;
3595 break;
3596 }
3597 }
3598 }
3599
3600 // If on container item without columns, only the expander column
3601 // may be directly editable:
3602 if ( candidate &&
3603 GetOwner()->GetExpanderColumn() != candidate &&
3604 GetModel()->IsContainer(item) &&
3605 !GetModel()->HasContainerColumns(item) )
3606 {
3607 candidate = GetOwner()->GetExpanderColumn();
3608 }
3609
3610 if ( !candidate )
3611 return NULL;
3612
3613 if ( !IsCellEditableInMode(item, candidate, mode) )
3614 return NULL;
3615
3616 return candidate;
3617 }
3618
3619 bool wxDataViewMainWindow::IsCellEditableInMode(const wxDataViewItem& item,
3620 const wxDataViewColumn *col,
3621 wxDataViewCellMode mode) const
3622 {
3623 if ( col->GetRenderer()->GetMode() != mode )
3624 return false;
3625
3626 if ( !GetModel()->IsEnabled(item, col->GetModelColumn()) )
3627 return false;
3628
3629 return true;
3630 }
3631
3632 void wxDataViewMainWindow::OnCharHook(wxKeyEvent& event)
3633 {
3634 if ( m_editorCtrl )
3635 {
3636 // Handle any keys special for the in-place editor and return without
3637 // calling Skip() below.
3638 switch ( event.GetKeyCode() )
3639 {
3640 case WXK_ESCAPE:
3641 m_editorRenderer->CancelEditing();
3642 return;
3643
3644 case WXK_RETURN:
3645 m_editorRenderer->FinishEditing();
3646 return;
3647 }
3648 }
3649
3650 event.Skip();
3651 }
3652
3653 void wxDataViewMainWindow::OnChar( wxKeyEvent &event )
3654 {
3655 wxWindow * const parent = GetParent();
3656
3657 // propagate the char event upwards
3658 wxKeyEvent eventForParent(event);
3659 eventForParent.SetEventObject(parent);
3660 if ( parent->ProcessWindowEvent(eventForParent) )
3661 return;
3662
3663 if ( parent->HandleAsNavigationKey(event) )
3664 return;
3665
3666 // no item -> nothing to do
3667 if (!HasCurrentRow())
3668 {
3669 event.Skip();
3670 return;
3671 }
3672
3673 // don't use m_linesPerPage directly as it might not be computed yet
3674 const int pageSize = GetCountPerPage();
3675 wxCHECK_RET( pageSize, wxT("should have non zero page size") );
3676
3677 switch ( event.GetKeyCode() )
3678 {
3679 case WXK_RETURN:
3680 if ( event.HasModifiers() )
3681 {
3682 event.Skip();
3683 break;
3684 }
3685 else
3686 {
3687 // Enter activates the item, i.e. sends wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED to
3688 // it. Only if that event is not handled do we activate column renderer (which
3689 // is normally done by Space) or even inline editing.
3690
3691 const wxDataViewItem item = GetItemByRow(m_currentRow);
3692
3693 wxDataViewEvent le(wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED,
3694 parent->GetId());
3695 le.SetItem(item);
3696 le.SetEventObject(parent);
3697 le.SetModel(GetModel());
3698
3699 if ( parent->ProcessWindowEvent(le) )
3700 break;
3701 // else: fall through to WXK_SPACE handling
3702 }
3703
3704 case WXK_SPACE:
3705 if ( event.HasModifiers() )
3706 {
3707 event.Skip();
3708 break;
3709 }
3710 else
3711 {
3712 // Space toggles activatable items or -- if not activatable --
3713 // starts inline editing (this is normally done using F2 on
3714 // Windows, but Space is common everywhere else, so use it too
3715 // for greater cross-platform compatibility).
3716
3717 const wxDataViewItem item = GetItemByRow(m_currentRow);
3718
3719 // Activate the current activatable column. If not column is focused (typically
3720 // because the user has full row selected), try to find the first activatable
3721 // column (this would typically be a checkbox and we don't want to force the user
3722 // to set focus on the checkbox column).
3723 wxDataViewColumn *activatableCol = FindColumnForEditing(item, wxDATAVIEW_CELL_ACTIVATABLE);
3724
3725 if ( activatableCol )
3726 {
3727 const unsigned colIdx = activatableCol->GetModelColumn();
3728 const wxRect cell_rect = GetOwner()->GetItemRect(item, activatableCol);
3729
3730 wxDataViewRenderer *cell = activatableCol->GetRenderer();
3731 cell->PrepareForItem(GetModel(), item, colIdx);
3732 cell->WXActivateCell(cell_rect, GetModel(), item, colIdx, NULL);
3733
3734 break;
3735 }
3736 // else: fall through to WXK_F2 handling
3737 }
3738
3739 case WXK_F2:
3740 if ( event.HasModifiers() )
3741 {
3742 event.Skip();
3743 break;
3744 }
3745 else
3746 {
3747 if( !m_selection.empty() )
3748 {
3749 // Mimic Windows 7 behavior: edit the item that has focus
3750 // if it is selected and the first selected item if focus
3751 // is out of selection.
3752 int sel;
3753 if ( m_selection.Index(m_currentRow) != wxNOT_FOUND )
3754 sel = m_currentRow;
3755 else
3756 sel = m_selection[0];
3757
3758
3759 const wxDataViewItem item = GetItemByRow(sel);
3760
3761 // Edit the current column. If no column is focused
3762 // (typically because the user has full row selected), try
3763 // to find the first editable column.
3764 wxDataViewColumn *editableCol = FindColumnForEditing(item, wxDATAVIEW_CELL_EDITABLE);
3765
3766 if ( editableCol )
3767 GetOwner()->EditItem(item, editableCol);
3768 }
3769 }
3770 break;
3771
3772 case WXK_UP:
3773 OnVerticalNavigation( -1, event );
3774 break;
3775
3776 case WXK_DOWN:
3777 OnVerticalNavigation( +1, event );
3778 break;
3779 // Add the process for tree expanding/collapsing
3780 case WXK_LEFT:
3781 OnLeftKey();
3782 break;
3783
3784 case WXK_RIGHT:
3785 OnRightKey();
3786 break;
3787
3788 case WXK_END:
3789 OnVerticalNavigation( +(int)GetRowCount(), event );
3790 break;
3791
3792 case WXK_HOME:
3793 OnVerticalNavigation( -(int)GetRowCount(), event );
3794 break;
3795
3796 case WXK_PAGEUP:
3797 OnVerticalNavigation( -(pageSize - 1), event );
3798 break;
3799
3800 case WXK_PAGEDOWN:
3801 OnVerticalNavigation( +(pageSize - 1), event );
3802 break;
3803
3804 default:
3805 event.Skip();
3806 }
3807 }
3808
3809 void wxDataViewMainWindow::OnVerticalNavigation(int delta, const wxKeyEvent& event)
3810 {
3811 // if there is no selection, we cannot move it anywhere
3812 if (!HasCurrentRow() || IsEmpty())
3813 return;
3814
3815 int newRow = (int)m_currentRow + delta;
3816
3817 // let's keep the new row inside the allowed range
3818 if ( newRow < 0 )
3819 newRow = 0;
3820
3821 const int rowCount = (int)GetRowCount();
3822 if ( newRow >= rowCount )
3823 newRow = rowCount - 1;
3824
3825 unsigned int oldCurrent = m_currentRow;
3826 unsigned int newCurrent = (unsigned int)newRow;
3827
3828 // in single selection we just ignore Shift as we can't select several
3829 // items anyhow
3830 if ( event.ShiftDown() && !IsSingleSel() )
3831 {
3832 RefreshRow( oldCurrent );
3833
3834 ChangeCurrentRow( newCurrent );
3835
3836 // select all the items between the old and the new one
3837 if ( oldCurrent > newCurrent )
3838 {
3839 newCurrent = oldCurrent;
3840 oldCurrent = m_currentRow;
3841 }
3842
3843 SelectRows( oldCurrent, newCurrent, true );
3844 if (oldCurrent!=newCurrent)
3845 SendSelectionChangedEvent(GetItemByRow(m_selection[0]));
3846 }
3847 else // !shift
3848 {
3849 RefreshRow( oldCurrent );
3850
3851 // all previously selected items are unselected unless ctrl is held
3852 if ( !event.ControlDown() )
3853 SelectAllRows(false);
3854
3855 ChangeCurrentRow( newCurrent );
3856
3857 if ( !event.ControlDown() )
3858 {
3859 SelectRow( m_currentRow, true );
3860 SendSelectionChangedEvent(GetItemByRow(m_currentRow));
3861 }
3862 else
3863 RefreshRow( m_currentRow );
3864 }
3865
3866 GetOwner()->EnsureVisible( m_currentRow, -1 );
3867 }
3868
3869 void wxDataViewMainWindow::OnLeftKey()
3870 {
3871 if ( IsList() )
3872 {
3873 TryAdvanceCurrentColumn(NULL, /*forward=*/false);
3874 }
3875 else
3876 {
3877 wxDataViewTreeNode* node = GetTreeNodeByRow(m_currentRow);
3878 if ( !node )
3879 return;
3880
3881 if ( TryAdvanceCurrentColumn(node, /*forward=*/false) )
3882 return;
3883
3884 // Because TryAdvanceCurrentColumn() return false, we are at the first
3885 // column or using whole-row selection. In this situation, we can use
3886 // the standard TreeView handling of the left key.
3887 if (node->HasChildren() && node->IsOpen())
3888 {
3889 Collapse(m_currentRow);
3890 }
3891 else
3892 {
3893 // if the node is already closed, we move the selection to its parent
3894 wxDataViewTreeNode *parent_node = node->GetParent();
3895
3896 if (parent_node)
3897 {
3898 int parent = GetRowByItem( parent_node->GetItem() );
3899 if ( parent >= 0 )
3900 {
3901 unsigned int row = m_currentRow;
3902 SelectRow( row, false);
3903 SelectRow( parent, true );
3904 ChangeCurrentRow( parent );
3905 GetOwner()->EnsureVisible( parent, -1 );
3906 SendSelectionChangedEvent( parent_node->GetItem() );
3907 }
3908 }
3909 }
3910 }
3911 }
3912
3913 void wxDataViewMainWindow::OnRightKey()
3914 {
3915 if ( IsList() )
3916 {
3917 TryAdvanceCurrentColumn(NULL, /*forward=*/true);
3918 }
3919 else
3920 {
3921 wxDataViewTreeNode* node = GetTreeNodeByRow(m_currentRow);
3922 if ( !node )
3923 return;
3924
3925 if ( node->HasChildren() )
3926 {
3927 if ( !node->IsOpen() )
3928 {
3929 Expand( m_currentRow );
3930 }
3931 else
3932 {
3933 // if the node is already open, we move the selection to the first child
3934 unsigned int row = m_currentRow;
3935 SelectRow( row, false );
3936 SelectRow( row + 1, true );
3937 ChangeCurrentRow( row + 1 );
3938 GetOwner()->EnsureVisible( row + 1, -1 );
3939 SendSelectionChangedEvent( GetItemByRow(row+1) );
3940 }
3941 }
3942 else
3943 {
3944 TryAdvanceCurrentColumn(node, /*forward=*/true);
3945 }
3946 }
3947 }
3948
3949 bool wxDataViewMainWindow::TryAdvanceCurrentColumn(wxDataViewTreeNode *node, bool forward)
3950 {
3951 if ( GetOwner()->GetColumnCount() == 0 )
3952 return false;
3953
3954 if ( !m_useCellFocus )
3955 return false;
3956
3957 if ( node )
3958 {
3959 // navigation shouldn't work in branch nodes without other columns:
3960 if ( node->HasChildren() && !GetModel()->HasContainerColumns(node->GetItem()) )
3961 return false;
3962 }
3963
3964 if ( m_currentCol == NULL || !m_currentColSetByKeyboard )
3965 {
3966 if ( forward )
3967 {
3968 m_currentCol = GetOwner()->GetColumnAt(1);
3969 m_currentColSetByKeyboard = true;
3970 RefreshRow(m_currentRow);
3971 return true;
3972 }
3973 else
3974 return false;
3975 }
3976
3977 int idx = GetOwner()->GetColumnIndex(m_currentCol) + (forward ? +1 : -1);
3978
3979 if ( idx >= (int)GetOwner()->GetColumnCount() )
3980 return false;
3981
3982 GetOwner()->EnsureVisible(m_currentRow, idx);
3983
3984 if ( idx < 1 )
3985 {
3986 // We are going to the left of the second column. Reset to whole-row
3987 // focus (which means first column would be edited).
3988 m_currentCol = NULL;
3989 RefreshRow(m_currentRow);
3990 return true;
3991 }
3992
3993 m_currentCol = GetOwner()->GetColumnAt(idx);
3994 m_currentColSetByKeyboard = true;
3995 RefreshRow(m_currentRow);
3996 return true;
3997 }
3998
3999 void wxDataViewMainWindow::OnMouse( wxMouseEvent &event )
4000 {
4001 if (event.GetEventType() == wxEVT_MOUSEWHEEL)
4002 {
4003 // let the base handle mouse wheel events.
4004 event.Skip();
4005 return;
4006 }
4007
4008 if(event.ButtonDown())
4009 {
4010 // Not skipping button down events would prevent the system from
4011 // setting focus to this window as most (all?) of them do by default,
4012 // so skip it to enable default handling.
4013 event.Skip();
4014 }
4015
4016 int x = event.GetX();
4017 int y = event.GetY();
4018 m_owner->CalcUnscrolledPosition( x, y, &x, &y );
4019 wxDataViewColumn *col = NULL;
4020
4021 int xpos = 0;
4022 unsigned int cols = GetOwner()->GetColumnCount();
4023 unsigned int i;
4024 for (i = 0; i < cols; i++)
4025 {
4026 wxDataViewColumn *c = GetOwner()->GetColumnAt( i );
4027 if (c->IsHidden())
4028 continue; // skip it!
4029
4030 if (x < xpos + c->GetWidth())
4031 {
4032 col = c;
4033 break;
4034 }
4035 xpos += c->GetWidth();
4036 }
4037
4038 wxDataViewModel* const model = GetModel();
4039
4040 const unsigned int current = GetLineAt( y );
4041 const wxDataViewItem item = GetItemByRow(current);
4042
4043 // Handle right clicking here, before everything else as context menu
4044 // events should be sent even when we click outside of any item, unlike all
4045 // the other ones.
4046 if (event.RightUp())
4047 {
4048 wxWindow *parent = GetParent();
4049 wxDataViewEvent le(wxEVT_COMMAND_DATAVIEW_ITEM_CONTEXT_MENU, parent->GetId());
4050 le.SetEventObject(parent);
4051 le.SetModel(model);
4052
4053 if ( item.IsOk() && col )
4054 {
4055 le.SetItem( item );
4056 le.SetColumn( col->GetModelColumn() );
4057 le.SetDataViewColumn( col );
4058 }
4059
4060 parent->ProcessWindowEvent(le);
4061 return;
4062 }
4063
4064 // Check if we clicked outside the item area.
4065 if ((current >= GetRowCount()) || !col)
4066 {
4067 // Follow Windows convention here: clicking either left or right (but
4068 // not middle) button clears the existing selection.
4069 if (m_owner && (event.LeftDown() || event.RightDown()))
4070 {
4071 if (!GetSelections().empty())
4072 {
4073 m_owner->UnselectAll();
4074 SendSelectionChangedEvent(wxDataViewItem());
4075 }
4076 }
4077 event.Skip();
4078 return;
4079 }
4080
4081 wxDataViewRenderer *cell = col->GetRenderer();
4082 wxDataViewColumn* const
4083 expander = GetExpanderColumnOrFirstOne(GetOwner());
4084
4085 // Test whether the mouse is hovering over the expander (a.k.a tree "+"
4086 // button) and also determine the offset of the real cell start, skipping
4087 // the indentation and the expander itself.
4088 bool hoverOverExpander = false;
4089 int itemOffset = 0;
4090 if ((!IsList()) && (expander == col))
4091 {
4092 wxDataViewTreeNode * node = GetTreeNodeByRow(current);
4093
4094 int indent = node->GetIndentLevel();
4095 itemOffset = GetOwner()->GetIndent()*indent;
4096
4097 if ( node->HasChildren() )
4098 {
4099 // we make the rectangle we are looking in a bit bigger than the actual
4100 // visual expander so the user can hit that little thing reliably
4101 wxRect rect(itemOffset,
4102 GetLineStart( current ) + (GetLineHeight(current) - m_lineHeight)/2,
4103 m_lineHeight, m_lineHeight);
4104
4105 if( rect.Contains(x, y) )
4106 {
4107 // So the mouse is over the expander
4108 hoverOverExpander = true;
4109 if (m_underMouse && m_underMouse != node)
4110 {
4111 // wxLogMessage("Undo the row: %d", GetRowByItem(m_underMouse->GetItem()));
4112 RefreshRow(GetRowByItem(m_underMouse->GetItem()));
4113 }
4114 if (m_underMouse != node)
4115 {
4116 // wxLogMessage("Do the row: %d", current);
4117 RefreshRow(current);
4118 }
4119 m_underMouse = node;
4120 }
4121 }
4122
4123 // Account for the expander as well, even if this item doesn't have it,
4124 // its parent does so it still counts for the offset.
4125 itemOffset += m_lineHeight;
4126 }
4127 if (!hoverOverExpander)
4128 {
4129 if (m_underMouse != NULL)
4130 {
4131 // wxLogMessage("Undo the row: %d", GetRowByItem(m_underMouse->GetItem()));
4132 RefreshRow(GetRowByItem(m_underMouse->GetItem()));
4133 m_underMouse = NULL;
4134 }
4135 }
4136
4137 #if wxUSE_DRAG_AND_DROP
4138 if (event.Dragging())
4139 {
4140 if (m_dragCount == 0)
4141 {
4142 // we have to report the raw, physical coords as we want to be
4143 // able to call HitTest(event.m_pointDrag) from the user code to
4144 // get the item being dragged
4145 m_dragStart = event.GetPosition();
4146 }
4147
4148 m_dragCount++;
4149
4150 if (m_dragCount != 3)
4151 return;
4152
4153 if (event.LeftIsDown())
4154 {
4155 m_owner->CalcUnscrolledPosition( m_dragStart.x, m_dragStart.y,
4156 &m_dragStart.x, &m_dragStart.y );
4157 unsigned int drag_item_row = GetLineAt( m_dragStart.y );
4158 wxDataViewItem itemDragged = GetItemByRow( drag_item_row );
4159
4160 // Notify cell about drag
4161 wxDataViewEvent event( wxEVT_COMMAND_DATAVIEW_ITEM_BEGIN_DRAG, m_owner->GetId() );
4162 event.SetEventObject( m_owner );
4163 event.SetItem( itemDragged );
4164 event.SetModel( model );
4165 if (!m_owner->HandleWindowEvent( event ))
4166 return;
4167
4168 if (!event.IsAllowed())
4169 return;
4170
4171 wxDataObject *obj = event.GetDataObject();
4172 if (!obj)
4173 return;
4174
4175 wxDataViewDropSource drag( this, drag_item_row );
4176 drag.SetData( *obj );
4177 /* wxDragResult res = */ drag.DoDragDrop(event.GetDragFlags());
4178 delete obj;
4179 }
4180 return;
4181 }
4182 else
4183 {
4184 m_dragCount = 0;
4185 }
4186 #endif // wxUSE_DRAG_AND_DROP
4187
4188 bool simulateClick = false;
4189
4190 if (event.ButtonDClick())
4191 {
4192 m_renameTimer->Stop();
4193 m_lastOnSame = false;
4194 }
4195
4196 bool ignore_other_columns =
4197 ((expander != col) &&
4198 (model->IsContainer(item)) &&
4199 (!model->HasContainerColumns(item)));
4200
4201 if (event.LeftDClick())
4202 {
4203 if(hoverOverExpander)
4204 {
4205 // a double click on the expander will be converted into a "simulated" normal click
4206 simulateClick = true;
4207 }
4208 else if ( current == m_lineLastClicked )
4209 {
4210 wxWindow *parent = GetParent();
4211 wxDataViewEvent le(wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED, parent->GetId());
4212 le.SetItem( item );
4213 le.SetColumn( col->GetModelColumn() );
4214 le.SetDataViewColumn( col );
4215 le.SetEventObject(parent);
4216 le.SetModel(GetModel());
4217
4218 parent->ProcessWindowEvent(le);
4219 return;
4220 }
4221 else
4222 {
4223 // The first click was on another item, so don't interpret this as
4224 // a double click, but as a simple click instead
4225 simulateClick = true;
4226 }
4227 }
4228
4229 if (event.LeftUp() && !hoverOverExpander)
4230 {
4231 if (m_lineSelectSingleOnUp != (unsigned int)-1)
4232 {
4233 // select single line
4234 SelectAllRows( false );
4235 SelectRow( m_lineSelectSingleOnUp, true );
4236 SendSelectionChangedEvent( GetItemByRow(m_lineSelectSingleOnUp) );
4237 }
4238
4239 // If the user click the expander, we do not do editing even if the column
4240 // with expander are editable
4241 if (m_lastOnSame && !ignore_other_columns)
4242 {
4243 if ((col == m_currentCol) && (current == m_currentRow) &&
4244 IsCellEditableInMode(item, col, wxDATAVIEW_CELL_EDITABLE) )
4245 {
4246 m_renameTimer->Start( 100, true );
4247 }
4248 }
4249
4250 m_lastOnSame = false;
4251 m_lineSelectSingleOnUp = (unsigned int)-1;
4252 }
4253 else if(!event.LeftUp())
4254 {
4255 // This is necessary, because after a DnD operation in
4256 // from and to ourself, the up event is swallowed by the
4257 // DnD code. So on next non-up event (which means here and
4258 // now) m_lineSelectSingleOnUp should be reset.
4259 m_lineSelectSingleOnUp = (unsigned int)-1;
4260 }
4261
4262 if (event.RightDown())
4263 {
4264 m_lineBeforeLastClicked = m_lineLastClicked;
4265 m_lineLastClicked = current;
4266
4267 // If the item is already selected, do not update the selection.
4268 // Multi-selections should not be cleared if a selected item is clicked.
4269 if (!IsRowSelected(current))
4270 {
4271 SelectAllRows(false);
4272 const unsigned oldCurrent = m_currentRow;
4273 ChangeCurrentRow(current);
4274 SelectRow(m_currentRow,true);
4275 RefreshRow(oldCurrent);
4276 SendSelectionChangedEvent(GetItemByRow( m_currentRow ) );
4277 }
4278 }
4279 else if (event.MiddleDown())
4280 {
4281 }
4282
4283 if((event.LeftDown() || simulateClick) && hoverOverExpander)
4284 {
4285 wxDataViewTreeNode* node = GetTreeNodeByRow(current);
4286
4287 // hoverOverExpander being true tells us that our node must be
4288 // valid and have children.
4289 // So we don't need any extra checks.
4290 if( node->IsOpen() )
4291 Collapse(current);
4292 else
4293 Expand(current);
4294 }
4295 else if ((event.LeftDown() || simulateClick) && !hoverOverExpander)
4296 {
4297 m_lineBeforeLastClicked = m_lineLastClicked;
4298 m_lineLastClicked = current;
4299
4300 unsigned int oldCurrentRow = m_currentRow;
4301 bool oldWasSelected = IsRowSelected(m_currentRow);
4302
4303 bool cmdModifierDown = event.CmdDown();
4304 if ( IsSingleSel() || !(cmdModifierDown || event.ShiftDown()) )
4305 {
4306 if ( IsSingleSel() || !IsRowSelected(current) )
4307 {
4308 SelectAllRows( false );
4309 ChangeCurrentRow(current);
4310 SelectRow(m_currentRow,true);
4311 SendSelectionChangedEvent(GetItemByRow( m_currentRow ) );
4312 }
4313 else // multi sel & current is highlighted & no mod keys
4314 {
4315 m_lineSelectSingleOnUp = current;
4316 ChangeCurrentRow(current); // change focus
4317 }
4318 }
4319 else // multi sel & either ctrl or shift is down
4320 {
4321 if (cmdModifierDown)
4322 {
4323 ChangeCurrentRow(current);
4324 ReverseRowSelection(m_currentRow);
4325 SendSelectionChangedEvent(GetItemByRow(m_currentRow));
4326 }
4327 else if (event.ShiftDown())
4328 {
4329 ChangeCurrentRow(current);
4330
4331 unsigned int lineFrom = oldCurrentRow,
4332 lineTo = current;
4333
4334 if ( lineTo < lineFrom )
4335 {
4336 lineTo = lineFrom;
4337 lineFrom = m_currentRow;
4338 }
4339
4340 SelectRows(lineFrom, lineTo, true);
4341 SendSelectionChangedEvent(GetItemByRow(m_selection[0]) );
4342 }
4343 else // !ctrl, !shift
4344 {
4345 // test in the enclosing if should make it impossible
4346 wxFAIL_MSG( wxT("how did we get here?") );
4347 }
4348 }
4349
4350 if (m_currentRow != oldCurrentRow)
4351 RefreshRow( oldCurrentRow );
4352
4353 wxDataViewColumn *oldCurrentCol = m_currentCol;
4354
4355 // Update selection here...
4356 m_currentCol = col;
4357 m_currentColSetByKeyboard = false;
4358
4359 // This flag is used to decide whether we should start editing the item
4360 // label. We do it if the user clicks twice (but not double clicks,
4361 // i.e. simulateClick is false) on the same item but not if the click
4362 // was used for something else already, e.g. selecting the item (so it
4363 // must have been already selected) or giving the focus to the control
4364 // (so it must have had focus already).
4365 m_lastOnSame = !simulateClick && ((col == oldCurrentCol) &&
4366 (current == oldCurrentRow)) && oldWasSelected &&
4367 HasFocus();
4368
4369 // Call ActivateCell() after everything else as under GTK+
4370 if ( IsCellEditableInMode(item, col, wxDATAVIEW_CELL_ACTIVATABLE) )
4371 {
4372 // notify cell about click
4373 cell->PrepareForItem(model, item, col->GetModelColumn());
4374
4375 wxRect cell_rect( xpos + itemOffset,
4376 GetLineStart( current ),
4377 col->GetWidth() - itemOffset,
4378 GetLineHeight( current ) );
4379
4380 // Report position relative to the cell's custom area, i.e.
4381 // no the entire space as given by the control but the one
4382 // used by the renderer after calculation of alignment etc.
4383
4384 // adjust the rectangle ourselves to account for the alignment
4385 wxRect rectItem = cell_rect;
4386 const int align = cell->GetAlignment();
4387 if ( align != wxDVR_DEFAULT_ALIGNMENT )
4388 {
4389 const wxSize size = cell->GetSize();
4390
4391 if ( size.x >= 0 && size.x < cell_rect.width )
4392 {
4393 if ( align & wxALIGN_CENTER_HORIZONTAL )
4394 rectItem.x += (cell_rect.width - size.x)/2;
4395 else if ( align & wxALIGN_RIGHT )
4396 rectItem.x += cell_rect.width - size.x;
4397 // else: wxALIGN_LEFT is the default
4398 }
4399
4400 if ( size.y >= 0 && size.y < cell_rect.height )
4401 {
4402 if ( align & wxALIGN_CENTER_VERTICAL )
4403 rectItem.y += (cell_rect.height - size.y)/2;
4404 else if ( align & wxALIGN_BOTTOM )
4405 rectItem.y += cell_rect.height - size.y;
4406 // else: wxALIGN_TOP is the default
4407 }
4408 }
4409
4410 wxMouseEvent event2(event);
4411 event2.m_x -= rectItem.x;
4412 event2.m_y -= rectItem.y;
4413 m_owner->CalcUnscrolledPosition(event2.m_x, event2.m_y, &event2.m_x, &event2.m_y);
4414
4415 /* ignore ret */ cell->WXActivateCell
4416 (
4417 cell_rect,
4418 model,
4419 item,
4420 col->GetModelColumn(),
4421 &event2
4422 );
4423 }
4424 }
4425 }
4426
4427 void wxDataViewMainWindow::OnSetFocus( wxFocusEvent &event )
4428 {
4429 m_hasFocus = true;
4430
4431 if (HasCurrentRow())
4432 Refresh();
4433
4434 event.Skip();
4435 }
4436
4437 void wxDataViewMainWindow::OnKillFocus( wxFocusEvent &event )
4438 {
4439 m_hasFocus = false;
4440
4441 if (HasCurrentRow())
4442 Refresh();
4443
4444 event.Skip();
4445 }
4446
4447 void wxDataViewMainWindow::OnColumnsCountChanged()
4448 {
4449 int editableCount = 0;
4450
4451 const unsigned cols = GetOwner()->GetColumnCount();
4452 for ( unsigned i = 0; i < cols; i++ )
4453 {
4454 wxDataViewColumn *c = GetOwner()->GetColumnAt(i);
4455 if ( c->IsHidden() )
4456 continue;
4457 if ( c->GetRenderer()->GetMode() != wxDATAVIEW_CELL_INERT )
4458 editableCount++;
4459 }
4460
4461 m_useCellFocus = (editableCount > 1);
4462
4463 UpdateDisplay();
4464 }
4465
4466 //-----------------------------------------------------------------------------
4467 // wxDataViewCtrl
4468 //-----------------------------------------------------------------------------
4469
4470 WX_DEFINE_LIST(wxDataViewColumnList)
4471
4472 IMPLEMENT_DYNAMIC_CLASS(wxDataViewCtrl, wxDataViewCtrlBase)
4473 BEGIN_EVENT_TABLE(wxDataViewCtrl, wxDataViewCtrlBase)
4474 EVT_SIZE(wxDataViewCtrl::OnSize)
4475 END_EVENT_TABLE()
4476
4477 wxDataViewCtrl::~wxDataViewCtrl()
4478 {
4479 if (m_notifier)
4480 GetModel()->RemoveNotifier( m_notifier );
4481
4482 m_cols.Clear();
4483 m_colsBestWidths.clear();
4484 }
4485
4486 void wxDataViewCtrl::Init()
4487 {
4488 m_cols.DeleteContents(true);
4489 m_notifier = NULL;
4490
4491 // No sorting column at start
4492 m_sortingColumnIdx = wxNOT_FOUND;
4493
4494 m_headerArea = NULL;
4495 m_clientArea = NULL;
4496
4497 m_colsDirty = false;
4498 }
4499
4500 bool wxDataViewCtrl::Create(wxWindow *parent,
4501 wxWindowID id,
4502 const wxPoint& pos,
4503 const wxSize& size,
4504 long style,
4505 const wxValidator& validator,
4506 const wxString& name)
4507 {
4508 // if ( (style & wxBORDER_MASK) == 0)
4509 // style |= wxBORDER_SUNKEN;
4510
4511 Init();
4512
4513 if (!wxControl::Create( parent, id, pos, size,
4514 style | wxScrolledWindowStyle, validator, name))
4515 return false;
4516
4517 SetInitialSize(size);
4518
4519 #ifdef __WXMAC__
4520 MacSetClipChildren( true );
4521 #endif
4522
4523 m_clientArea = new wxDataViewMainWindow( this, wxID_ANY );
4524
4525 // We use the cursor keys for moving the selection, not scrolling, so call
4526 // this method to ensure wxScrollHelperEvtHandler doesn't catch all
4527 // keyboard events forwarded to us from wxListMainWindow.
4528 DisableKeyboardScrolling();
4529
4530 if (HasFlag(wxDV_NO_HEADER))
4531 m_headerArea = NULL;
4532 else
4533 m_headerArea = new wxDataViewHeaderWindow(this);
4534
4535 SetTargetWindow( m_clientArea );
4536
4537 wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL );
4538 if (m_headerArea)
4539 sizer->Add( m_headerArea, 0, wxGROW );
4540 sizer->Add( m_clientArea, 1, wxGROW );
4541 SetSizer( sizer );
4542
4543 return true;
4544 }
4545
4546 wxBorder wxDataViewCtrl::GetDefaultBorder() const
4547 {
4548 return wxBORDER_THEME;
4549 }
4550
4551 #ifdef __WXMSW__
4552 WXLRESULT wxDataViewCtrl::MSWWindowProc(WXUINT nMsg,
4553 WXWPARAM wParam,
4554 WXLPARAM lParam)
4555 {
4556 WXLRESULT rc = wxDataViewCtrlBase::MSWWindowProc(nMsg, wParam, lParam);
4557
4558 #ifndef __WXWINCE__
4559 // we need to process arrows ourselves for scrolling
4560 if ( nMsg == WM_GETDLGCODE )
4561 {
4562 rc |= DLGC_WANTARROWS;
4563 }
4564 #endif
4565
4566 return rc;
4567 }
4568 #endif
4569
4570 wxSize wxDataViewCtrl::GetSizeAvailableForScrollTarget(const wxSize& size)
4571 {
4572 wxSize newsize = size;
4573 if (!HasFlag(wxDV_NO_HEADER) && (m_headerArea))
4574 newsize.y -= m_headerArea->GetSize().y;
4575
4576 return newsize;
4577 }
4578
4579 void wxDataViewCtrl::OnSize( wxSizeEvent &WXUNUSED(event) )
4580 {
4581 // We need to override OnSize so that our scrolled
4582 // window a) does call Layout() to use sizers for
4583 // positioning the controls but b) does not query
4584 // the sizer for their size and use that for setting
4585 // the scrollable area as set that ourselves by
4586 // calling SetScrollbar() further down.
4587
4588 Layout();
4589
4590 AdjustScrollbars();
4591
4592 // We must redraw the headers if their height changed. Normally this
4593 // shouldn't happen as the control shouldn't let itself be resized beneath
4594 // its minimal height but avoid the display artefacts that appear if it
4595 // does happen, e.g. because there is really not enough vertical space.
4596 if ( !HasFlag(wxDV_NO_HEADER) && m_headerArea &&
4597 m_headerArea->GetSize().y <= m_headerArea->GetBestSize(). y )
4598 {
4599 m_headerArea->Refresh();
4600 }
4601 }
4602
4603 void wxDataViewCtrl::SetFocus()
4604 {
4605 if (m_clientArea)
4606 m_clientArea->SetFocus();
4607 }
4608
4609 bool wxDataViewCtrl::SetFont(const wxFont & font)
4610 {
4611 if (!wxControl::SetFont(font))
4612 return false;
4613
4614 if (m_headerArea)
4615 m_headerArea->SetFont(font);
4616
4617 if (m_clientArea)
4618 {
4619 m_clientArea->SetFont(font);
4620 m_clientArea->SetRowHeight(m_clientArea->GetDefaultRowHeight());
4621 }
4622
4623 if (m_headerArea || m_clientArea)
4624 {
4625 InvalidateColBestWidths();
4626 Layout();
4627 }
4628
4629 return true;
4630 }
4631
4632
4633
4634 bool wxDataViewCtrl::AssociateModel( wxDataViewModel *model )
4635 {
4636 if (!wxDataViewCtrlBase::AssociateModel( model ))
4637 return false;
4638
4639 if (model)
4640 {
4641 m_notifier = new wxGenericDataViewModelNotifier( m_clientArea );
4642 model->AddNotifier( m_notifier );
4643 }
4644 else if (m_notifier)
4645 {
4646 m_notifier->Cleared();
4647 m_notifier = NULL;
4648 }
4649
4650 m_clientArea->DestroyTree();
4651
4652 if (model)
4653 {
4654 m_clientArea->BuildTree(model);
4655 }
4656
4657 m_clientArea->UpdateDisplay();
4658
4659 return true;
4660 }
4661
4662 #if wxUSE_DRAG_AND_DROP
4663
4664 bool wxDataViewCtrl::EnableDragSource( const wxDataFormat &format )
4665 {
4666 return m_clientArea->EnableDragSource( format );
4667 }
4668
4669 bool wxDataViewCtrl::EnableDropTarget( const wxDataFormat &format )
4670 {
4671 return m_clientArea->EnableDropTarget( format );
4672 }
4673
4674 #endif // wxUSE_DRAG_AND_DROP
4675
4676 bool wxDataViewCtrl::AppendColumn( wxDataViewColumn *col )
4677 {
4678 if (!wxDataViewCtrlBase::AppendColumn(col))
4679 return false;
4680
4681 m_cols.Append( col );
4682 m_colsBestWidths.push_back(CachedColWidthInfo());
4683 OnColumnsCountChanged();
4684 return true;
4685 }
4686
4687 bool wxDataViewCtrl::PrependColumn( wxDataViewColumn *col )
4688 {
4689 if (!wxDataViewCtrlBase::PrependColumn(col))
4690 return false;
4691
4692 m_cols.Insert( col );
4693 m_colsBestWidths.insert(m_colsBestWidths.begin(), CachedColWidthInfo());
4694 OnColumnsCountChanged();
4695 return true;
4696 }
4697
4698 bool wxDataViewCtrl::InsertColumn( unsigned int pos, wxDataViewColumn *col )
4699 {
4700 if (!wxDataViewCtrlBase::InsertColumn(pos,col))
4701 return false;
4702
4703 m_cols.Insert( pos, col );
4704 m_colsBestWidths.insert(m_colsBestWidths.begin() + pos, CachedColWidthInfo());
4705 OnColumnsCountChanged();
4706 return true;
4707 }
4708
4709 void wxDataViewCtrl::OnColumnChange(unsigned int idx)
4710 {
4711 if ( m_headerArea )
4712 m_headerArea->UpdateColumn(idx);
4713
4714 m_clientArea->UpdateDisplay();
4715 }
4716
4717 void wxDataViewCtrl::OnColumnsCountChanged()
4718 {
4719 if (m_headerArea)
4720 m_headerArea->SetColumnCount(GetColumnCount());
4721
4722 m_clientArea->OnColumnsCountChanged();
4723 }
4724
4725 void wxDataViewCtrl::DoSetExpanderColumn()
4726 {
4727 m_clientArea->UpdateDisplay();
4728 }
4729
4730 void wxDataViewCtrl::DoSetIndent()
4731 {
4732 m_clientArea->UpdateDisplay();
4733 }
4734
4735 unsigned int wxDataViewCtrl::GetColumnCount() const
4736 {
4737 return m_cols.GetCount();
4738 }
4739
4740 bool wxDataViewCtrl::SetRowHeight( int lineHeight )
4741 {
4742 if ( !m_clientArea )
4743 return false;
4744
4745 m_clientArea->SetRowHeight(lineHeight);
4746
4747 return true;
4748 }
4749
4750 wxDataViewColumn* wxDataViewCtrl::GetColumn( unsigned int idx ) const
4751 {
4752 return m_cols[idx];
4753 }
4754
4755 wxDataViewColumn *wxDataViewCtrl::GetColumnAt(unsigned int pos) const
4756 {
4757 // columns can't be reordered if there is no header window which allows
4758 // to do this
4759 const unsigned idx = m_headerArea ? m_headerArea->GetColumnsOrder()[pos]
4760 : pos;
4761
4762 return GetColumn(idx);
4763 }
4764
4765 int wxDataViewCtrl::GetColumnIndex(const wxDataViewColumn *column) const
4766 {
4767 const unsigned count = m_cols.size();
4768 for ( unsigned n = 0; n < count; n++ )
4769 {
4770 if ( m_cols[n] == column )
4771 return n;
4772 }
4773
4774 return wxNOT_FOUND;
4775 }
4776
4777 unsigned int wxDataViewCtrl::GetBestColumnWidth(int idx) const
4778 {
4779 if ( m_colsBestWidths[idx].width != 0 )
4780 return m_colsBestWidths[idx].width;
4781
4782 const int count = m_clientArea->GetRowCount();
4783 wxDataViewColumn *column = GetColumn(idx);
4784 wxDataViewRenderer *renderer =
4785 const_cast<wxDataViewRenderer*>(column->GetRenderer());
4786
4787 class MaxWidthCalculator
4788 {
4789 public:
4790 MaxWidthCalculator(const wxDataViewCtrl *dvc,
4791 wxDataViewMainWindow *clientArea,
4792 wxDataViewRenderer *renderer,
4793 const wxDataViewModel *model,
4794 unsigned column,
4795 int expanderSize)
4796 : m_width(0),
4797 m_dvc(dvc),
4798 m_clientArea(clientArea),
4799 m_renderer(renderer),
4800 m_model(model),
4801 m_column(column),
4802 m_expanderSize(expanderSize)
4803
4804 {
4805 m_isExpanderCol =
4806 !clientArea->IsList() &&
4807 (column == 0 ||
4808 GetExpanderColumnOrFirstOne(const_cast<wxDataViewCtrl*>(dvc)) == dvc->GetColumnAt(column));
4809 }
4810
4811 void UpdateWithWidth(int width)
4812 {
4813 m_width = wxMax(m_width, width);
4814 }
4815
4816 void UpdateWithRow(int row)
4817 {
4818 int indent = 0;
4819 wxDataViewItem item;
4820
4821 if ( m_isExpanderCol )
4822 {
4823 wxDataViewTreeNode *node = m_clientArea->GetTreeNodeByRow(row);
4824 item = node->GetItem();
4825 indent = m_dvc->GetIndent() * node->GetIndentLevel() + m_expanderSize;
4826 }
4827 else
4828 {
4829 item = m_clientArea->GetItemByRow(row);
4830 }
4831
4832 m_renderer->PrepareForItem(m_model, item, m_column);
4833 m_width = wxMax(m_width, m_renderer->GetSize().x + indent);
4834 }
4835
4836 int GetMaxWidth() const { return m_width; }
4837
4838 private:
4839 int m_width;
4840 const wxDataViewCtrl *m_dvc;
4841 wxDataViewMainWindow *m_clientArea;
4842 wxDataViewRenderer *m_renderer;
4843 const wxDataViewModel *m_model;
4844 unsigned m_column;
4845 bool m_isExpanderCol;
4846 int m_expanderSize;
4847 };
4848
4849 MaxWidthCalculator calculator(this, m_clientArea, renderer,
4850 GetModel(), column->GetModelColumn(),
4851 m_clientArea->GetRowHeight());
4852
4853 calculator.UpdateWithWidth(column->GetMinWidth());
4854
4855 if ( m_headerArea )
4856 calculator.UpdateWithWidth(m_headerArea->GetColumnTitleWidth(*column));
4857
4858 // The code below deserves some explanation. For very large controls, we
4859 // simply can't afford to calculate sizes for all items, it takes too
4860 // long. So the best we can do is to check the first and the last N/2
4861 // items in the control for some sufficiently large N and calculate best
4862 // sizes from that. That can result in the calculated best width being too
4863 // small for some outliers, but it's better to get slightly imperfect
4864 // result than to wait several seconds after every update. To avoid highly
4865 // visible miscalculations, we also include all currently visible items
4866 // no matter what. Finally, the value of N is determined dynamically by
4867 // measuring how much time we spent on the determining item widths so far.
4868
4869 #if wxUSE_STOPWATCH
4870 int top_part_end = count;
4871 static const long CALC_TIMEOUT = 20/*ms*/;
4872 // don't call wxStopWatch::Time() too often
4873 static const unsigned CALC_CHECK_FREQ = 100;
4874 wxStopWatch timer;
4875 #else
4876 // use some hard-coded limit, that's the best we can do without timer
4877 int top_part_end = wxMin(500, count);
4878 #endif // wxUSE_STOPWATCH/!wxUSE_STOPWATCH
4879
4880 int row = 0;
4881
4882 for ( row = 0; row < top_part_end; row++ )
4883 {
4884 #if wxUSE_STOPWATCH
4885 if ( row % CALC_CHECK_FREQ == CALC_CHECK_FREQ-1 &&
4886 timer.Time() > CALC_TIMEOUT )
4887 break;
4888 #endif // wxUSE_STOPWATCH
4889 calculator.UpdateWithRow(row);
4890 }
4891
4892 // row is the first unmeasured item now; that's our value of N/2
4893
4894 if ( row < count )
4895 {
4896 top_part_end = row;
4897
4898 // add bottom N/2 items now:
4899 const int bottom_part_start = wxMax(row, count - row);
4900 for ( row = bottom_part_start; row < count; row++ )
4901 {
4902 calculator.UpdateWithRow(row);
4903 }
4904
4905 // finally, include currently visible items in the calculation:
4906 const wxPoint origin = CalcUnscrolledPosition(wxPoint(0, 0));
4907 int first_visible = m_clientArea->GetLineAt(origin.y);
4908 int last_visible = m_clientArea->GetLineAt(origin.y + GetClientSize().y);
4909
4910 first_visible = wxMax(first_visible, top_part_end);
4911 last_visible = wxMin(bottom_part_start, last_visible);
4912
4913 for ( row = first_visible; row < last_visible; row++ )
4914 {
4915 calculator.UpdateWithRow(row);
4916 }
4917
4918 wxLogTrace("dataview",
4919 "determined best size from %d top, %d bottom plus %d more visible items out of %d total",
4920 top_part_end,
4921 count - bottom_part_start,
4922 wxMax(0, last_visible - first_visible),
4923 count);
4924 }
4925
4926 int max_width = calculator.GetMaxWidth();
4927 if ( max_width > 0 )
4928 max_width += 2 * PADDING_RIGHTLEFT;
4929
4930 const_cast<wxDataViewCtrl*>(this)->m_colsBestWidths[idx].width = max_width;
4931 return max_width;
4932 }
4933
4934 void wxDataViewCtrl::ColumnMoved(wxDataViewColumn * WXUNUSED(col),
4935 unsigned int WXUNUSED(new_pos))
4936 {
4937 // do _not_ reorder m_cols elements here, they should always be in the
4938 // order in which columns were added, we only display the columns in
4939 // different order
4940 m_clientArea->UpdateDisplay();
4941 }
4942
4943 bool wxDataViewCtrl::DeleteColumn( wxDataViewColumn *column )
4944 {
4945 wxDataViewColumnList::compatibility_iterator ret = m_cols.Find( column );
4946 if (!ret)
4947 return false;
4948
4949 m_colsBestWidths.erase(m_colsBestWidths.begin() + GetColumnIndex(column));
4950 m_cols.Erase(ret);
4951
4952 if ( m_clientArea->GetCurrentColumn() == column )
4953 m_clientArea->ClearCurrentColumn();
4954
4955 OnColumnsCountChanged();
4956
4957 return true;
4958 }
4959
4960 bool wxDataViewCtrl::ClearColumns()
4961 {
4962 SetExpanderColumn(NULL);
4963 m_cols.Clear();
4964 m_colsBestWidths.clear();
4965
4966 m_clientArea->ClearCurrentColumn();
4967
4968 OnColumnsCountChanged();
4969
4970 return true;
4971 }
4972
4973 void wxDataViewCtrl::InvalidateColBestWidth(int idx)
4974 {
4975 m_colsBestWidths[idx].width = 0;
4976 m_colsBestWidths[idx].dirty = true;
4977 m_colsDirty = true;
4978 }
4979
4980 void wxDataViewCtrl::InvalidateColBestWidths()
4981 {
4982 // mark all columns as dirty:
4983 m_colsBestWidths.clear();
4984 m_colsBestWidths.resize(m_cols.size());
4985 m_colsDirty = true;
4986 }
4987
4988 void wxDataViewCtrl::UpdateColWidths()
4989 {
4990 m_colsDirty = false;
4991
4992 if ( !m_headerArea )
4993 return;
4994
4995 const unsigned len = m_colsBestWidths.size();
4996 for ( unsigned i = 0; i < len; i++ )
4997 {
4998 // Note that we have to have an explicit 'dirty' flag here instead of
4999 // checking if the width==0, as is done in GetBestColumnWidth().
5000 //
5001 // Testing width==0 wouldn't work correctly if some code called
5002 // GetWidth() after col. width invalidation but before
5003 // wxDataViewCtrl::UpdateColWidths() was called at idle time. This
5004 // would result in the header's column width getting out of sync with
5005 // the control itself.
5006 if ( m_colsBestWidths[i].dirty )
5007 {
5008 m_headerArea->UpdateColumn(i);
5009 m_colsBestWidths[i].dirty = false;
5010 }
5011 }
5012 }
5013
5014 void wxDataViewCtrl::OnInternalIdle()
5015 {
5016 wxDataViewCtrlBase::OnInternalIdle();
5017
5018 if ( m_colsDirty )
5019 UpdateColWidths();
5020 }
5021
5022 int wxDataViewCtrl::GetColumnPosition( const wxDataViewColumn *column ) const
5023 {
5024 unsigned int len = GetColumnCount();
5025 for ( unsigned int i = 0; i < len; i++ )
5026 {
5027 wxDataViewColumn * col = GetColumnAt(i);
5028 if (column==col)
5029 return i;
5030 }
5031
5032 return wxNOT_FOUND;
5033 }
5034
5035 wxDataViewColumn *wxDataViewCtrl::GetSortingColumn() const
5036 {
5037 return m_sortingColumnIdx == wxNOT_FOUND ? NULL
5038 : GetColumn(m_sortingColumnIdx);
5039 }
5040
5041 wxDataViewItem wxDataViewCtrl::DoGetCurrentItem() const
5042 {
5043 return GetItemByRow(m_clientArea->GetCurrentRow());
5044 }
5045
5046 void wxDataViewCtrl::DoSetCurrentItem(const wxDataViewItem& item)
5047 {
5048 const int row = m_clientArea->GetRowByItem(item);
5049
5050 const unsigned oldCurrent = m_clientArea->GetCurrentRow();
5051 if ( static_cast<unsigned>(row) != oldCurrent )
5052 {
5053 m_clientArea->ChangeCurrentRow(row);
5054 m_clientArea->RefreshRow(oldCurrent);
5055 m_clientArea->RefreshRow(row);
5056 }
5057 }
5058
5059 wxDataViewColumn *wxDataViewCtrl::GetCurrentColumn() const
5060 {
5061 return m_clientArea->GetCurrentColumn();
5062 }
5063
5064 int wxDataViewCtrl::GetSelectedItemsCount() const
5065 {
5066 return m_clientArea->GetSelections().size();
5067 }
5068
5069 int wxDataViewCtrl::GetSelections( wxDataViewItemArray & sel ) const
5070 {
5071 sel.Empty();
5072 const wxDataViewSelection& selections = m_clientArea->GetSelections();
5073
5074 const size_t len = selections.size();
5075 for ( size_t i = 0; i < len; i++ )
5076 {
5077 wxDataViewItem item = m_clientArea->GetItemByRow(selections[i]);
5078 if ( item.IsOk() )
5079 {
5080 sel.Add(item);
5081 }
5082 else
5083 {
5084 wxFAIL_MSG( "invalid item in selection - bad internal state" );
5085 }
5086 }
5087
5088 return sel.size();
5089 }
5090
5091 void wxDataViewCtrl::SetSelections( const wxDataViewItemArray & sel )
5092 {
5093 wxDataViewSelection selection(wxDataViewSelectionCmp);
5094
5095 wxDataViewItem last_parent;
5096
5097 int len = sel.GetCount();
5098 for( int i = 0; i < len; i ++ )
5099 {
5100 wxDataViewItem item = sel[i];
5101 wxDataViewItem parent = GetModel()->GetParent( item );
5102 if (parent)
5103 {
5104 if (parent != last_parent)
5105 ExpandAncestors(item);
5106 }
5107
5108 last_parent = parent;
5109 int row = m_clientArea->GetRowByItem( item );
5110 if( row >= 0 )
5111 selection.Add( static_cast<unsigned int>(row) );
5112 }
5113
5114 m_clientArea->SetSelections( selection );
5115 }
5116
5117 void wxDataViewCtrl::Select( const wxDataViewItem & item )
5118 {
5119 ExpandAncestors( item );
5120
5121 int row = m_clientArea->GetRowByItem( item );
5122 if( row >= 0 )
5123 {
5124 // Unselect all rows before select another in the single select mode
5125 if (m_clientArea->IsSingleSel())
5126 m_clientArea->SelectAllRows(false);
5127
5128 m_clientArea->SelectRow(row, true);
5129
5130 // Also set focus to the selected item
5131 m_clientArea->ChangeCurrentRow( row );
5132 }
5133 }
5134
5135 void wxDataViewCtrl::Unselect( const wxDataViewItem & item )
5136 {
5137 int row = m_clientArea->GetRowByItem( item );
5138 if( row >= 0 )
5139 m_clientArea->SelectRow(row, false);
5140 }
5141
5142 bool wxDataViewCtrl::IsSelected( const wxDataViewItem & item ) const
5143 {
5144 int row = m_clientArea->GetRowByItem( item );
5145 if( row >= 0 )
5146 {
5147 return m_clientArea->IsRowSelected(row);
5148 }
5149 return false;
5150 }
5151
5152 void wxDataViewCtrl::SetAlternateRowColour(const wxColour& colour)
5153 {
5154 m_alternateRowColour = colour;
5155 }
5156
5157 void wxDataViewCtrl::SelectAll()
5158 {
5159 m_clientArea->SelectAllRows(true);
5160 }
5161
5162 void wxDataViewCtrl::UnselectAll()
5163 {
5164 m_clientArea->SelectAllRows(false);
5165 }
5166
5167 void wxDataViewCtrl::EnsureVisible( int row, int column )
5168 {
5169 if( row < 0 )
5170 row = 0;
5171 if( row > (int) m_clientArea->GetRowCount() )
5172 row = m_clientArea->GetRowCount();
5173
5174 int first = m_clientArea->GetFirstVisibleRow();
5175 int last = m_clientArea->GetLastVisibleRow();
5176 if( row < first )
5177 m_clientArea->ScrollTo( row, column );
5178 else if( row > last )
5179 m_clientArea->ScrollTo( row - last + first, column );
5180 else
5181 m_clientArea->ScrollTo( first, column );
5182 }
5183
5184 void wxDataViewCtrl::EnsureVisible( const wxDataViewItem & item, const wxDataViewColumn * column )
5185 {
5186 ExpandAncestors( item );
5187
5188 m_clientArea->RecalculateDisplay();
5189
5190 int row = m_clientArea->GetRowByItem(item);
5191 if( row >= 0 )
5192 {
5193 if( column == NULL )
5194 EnsureVisible(row, -1);
5195 else
5196 EnsureVisible( row, GetColumnIndex(column) );
5197 }
5198
5199 }
5200
5201 void wxDataViewCtrl::HitTest( const wxPoint & point, wxDataViewItem & item,
5202 wxDataViewColumn* &column ) const
5203 {
5204 m_clientArea->HitTest(point, item, column);
5205 }
5206
5207 wxRect wxDataViewCtrl::GetItemRect( const wxDataViewItem & item,
5208 const wxDataViewColumn* column ) const
5209 {
5210 return m_clientArea->GetItemRect(item, column);
5211 }
5212
5213 wxDataViewItem wxDataViewCtrl::GetItemByRow( unsigned int row ) const
5214 {
5215 return m_clientArea->GetItemByRow( row );
5216 }
5217
5218 int wxDataViewCtrl::GetRowByItem( const wxDataViewItem & item ) const
5219 {
5220 return m_clientArea->GetRowByItem( item );
5221 }
5222
5223 void wxDataViewCtrl::Expand( const wxDataViewItem & item )
5224 {
5225 ExpandAncestors( item );
5226
5227 int row = m_clientArea->GetRowByItem( item );
5228 if (row != -1)
5229 {
5230 m_clientArea->Expand(row);
5231 InvalidateColBestWidths();
5232 }
5233 }
5234
5235 void wxDataViewCtrl::Collapse( const wxDataViewItem & item )
5236 {
5237 int row = m_clientArea->GetRowByItem( item );
5238 if (row != -1)
5239 {
5240 m_clientArea->Collapse(row);
5241 InvalidateColBestWidths();
5242 }
5243 }
5244
5245 bool wxDataViewCtrl::IsExpanded( const wxDataViewItem & item ) const
5246 {
5247 int row = m_clientArea->GetRowByItem( item );
5248 if (row != -1)
5249 return m_clientArea->IsExpanded(row);
5250 return false;
5251 }
5252
5253 void wxDataViewCtrl::EditItem(const wxDataViewItem& item, const wxDataViewColumn *column)
5254 {
5255 wxCHECK_RET( item.IsOk(), "invalid item" );
5256 wxCHECK_RET( column, "no column provided" );
5257
5258 m_clientArea->StartEditing(item, column);
5259 }
5260
5261 #endif // !wxUSE_GENERICDATAVIEWCTRL
5262
5263 #endif // wxUSE_DATAVIEWCTRL