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