2 // This file is part of the aMule Project.
4 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002 Merkur ( devs@emule-project.net / http://www.emule-project.net )
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include <wx/menu.h> // Needed for wxMenu
27 #include <wx/fileconf.h> // Needed for wxConfig
28 #include <wx/tokenzr.h> // Needed for wxStringTokenizer
29 #include <wx/imaglist.h> // Needed for wxImageList
31 #include <common/MuleDebug.h> // Needed for MULE_VALIDATE_
32 #include <common/StringFunctions.h> // Needed for StrToLong
34 #include <common/MenuIDs.h>
36 #include "MuleListCtrl.h" // Interface declarations
37 #include "GetTickCount.h" // Needed for GetTickCount()
38 #include "OtherFunctions.h"
42 #include "pixmaps/sort_dn.xpm"
43 #include "pixmaps/sort_up.xpm"
44 #include "pixmaps/sort_dnx2.xpm"
45 #include "pixmaps/sort_upx2.xpm"
50 const int COL_SIZE_MIN
= 10;
51 #elif defined(__WXMSW__) || defined(__WXMAC__) || defined(__WXCOCOA__)
52 const int COL_SIZE_MIN
= 0;
54 #error Need to define COL_SIZE_MIN for your OS
58 BEGIN_EVENT_TABLE(CMuleListCtrl
, MuleExtern::wxGenericListCtrl
)
59 EVT_LIST_COL_CLICK( -1, CMuleListCtrl::OnColumnLClick
)
60 EVT_LIST_COL_RIGHT_CLICK( -1, CMuleListCtrl::OnColumnRClick
)
61 EVT_LIST_ITEM_SELECTED(-1, CMuleListCtrl::OnItemSelected
)
62 EVT_LIST_DELETE_ITEM(-1, CMuleListCtrl::OnItemDeleted
)
63 EVT_LIST_DELETE_ALL_ITEMS(-1, CMuleListCtrl::OnAllItemsDeleted
)
64 EVT_CHAR( CMuleListCtrl::OnChar
)
65 EVT_MENU_RANGE(MP_LISTCOL_1
, MP_LISTCOL_15
, CMuleListCtrl::OnMenuSelected
)
66 EVT_MOUSEWHEEL(CMuleListCtrl::OnMouseWheel
)
70 //! Shared list of arrow-pixmaps
71 static wxImageList
imgList(16, 16, true, 0);
74 CMuleListCtrl::CMuleListCtrl(wxWindow
*parent
, wxWindowID winid
, const wxPoint
& pos
, const wxSize
& size
, long style
, const wxValidator
& validator
, const wxString
& name
)
75 : MuleExtern::wxGenericListCtrl(parent
, winid
, pos
, size
, style
, validator
, name
)
81 if (imgList
.GetImageCount() == 0) {
82 imgList
.Add(wxBitmap(sort_dn_xpm
));
83 imgList
.Add(wxBitmap(sort_up_xpm
));
84 imgList
.Add(wxBitmap(sort_dnx2_xpm
));
85 imgList
.Add(wxBitmap(sort_upx2_xpm
));
88 // Default sort-order is to sort by the first column (asc).
89 m_sort_orders
.push_back(CColPair(0, 0));
91 SetImageList(&imgList
, wxIMAGE_LIST_SMALL
);
95 CMuleListCtrl::~CMuleListCtrl()
97 if (!m_name
.IsEmpty()) {
102 long CMuleListCtrl::InsertColumn(long col
, const wxString
& heading
, int format
, int width
, const wxString
& name
)
104 if (!name
.IsEmpty()) {
106 // Check for valid names
107 wxASSERT_MSG(name
.Find(wxT(':')) == wxNOT_FOUND
, wxT("Column name \"") + name
+ wxT("\" contains invalid characters!"));
108 wxASSERT_MSG(name
.Find(wxT(',')) == wxNOT_FOUND
, wxT("Column name \"") + name
+ wxT("\" contains invalid characters!"));
110 // Check for uniqueness of names.
111 for (ColNameList::const_iterator it
= m_column_names
.begin(); it
!= m_column_names
.end(); ++it
) {
112 if (name
== it
->second
) {
113 wxFAIL_MSG(wxT("Column name \"") + name
+ wxT("\" is not unique!"));
117 // Insert name at position col.
118 ColNameList::iterator it
= m_column_names
.begin();
119 while (it
!= m_column_names
.end() && it
->first
< col
) {
122 m_column_names
.insert(it
, ColNameEntry(col
, name
));
123 while (it
!= m_column_names
.end()) {
129 return MuleExtern::wxGenericListCtrl::InsertColumn(col
, heading
, format
, width
);
132 void CMuleListCtrl::SaveSettings()
134 wxCHECK_RET(!m_name
.IsEmpty(), wxT("Cannot save settings for unnamed list"));
136 wxConfigBase
* cfg
= wxConfigBase::Get();
138 // Save sorting, column and order
140 for (CSortingList::iterator it
= m_sort_orders
.begin(); it
!= m_sort_orders
.end();) {
141 wxString columnName
= GetColumnName(it
->first
);
142 if (!columnName
.IsEmpty()) {
143 sortOrder
+= columnName
;
144 sortOrder
+= wxT(":");
145 sortOrder
+= it
->second
& SORT_DES
? wxT("1") : wxT("0");
146 sortOrder
+= wxT(":");
147 sortOrder
+= it
->second
& SORT_ALT
? wxT("1") : wxT("0");
148 if (++it
!= m_sort_orders
.end()) {
149 sortOrder
+= wxT(",");
156 cfg
->Write(wxT("/eMule/TableOrdering") + m_name
, sortOrder
);
158 // Save column widths. ATM this is also used to signify hidden columns.
160 for (int i
= 0; i
< GetColumnCount(); ++i
) {
161 wxString columnName
= GetColumnName(i
);
162 if (!columnName
.IsEmpty()) {
163 if (!buffer
.IsEmpty()) {
166 buffer
<< columnName
<< wxT(":") << GetColumnWidth(i
);
170 cfg
->Write(wxT("/eMule/TableWidths") + m_name
, buffer
);
173 void CMuleListCtrl::ParseOldConfigEntries(const wxString
& sortOrders
, const wxString
& columnWidths
)
175 // Set sort order (including sort column)
176 wxStringTokenizer
tokens(sortOrders
, wxT(","));
177 while (tokens
.HasMoreTokens()) {
178 wxString token
= tokens
.GetNextToken();
181 unsigned long order
= 0;
183 if (token
.BeforeFirst(wxT(' ')).Strip(wxString::both
).ToLong(&column
)) {
184 if (token
.AfterFirst(wxT(' ')).Strip(wxString::both
).ToULong(&order
)) {
185 column
= GetNewColumnIndex(column
);
186 // Sanity checking, to avoid asserting if column count changes.
187 if (column
>= 0 && column
< GetColumnCount()) {
188 // Sanity checking, to avoid asserting if data-format changes.
189 if ((order
& ~SORTING_MASK
) == 0) {
190 // SetSorting will take care of duplicate entries
191 SetSorting(column
, order
);
200 wxStringTokenizer
tokenizer(columnWidths
, wxT(","));
201 while (tokenizer
.HasMoreTokens()) {
202 long idx
= GetNewColumnIndex(counter
++);
203 long width
= StrToLong(tokenizer
.GetNextToken());
205 SetColumnWidth(idx
, width
);
210 void CMuleListCtrl::LoadSettings()
212 wxCHECK_RET(!m_name
.IsEmpty(), wxT("Cannot load settings for unnamed list"));
214 wxConfigBase
* cfg
= wxConfigBase::Get();
216 // Load sort order (including sort-column)
217 m_sort_orders
.clear();
218 wxString sortOrders
= cfg
->Read(wxT("/eMule/TableOrdering") + m_name
, wxEmptyString
);
219 wxString columnWidths
= cfg
->Read(wxT("/eMule/TableWidths") + m_name
, wxEmptyString
);
221 // Prevent sorting from occuring when calling SetSorting
222 MuleListCtrlCompare sortFunc
= m_sort_func
;
225 if (columnWidths
.Find(wxT(':')) == wxNOT_FOUND
) {
226 // Old-style config entries...
227 ParseOldConfigEntries(sortOrders
, columnWidths
);
230 wxStringTokenizer
tokens(sortOrders
, wxT(","));
231 while (tokens
.HasMoreTokens()) {
232 wxString token
= tokens
.GetNextToken();
233 wxString name
= token
.BeforeFirst(wxT(':'));
234 long order
= StrToLong(token
.AfterFirst(wxT(':')).BeforeLast(wxT(':')));
235 long alt
= StrToLong(token
.AfterLast(wxT(':')));
236 int col
= GetColumnIndex(name
);
238 SetSorting(col
, (order
? SORT_DES
: 0) | (alt
? SORT_ALT
: 0));
243 wxStringTokenizer
tkz(columnWidths
, wxT(","));
244 while (tkz
.HasMoreTokens()) {
245 wxString token
= tkz
.GetNextToken();
246 wxString name
= token
.BeforeFirst(wxT(':'));
247 long width
= StrToLong(token
.AfterFirst(wxT(':')));
248 int col
= GetColumnIndex(name
);
250 SetColumnWidth(col
, width
);
255 // Must have at least one sort-order specified
256 if (m_sort_orders
.empty()) {
257 m_sort_orders
.push_back(CColPair(0, 0));
260 // Re-enable sorting and resort the contents (if any).
261 m_sort_func
= sortFunc
;
266 const wxString
& CMuleListCtrl::GetColumnName(int index
) const
268 for (ColNameList::const_iterator it
= m_column_names
.begin(); it
!= m_column_names
.end(); ++it
) {
269 if (it
->first
== index
) {
276 int CMuleListCtrl::GetColumnIndex(const wxString
& name
) const
278 for (ColNameList::const_iterator it
= m_column_names
.begin(); it
!= m_column_names
.end(); ++it
) {
279 if (it
->second
== name
) {
286 int CMuleListCtrl::GetNewColumnIndex(int oldindex
) const
288 wxStringTokenizer
oldcolumns(GetOldColumnOrder(), wxT(","), wxTOKEN_RET_EMPTY_ALL
);
290 while (oldcolumns
.HasMoreTokens()) {
291 wxString name
= oldcolumns
.GetNextToken();
293 return GetColumnIndex(name
);
300 long CMuleListCtrl::GetInsertPos(wxUIntPtr data
)
302 // Find the best place to position the item through a binary search
304 int Max
= GetItemCount();
306 // Only do this if there are any items and a sorter function
307 if (Max
&& m_sort_func
) {
308 // This search will narrow down the best place to position the new
309 // item. The result will be the item after that position, which is
310 // the format expected by the insertion function.
312 int cur_pos
= ( Max
- Min
) / 2 + Min
;
313 int cmp
= CompareItems(data
, GetItemData(cur_pos
));
315 // Value is lesser than the one at the current pos
321 } while ((Min
!= Max
));
329 int CMuleListCtrl::CompareItems(wxUIntPtr item1
, wxUIntPtr item2
)
331 CSortingList::const_iterator it
= m_sort_orders
.begin();
332 for (; it
!= m_sort_orders
.end(); ++it
) {
333 int result
= m_sort_func(item1
, item2
, it
->first
| it
->second
);
339 // Ensure that different items are never considered equal.
340 return CmpAny(item1
, item2
);
344 MuleListCtrlCompare g_sort_func
= NULL
;
345 CMuleListCtrl
* g_sort_list
= NULL
;
348 int CMuleListCtrl::SortProc(wxUIntPtr item1
, wxUIntPtr item2
, long)
350 const CSortingList
& orders
= g_sort_list
->m_sort_orders
;
352 CSortingList::const_iterator it
= orders
.begin();
353 for (; it
!= orders
.end(); ++it
) {
354 int result
= g_sort_func(item1
, item2
, it
->first
| it
->second
);
360 // Ensure that different items are never considered equal.
361 return CmpAny(item1
, item2
);
365 void CMuleListCtrl::SortList()
367 wxCHECK_RET(g_sort_func
== NULL
, wxT("Sort-function already set"));
368 wxCHECK_RET(g_sort_list
== NULL
, wxT("Sort-list already set"));
370 if (m_sort_func
&& GetColumnCount()) {
371 // Positions are likely to be invalid after sorting.
374 g_sort_func
= m_sort_func
;
377 SortItems(SortProc
, 0);
385 CMuleListCtrl::ItemDataList
CMuleListCtrl::GetSelectedItems() const
387 // Create the initial vector with as many items as are selected
388 ItemDataList
list( GetSelectedItemCount() );
390 // Current item being located
391 unsigned int current
= 0;
393 long pos
= GetNextItem( -1, wxLIST_NEXT_ALL
, wxLIST_STATE_SELECTED
);
394 while ( pos
!= -1 ) {
395 wxASSERT( current
< list
.size() );
397 list
[ current
++ ] = GetItemData( pos
);
399 pos
= GetNextItem( pos
, wxLIST_NEXT_ALL
, wxLIST_STATE_SELECTED
);
406 void CMuleListCtrl::OnColumnRClick(wxListEvent
& evt
)
411 for ( int i
= 0; i
< GetColumnCount() && i
< 15; ++i
) {
414 menu
.AppendCheckItem(i
+ MP_LISTCOL_1
, item
.GetText() );
415 menu
.Check( i
+ MP_LISTCOL_1
, GetColumnWidth(i
) > COL_SIZE_MIN
);
418 PopupMenu(&menu
, evt
.GetPoint());
422 void CMuleListCtrl::OnMenuSelected( wxCommandEvent
& evt
)
424 int col
= evt
.GetId() - MP_LISTCOL_1
;
426 if (GetColumnWidth(col
) > COL_SIZE_MIN
) {
427 SetColumnWidth(col
, 0);
429 SetColumnWidth(col
, wxLIST_AUTOSIZE
);
434 void CMuleListCtrl::OnColumnLClick(wxListEvent
& evt
)
436 // Stop if no sorter-function has been defined
439 } else if (evt
.GetColumn() == -1) {
440 // This happens if a user clicks past the last column header.
444 // Get the currently focused item
445 long pos
= GetNextItem( -1, wxLIST_NEXT_ALL
, wxLIST_STATE_FOCUSED
);
448 item
= GetItemData(pos
);
452 unsigned sort_order
= 0;
453 if (m_sort_orders
.front().first
== (unsigned)evt
.GetColumn()) {
454 // Same column as before, flip the sort-order
455 sort_order
= m_sort_orders
.front().second
;
457 if (sort_order
& SORT_DES
) {
458 if (AltSortAllowed(evt
.GetColumn())) {
459 sort_order
= (~sort_order
) & SORT_ALT
;
464 sort_order
= SORT_DES
| (sort_order
& SORT_ALT
);
467 m_sort_orders
.pop_front();
469 // Check if the column has already been set
470 CSortingList::iterator it
= m_sort_orders
.begin();
471 for (; it
!= m_sort_orders
.end(); ++it
) {
472 if ((unsigned)evt
.GetColumn() == it
->first
) {
473 sort_order
= it
->second
;
479 SetSorting(evt
.GetColumn(), sort_order
);
482 // Set focus on item if any was focused
484 long it_pos
= FindItem(-1, item
);
486 SetItemState(it_pos
,wxLIST_STATE_FOCUSED
, wxLIST_STATE_FOCUSED
| wxLIST_STATE_SELECTED
);
492 void CMuleListCtrl::ClearSelection()
494 if (GetSelectedItemCount()) {
495 long index
= GetNextItem(-1, wxLIST_NEXT_ALL
, wxLIST_STATE_SELECTED
);
496 while (index
!= -1) {
497 SetItemState(index
, 0, wxLIST_STATE_SELECTED
);
498 index
= GetNextItem(index
, wxLIST_NEXT_ALL
, wxLIST_STATE_SELECTED
);
504 bool CMuleListCtrl::AltSortAllowed(unsigned WXUNUSED(column
)) const
510 void CMuleListCtrl::SetSorting(unsigned column
, unsigned order
)
512 MULE_VALIDATE_PARAMS(column
< (unsigned)GetColumnCount(), wxT("Invalid column to sort by."));
513 MULE_VALIDATE_PARAMS(!(order
& ~SORTING_MASK
), wxT("Sorting order contains invalid data."));
515 if (!m_sort_orders
.empty()) {
516 SetColumnImage(m_sort_orders
.front().first
, -1);
518 CSortingList::iterator it
= m_sort_orders
.begin();
519 for (; it
!= m_sort_orders
.end(); ++it
) {
520 if (it
->first
== column
) {
521 m_sort_orders
.erase(it
);
527 m_sort_orders
.push_front(CColPair(column
, order
));
529 if (order
& SORT_DES
) {
530 SetColumnImage(column
, (order
& SORT_ALT
) ? 2 : 0);
532 SetColumnImage(column
, (order
& SORT_ALT
) ? 3 : 1);
539 bool CMuleListCtrl::IsItemSorted(long item
)
541 wxCHECK_MSG(m_sort_func
, true, wxT("No sort function specified!"));
542 wxCHECK_MSG((item
>= 0) && (item
< GetItemCount()), true, wxT("Invalid item"));
545 wxUIntPtr data
= GetItemData(item
);
547 // Check that the item before the current item is smaller (or equal)
549 sorted
&= (CompareItems(GetItemData(item
- 1), data
) <= 0);
552 // Check that the item after the current item is greater (or equal)
553 if (sorted
&& (item
< GetItemCount() - 1)) {
554 sorted
&= (CompareItems(GetItemData(item
+ 1), data
) >= 0);
561 void CMuleListCtrl::OnMouseWheel(wxMouseEvent
&event
)
563 // This enables scrolling with the mouse wheel
568 void CMuleListCtrl::SetColumnImage(unsigned col
, int image
)
571 item
.SetMask(wxLIST_MASK_IMAGE
);
572 item
.SetImage(image
);
573 SetColumn(col
, item
);
577 long CMuleListCtrl::CheckSelection(wxMouseEvent
& event
)
581 evt
.m_itemIndex
= HitTest(event
.GetPosition(), flags
);
583 return CheckSelection(evt
);
587 long CMuleListCtrl::CheckSelection(wxListEvent
& event
)
589 long item
= event
.GetIndex();
591 // Check if clicked item is selected. If not, unselect all and select it.
592 if ((item
!= -1) && !GetItemState(item
, wxLIST_STATE_SELECTED
)) {
595 SetItemState(item
, wxLIST_STATE_SELECTED
, wxLIST_STATE_SELECTED
);
602 wxString
CMuleListCtrl::GetTTSText(unsigned item
) const
604 MULE_VALIDATE_PARAMS(item
< (unsigned)GetItemCount(), wxT("Invalid row."));
605 MULE_VALIDATE_STATE((GetWindowStyle() & wxLC_OWNERDRAW
) == 0,
606 wxT("GetTTSText must be overwritten for owner-drawn lists."));
608 return GetItemText(item
);
612 void CMuleListCtrl::OnChar(wxKeyEvent
& evt
)
614 wxChar key
= evt
.GetKeyCode();
616 // We prefer GetKeyCode() to GetUnicodeKey(), in order to work
617 // around a bug in the GetUnicodeKey(), that causes values to
618 // be returned untranslated. This means for instance, that if
619 // shift and '1' is pressed, the result is '1' rather than '!'
620 // (as it should be on my keyboard). This has been reported:
621 // http://sourceforge.net/tracker/index.php?func=detail&aid=1864810&group_id=9863&atid=109863
622 key
= evt
.GetUnicodeKey();
623 } else if (key
>= WXK_START
) {
624 // wxKeycodes are ignored, as they signify events such as the 'home'
625 // button. Unicoded chars are not checked as there is an overlap valid
626 // chars and the wx keycodes.
631 // We wish to avoid handling shortcuts, with the exception of 'select-all'.
632 if (evt
.AltDown() || evt
.ControlDown() || evt
.MetaDown()) {
633 if (evt
.CmdDown() && (evt
.GetKeyCode() == 0x01)) {
634 // Ctrl+a (Command+a on Mac) was pressed, select all items
635 for (int i
= 0; i
< GetItemCount(); ++i
) {
636 SetItemState(i
, wxLIST_STATE_SELECTED
, wxLIST_STATE_SELECTED
);
642 } else if (m_tts_time
+ 1500u < GetTickCount()) {
646 m_tts_time
= GetTickCount();
647 m_tts_text
.Append(wxTolower(key
));
649 // May happen if the subclass does not forward deletion events.
650 if (m_tts_item
>= GetItemCount()) {
655 unsigned next
= (m_tts_item
== -1) ? 0 : m_tts_item
;
656 for (unsigned i
= 0, count
= GetItemCount(); i
< count
; ++i
) {
657 wxString text
= GetTTSText((next
+ i
) % count
).MakeLower();
659 if (text
.StartsWith(m_tts_text
)) {
662 m_tts_item
= (next
+ i
) % count
;
663 SetItemState(m_tts_item
, wxLIST_STATE_FOCUSED
| wxLIST_STATE_SELECTED
,
664 wxLIST_STATE_FOCUSED
| wxLIST_STATE_SELECTED
);
665 EnsureVisible(m_tts_item
);
671 if (m_tts_item
!= -1) {
672 // Crop the string so that it matches the old item (avoid typos).
673 wxString text
= GetTTSText(m_tts_item
).MakeLower();
675 // If the last key didn't result in a hit, then we skip the event.
676 if (!text
.StartsWith(m_tts_text
)) {
677 if ((m_tts_text
.Length() == 2) && (m_tts_text
[0] == m_tts_text
[1])) {
678 // Special case, single-char, repeated. This allows toggeling
679 // between items starting with a specific letter.
681 // Increment, so the next will be selected (or wrap around).
685 m_tts_text
.RemoveLast();
695 void CMuleListCtrl::OnItemSelected(wxListEvent
& evt
)
697 // We reset the current TTS session if the user manually changes the selection
698 if (m_tts_item
!= evt
.GetIndex()) {
701 // The item is changed so that the next TTS starts from the selected item.
702 m_tts_item
= evt
.GetIndex();
709 void CMuleListCtrl::OnItemDeleted(wxListEvent
& evt
)
711 if (evt
.GetIndex() <= m_tts_item
) {
719 void CMuleListCtrl::OnAllItemsDeleted(wxListEvent
& evt
)
727 void CMuleListCtrl::ResetTTS()
733 wxString
CMuleListCtrl::GetOldColumnOrder() const
735 return wxEmptyString
;
737 // File_checked_for_headers