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