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