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