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