add events API to wxHtmlWindow (patch #1504493 by Francesco Montorsi)
[wxWidgets.git] / src / generic / htmllbox.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: generic/htmllbox.cpp
3 // Purpose: implementation of wxHtmlListBox
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 31.05.03
7 // RCS-ID: $Id$
8 // Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwindows.org>
9 // License: wxWindows license
10 ///////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #ifndef WX_PRECOMP
28 #include "wx/dcclient.h"
29 #endif //WX_PRECOMP
30
31 #if wxUSE_HTML
32
33 #include "wx/htmllbox.h"
34
35 #include "wx/html/htmlcell.h"
36 #include "wx/html/winpars.h"
37
38 // this hack forces the linker to always link in m_* files
39 #include "wx/html/forcelnk.h"
40 FORCE_WXHTML_MODULES()
41
42 // ----------------------------------------------------------------------------
43 // constants
44 // ----------------------------------------------------------------------------
45
46 // small border always added to the cells:
47 static const wxCoord CELL_BORDER = 2;
48
49 const wxChar wxHtmlListBoxNameStr[] = wxT("htmlListBox");
50 const wxChar wxSimpleHtmlListBoxNameStr[] = wxT("simpleHtmlListBox");
51
52 // ============================================================================
53 // private classes
54 // ============================================================================
55
56 // ----------------------------------------------------------------------------
57 // wxHtmlListBoxCache
58 // ----------------------------------------------------------------------------
59
60 // this class is used by wxHtmlListBox to cache the parsed representation of
61 // the items to avoid doing it anew each time an item must be drawn
62 class wxHtmlListBoxCache
63 {
64 private:
65 // invalidate a single item, used by Clear() and InvalidateRange()
66 void InvalidateItem(size_t n)
67 {
68 m_items[n] = (size_t)-1;
69 delete m_cells[n];
70 m_cells[n] = NULL;
71 }
72
73 public:
74 wxHtmlListBoxCache()
75 {
76 for ( size_t n = 0; n < SIZE; n++ )
77 {
78 m_items[n] = (size_t)-1;
79 m_cells[n] = NULL;
80 }
81
82 m_next = 0;
83 }
84
85 ~wxHtmlListBoxCache()
86 {
87 for ( size_t n = 0; n < SIZE; n++ )
88 {
89 delete m_cells[n];
90 }
91 }
92
93 // completely invalidate the cache
94 void Clear()
95 {
96 for ( size_t n = 0; n < SIZE; n++ )
97 {
98 InvalidateItem(n);
99 }
100 }
101
102 // return the cached cell for this index or NULL if none
103 wxHtmlCell *Get(size_t item) const
104 {
105 for ( size_t n = 0; n < SIZE; n++ )
106 {
107 if ( m_items[n] == item )
108 return m_cells[n];
109 }
110
111 return NULL;
112 }
113
114 // returns true if we already have this item cached
115 bool Has(size_t item) const { return Get(item) != NULL; }
116
117 // ensure that the item is cached
118 void Store(size_t item, wxHtmlCell *cell)
119 {
120 delete m_cells[m_next];
121 m_cells[m_next] = cell;
122 m_items[m_next] = item;
123
124 // advance to the next item wrapping around if there are no more
125 if ( ++m_next == SIZE )
126 m_next = 0;
127 }
128
129 // forget the cached value of the item(s) between the given ones (inclusive)
130 void InvalidateRange(size_t from, size_t to)
131 {
132 for ( size_t n = 0; n < SIZE; n++ )
133 {
134 if ( m_items[n] >= from && m_items[n] <= to )
135 {
136 InvalidateItem(n);
137 }
138 }
139 }
140
141 private:
142 // the max number of the items we cache
143 enum { SIZE = 50 };
144
145 // the index of the LRU (oldest) cell
146 size_t m_next;
147
148 // the parsed representation of the cached item or NULL
149 wxHtmlCell *m_cells[SIZE];
150
151 // the index of the currently cached item (only valid if m_cells != NULL)
152 size_t m_items[SIZE];
153 };
154
155 // ----------------------------------------------------------------------------
156 // wxHtmlListBoxStyle
157 // ----------------------------------------------------------------------------
158
159 // just forward wxDefaultHtmlRenderingStyle callbacks to the main class so that
160 // they could be overridden by the user code
161 class wxHtmlListBoxStyle : public wxDefaultHtmlRenderingStyle
162 {
163 public:
164 wxHtmlListBoxStyle(const wxHtmlListBox& hlbox) : m_hlbox(hlbox) { }
165
166 virtual wxColour GetSelectedTextColour(const wxColour& colFg)
167 {
168 return m_hlbox.GetSelectedTextColour(colFg);
169 }
170
171 virtual wxColour GetSelectedTextBgColour(const wxColour& colBg)
172 {
173 return m_hlbox.GetSelectedTextBgColour(colBg);
174 }
175
176 private:
177 const wxHtmlListBox& m_hlbox;
178
179 DECLARE_NO_COPY_CLASS(wxHtmlListBoxStyle)
180 };
181
182 // ----------------------------------------------------------------------------
183 // event tables
184 // ----------------------------------------------------------------------------
185
186 BEGIN_EVENT_TABLE(wxHtmlListBox, wxVListBox)
187 EVT_SIZE(wxHtmlListBox::OnSize)
188 EVT_MOTION(wxHtmlListBox::OnMouseMove)
189 EVT_LEFT_DOWN(wxHtmlListBox::OnLeftDown)
190 END_EVENT_TABLE()
191
192 // ============================================================================
193 // implementation
194 // ============================================================================
195
196 IMPLEMENT_ABSTRACT_CLASS(wxHtmlListBox, wxVListBox)
197
198
199 // ----------------------------------------------------------------------------
200 // wxHtmlListBox creation
201 // ----------------------------------------------------------------------------
202
203 wxHtmlListBox::wxHtmlListBox()
204 : wxHtmlWindowMouseHelper(this)
205 {
206 Init();
207 }
208
209 // normal constructor which calls Create() internally
210 wxHtmlListBox::wxHtmlListBox(wxWindow *parent,
211 wxWindowID id,
212 const wxPoint& pos,
213 const wxSize& size,
214 long style,
215 const wxString& name)
216 : wxHtmlWindowMouseHelper(this)
217 {
218 Init();
219
220 (void)Create(parent, id, pos, size, style, name);
221 }
222
223 void wxHtmlListBox::Init()
224 {
225 m_htmlParser = NULL;
226 m_htmlRendStyle = new wxHtmlListBoxStyle(*this);
227 m_cache = new wxHtmlListBoxCache;
228 }
229
230 bool wxHtmlListBox::Create(wxWindow *parent,
231 wxWindowID id,
232 const wxPoint& pos,
233 const wxSize& size,
234 long style,
235 const wxString& name)
236 {
237 return wxVListBox::Create(parent, id, pos, size, style, name);
238 }
239
240 wxHtmlListBox::~wxHtmlListBox()
241 {
242 delete m_cache;
243
244 if ( m_htmlParser )
245 {
246 delete m_htmlParser->GetDC();
247 delete m_htmlParser;
248 }
249
250 delete m_htmlRendStyle;
251 }
252
253 // ----------------------------------------------------------------------------
254 // wxHtmlListBox appearance
255 // ----------------------------------------------------------------------------
256
257 wxColour wxHtmlListBox::GetSelectedTextColour(const wxColour& colFg) const
258 {
259 return m_htmlRendStyle->
260 wxDefaultHtmlRenderingStyle::GetSelectedTextColour(colFg);
261 }
262
263 wxColour
264 wxHtmlListBox::GetSelectedTextBgColour(const wxColour& WXUNUSED(colBg)) const
265 {
266 return GetSelectionBackground();
267 }
268
269 // ----------------------------------------------------------------------------
270 // wxHtmlListBox items markup
271 // ----------------------------------------------------------------------------
272
273 wxString wxHtmlListBox::OnGetItemMarkup(size_t n) const
274 {
275 // we don't even need to wrap the value returned by OnGetItem() inside
276 // "<html><body>" and "</body></html>" because wxHTML can parse it even
277 // without these tags
278 return OnGetItem(n);
279 }
280
281 // ----------------------------------------------------------------------------
282 // wxHtmlListBox cache handling
283 // ----------------------------------------------------------------------------
284
285 void wxHtmlListBox::CacheItem(size_t n) const
286 {
287 if ( !m_cache->Has(n) )
288 {
289 if ( !m_htmlParser )
290 {
291 wxHtmlListBox *self = wxConstCast(this, wxHtmlListBox);
292
293 self->m_htmlParser = new wxHtmlWinParser(self);
294 m_htmlParser->SetDC(new wxClientDC(self));
295 m_htmlParser->SetFS(&self->m_filesystem);
296
297 // use system's default GUI font by default:
298 m_htmlParser->SetStandardFonts();
299 }
300
301 wxHtmlContainerCell *cell = (wxHtmlContainerCell *)m_htmlParser->
302 Parse(OnGetItemMarkup(n));
303 wxCHECK_RET( cell, _T("wxHtmlParser::Parse() returned NULL?") );
304
305 // set the cell's ID to item's index so that CellCoordsToPhysical()
306 // can quickly find the item:
307 cell->SetId(wxString::Format(_T("%lu"), (unsigned long)n));
308
309 cell->Layout(GetClientSize().x - 2*GetMargins().x);
310
311 m_cache->Store(n, cell);
312 }
313 }
314
315 void wxHtmlListBox::OnSize(wxSizeEvent& event)
316 {
317 // we need to relayout all the cached cells
318 m_cache->Clear();
319
320 event.Skip();
321 }
322
323 void wxHtmlListBox::RefreshLine(size_t line)
324 {
325 m_cache->InvalidateRange(line, line);
326
327 wxVListBox::RefreshLine(line);
328 }
329
330 void wxHtmlListBox::RefreshLines(size_t from, size_t to)
331 {
332 m_cache->InvalidateRange(from, to);
333
334 wxVListBox::RefreshLines(from, to);
335 }
336
337 void wxHtmlListBox::RefreshAll()
338 {
339 m_cache->Clear();
340
341 wxVListBox::RefreshAll();
342 }
343
344 void wxHtmlListBox::SetItemCount(size_t count)
345 {
346 // the items are going to change, forget the old ones
347 m_cache->Clear();
348
349 wxVListBox::SetItemCount(count);
350 }
351
352 // ----------------------------------------------------------------------------
353 // wxHtmlListBox implementation of wxVListBox pure virtuals
354 // ----------------------------------------------------------------------------
355
356 void wxHtmlListBox::OnDrawItem(wxDC& dc, const wxRect& rect, size_t n) const
357 {
358 CacheItem(n);
359
360 wxHtmlCell *cell = m_cache->Get(n);
361 wxCHECK_RET( cell, _T("this cell should be cached!") );
362
363 wxHtmlRenderingInfo htmlRendInfo;
364
365 // draw the selected cell in selected state
366 if ( IsSelected(n) )
367 {
368 wxHtmlSelection htmlSel;
369 htmlSel.Set(wxPoint(0,0), cell, wxPoint(INT_MAX, INT_MAX), cell);
370 htmlRendInfo.SetSelection(&htmlSel);
371 if ( m_htmlRendStyle )
372 htmlRendInfo.SetStyle(m_htmlRendStyle);
373 htmlRendInfo.GetState().SetSelectionState(wxHTML_SEL_IN);
374 }
375
376 // note that we can't stop drawing exactly at the window boundary as then
377 // even the visible cells part could be not drawn, so always draw the
378 // entire cell
379 cell->Draw(dc,
380 rect.x + CELL_BORDER, rect.y + CELL_BORDER,
381 0, INT_MAX, htmlRendInfo);
382 }
383
384 wxCoord wxHtmlListBox::OnMeasureItem(size_t n) const
385 {
386 CacheItem(n);
387
388 wxHtmlCell *cell = m_cache->Get(n);
389 wxCHECK_MSG( cell, 0, _T("this cell should be cached!") );
390
391 return cell->GetHeight() + cell->GetDescent() + 4;
392 }
393
394 // ----------------------------------------------------------------------------
395 // wxHtmlListBox implementation of wxHtmlListBoxWinInterface
396 // ----------------------------------------------------------------------------
397
398 void wxHtmlListBox::SetHTMLWindowTitle(const wxString& WXUNUSED(title))
399 {
400 // nothing to do
401 }
402
403 void wxHtmlListBox::OnHTMLLinkClicked(const wxHtmlLinkInfo& link)
404 {
405 OnLinkClicked(GetItemForCell(link.GetHtmlCell()), link);
406 }
407
408 void wxHtmlListBox::OnLinkClicked(size_t WXUNUSED(n),
409 const wxHtmlLinkInfo& link)
410 {
411 wxHtmlLinkEvent event(GetId(), link);
412 GetEventHandler()->ProcessEvent(event);
413 }
414
415 wxHtmlOpeningStatus
416 wxHtmlListBox::OnHTMLOpeningURL(wxHtmlURLType WXUNUSED(type),
417 const wxString& WXUNUSED(url),
418 wxString *WXUNUSED(redirect)) const
419 {
420 return wxHTML_OPEN;
421 }
422
423 wxPoint wxHtmlListBox::HTMLCoordsToWindow(wxHtmlCell *cell,
424 const wxPoint& pos) const
425 {
426 return CellCoordsToPhysical(pos, cell);
427 }
428
429 wxWindow* wxHtmlListBox::GetHTMLWindow() { return this; }
430
431 wxColour wxHtmlListBox::GetHTMLBackgroundColour() const
432 {
433 return GetBackgroundColour();
434 }
435
436 void wxHtmlListBox::SetHTMLBackgroundColour(const wxColour& WXUNUSED(clr))
437 {
438 // nothing to do
439 }
440
441 void wxHtmlListBox::SetHTMLBackgroundImage(const wxBitmap& WXUNUSED(bmpBg))
442 {
443 // nothing to do
444 }
445
446 void wxHtmlListBox::SetHTMLStatusText(const wxString& WXUNUSED(text))
447 {
448 // nothing to do
449 }
450
451 wxCursor wxHtmlListBox::GetHTMLCursor(HTMLCursor type) const
452 {
453 // we don't want to show text selection cursor in listboxes
454 if (type == HTMLCursor_Text)
455 return wxHtmlWindow::GetDefaultHTMLCursor(HTMLCursor_Default);
456
457 // in all other cases, use the same cursor as wxHtmlWindow:
458 return wxHtmlWindow::GetDefaultHTMLCursor(type);
459 }
460
461 // ----------------------------------------------------------------------------
462 // wxHtmlListBox handling of HTML links
463 // ----------------------------------------------------------------------------
464
465 wxPoint wxHtmlListBox::GetRootCellCoords(size_t n) const
466 {
467 wxPoint pos(CELL_BORDER, CELL_BORDER);
468 pos += GetMargins();
469 pos.y += GetLinesHeight(GetFirstVisibleLine(), n);
470 return pos;
471 }
472
473 bool wxHtmlListBox::PhysicalCoordsToCell(wxPoint& pos, wxHtmlCell*& cell) const
474 {
475 int n = HitTest(pos);
476 if ( n == wxNOT_FOUND )
477 return false;
478
479 // convert mouse coordinates to coords relative to item's wxHtmlCell:
480 pos -= GetRootCellCoords(n);
481
482 CacheItem(n);
483 cell = m_cache->Get(n);
484
485 return true;
486 }
487
488 size_t wxHtmlListBox::GetItemForCell(const wxHtmlCell *cell) const
489 {
490 wxCHECK_MSG( cell, 0, _T("no cell") );
491
492 cell = cell->GetRootCell();
493
494 wxCHECK_MSG( cell, 0, _T("no root cell") );
495
496 // the cell's ID contains item index, see CacheItem():
497 unsigned long n;
498 if ( !cell->GetId().ToULong(&n) )
499 {
500 wxFAIL_MSG( _T("unexpected root cell's ID") );
501 return 0;
502 }
503
504 return n;
505 }
506
507 wxPoint
508 wxHtmlListBox::CellCoordsToPhysical(const wxPoint& pos, wxHtmlCell *cell) const
509 {
510 return pos + GetRootCellCoords(GetItemForCell(cell));
511 }
512
513 void wxHtmlListBox::OnInternalIdle()
514 {
515 wxVListBox::OnInternalIdle();
516
517 if ( wxHtmlWindowMouseHelper::DidMouseMove() )
518 {
519 wxPoint pos = ScreenToClient(wxGetMousePosition());
520 wxHtmlCell *cell;
521
522 if ( !PhysicalCoordsToCell(pos, cell) )
523 return;
524
525 wxHtmlWindowMouseHelper::HandleIdle(cell, pos);
526 }
527 }
528
529 void wxHtmlListBox::OnMouseMove(wxMouseEvent& event)
530 {
531 wxHtmlWindowMouseHelper::HandleMouseMoved();
532 event.Skip();
533 }
534
535 void wxHtmlListBox::OnLeftDown(wxMouseEvent& event)
536 {
537 wxPoint pos = event.GetPosition();
538 wxHtmlCell *cell;
539
540 if ( !PhysicalCoordsToCell(pos, cell) )
541 {
542 event.Skip();
543 return;
544 }
545
546 if ( !wxHtmlWindowMouseHelper::HandleMouseClick(cell, pos, event) )
547 {
548 // no link was clicked, so let the listbox code handle the click (e.g.
549 // by selecting another item in the list):
550 event.Skip();
551 }
552 }
553
554
555 // ----------------------------------------------------------------------------
556 // wxSimpleHtmlListBox
557 // ----------------------------------------------------------------------------
558
559 bool wxSimpleHtmlListBox::Create(wxWindow *parent, wxWindowID id,
560 const wxPoint& pos,
561 const wxSize& size,
562 int n, const wxString choices[],
563 long style,
564 const wxValidator& validator,
565 const wxString& name)
566 {
567 if (!wxHtmlListBox::Create(parent, id, pos, size, style, name))
568 return false;
569
570 SetValidator(validator);
571 for (int i=0; i<n; i++)
572 Append(choices[i]);
573
574 return true;
575 }
576
577 bool wxSimpleHtmlListBox::Create(wxWindow *parent, wxWindowID id,
578 const wxPoint& pos,
579 const wxSize& size,
580 const wxArrayString& choices,
581 long style,
582 const wxValidator& validator,
583 const wxString& name)
584 {
585 if (!wxHtmlListBox::Create(parent, id, pos, size, style, name))
586 return false;
587
588 SetValidator(validator);
589 Append(choices);
590
591 return true;
592 }
593
594 wxSimpleHtmlListBox::~wxSimpleHtmlListBox()
595 {
596 wxASSERT(m_items.GetCount() == m_clientData.GetCount());
597 if (HasClientObjectData())
598 {
599 // clear the array of client data objects
600 for (size_t i=0; i<m_items.GetCount(); i++)
601 delete DoGetItemClientObject(i);
602 }
603
604 m_items.Clear();
605 m_clientData.Clear();
606 }
607
608 void wxSimpleHtmlListBox::Clear()
609 {
610 m_items.Clear();
611 m_clientData.Clear();
612 UpdateCount();
613 }
614
615 void wxSimpleHtmlListBox::Delete(unsigned int n)
616 {
617 m_items.RemoveAt(n);
618 m_clientData.RemoveAt(n);
619 UpdateCount();
620 }
621
622 void wxSimpleHtmlListBox::Append(const wxArrayString& strings)
623 {
624 // we know how many items are going to be added - avoid too many reallocs
625 // m_items.Alloc(strings.GetCount());
626 // FIXME: Alloc() will clear all the old contents.
627 // Suggested fix = make Grow() public and make WX_APPEND_ARRAY take
628 // care of calling it automatically
629
630 // append all given items at once
631 WX_APPEND_ARRAY(m_items, strings);
632 m_clientData.Add(NULL, strings.GetCount());
633 UpdateCount();
634 }
635
636 int wxSimpleHtmlListBox::DoAppend(const wxString& item)
637 {
638 m_items.Add(item);
639 m_clientData.Add(NULL);
640 UpdateCount();
641 return GetCount()-1;
642 }
643
644 int wxSimpleHtmlListBox::DoInsert(const wxString& item, unsigned int pos)
645 {
646 m_items.Insert(item, pos);
647 m_clientData.Insert(NULL, pos);
648 UpdateCount();
649 return pos;
650 }
651
652 void wxSimpleHtmlListBox::SetString(unsigned int n, const wxString& s)
653 {
654 wxCHECK_RET( IsValid(n),
655 wxT("invalid index in wxSimpleHtmlListBox::SetString") );
656
657 m_items[n]=s;
658 RefreshLine(n);
659 }
660
661 wxString wxSimpleHtmlListBox::GetString(unsigned int n) const
662 {
663 wxCHECK_MSG( IsValid(n), wxEmptyString,
664 wxT("invalid index in wxSimpleHtmlListBox::GetString") );
665
666 return m_items[n];
667 }
668
669 void wxSimpleHtmlListBox::UpdateCount()
670 {
671 wxASSERT(m_items.GetCount() == m_clientData.GetCount());
672 wxHtmlListBox::SetItemCount(m_items.GetCount());
673
674 // very small optimization: if you need to add lot of items to
675 // a wxSimpleHtmlListBox be sure to use the
676 // wxSimpleHtmlListBox::Append(const wxArrayString&) method instead!
677 if (!this->IsFrozen())
678 RefreshAll();
679 }
680
681 #endif // wxUSE_HTML