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