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