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