fixed memory leak (m_selection wasn't deleted)
[wxWidgets.git] / src / html / htmlwin.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: htmlwin.cpp
3 // Purpose: wxHtmlWindow class for parsing & displaying HTML (implementation)
4 // Author: Vaclav Slavik
5 // RCS-ID: $Id$
6 // Copyright: (c) 1999 Vaclav Slavik
7 // Licence: wxWindows Licence
8 /////////////////////////////////////////////////////////////////////////////
9
10
11 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
12 #pragma implementation "htmlwin.h"
13 #pragma implementation "htmlproc.h"
14 #endif
15
16 #include "wx/wxprec.h"
17
18 #include "wx/defs.h"
19 #if wxUSE_HTML && wxUSE_STREAMS
20
21 #ifdef __BORLANDC__
22 #pragma hdrstop
23 #endif
24
25 #ifndef WXPRECOMP
26 #include "wx/log.h"
27 #include "wx/intl.h"
28 #include "wx/dcclient.h"
29 #include "wx/frame.h"
30 #endif
31
32 #include "wx/html/htmlwin.h"
33 #include "wx/html/htmlproc.h"
34 #include "wx/list.h"
35 #include "wx/clipbrd.h"
36 #include "wx/dataobj.h"
37 #include "wx/timer.h"
38 #include "wx/dcmemory.h"
39
40 #include "wx/arrimpl.cpp"
41 #include "wx/listimpl.cpp"
42
43
44
45 #if wxUSE_CLIPBOARD
46 // ----------------------------------------------------------------------------
47 // wxHtmlWinAutoScrollTimer: the timer used to generate a stream of scroll
48 // events when a captured mouse is held outside the window
49 // ----------------------------------------------------------------------------
50
51 class wxHtmlWinAutoScrollTimer : public wxTimer
52 {
53 public:
54 wxHtmlWinAutoScrollTimer(wxScrolledWindow *win,
55 wxEventType eventTypeToSend,
56 int pos, int orient)
57 {
58 m_win = win;
59 m_eventType = eventTypeToSend;
60 m_pos = pos;
61 m_orient = orient;
62 }
63
64 virtual void Notify();
65
66 private:
67 wxScrolledWindow *m_win;
68 wxEventType m_eventType;
69 int m_pos,
70 m_orient;
71
72 DECLARE_NO_COPY_CLASS(wxHtmlWinAutoScrollTimer)
73 };
74
75 void wxHtmlWinAutoScrollTimer::Notify()
76 {
77 // only do all this as long as the window is capturing the mouse
78 if ( wxWindow::GetCapture() != m_win )
79 {
80 Stop();
81 }
82 else // we still capture the mouse, continue generating events
83 {
84 // first scroll the window if we are allowed to do it
85 wxScrollWinEvent event1(m_eventType, m_pos, m_orient);
86 event1.SetEventObject(m_win);
87 if ( m_win->GetEventHandler()->ProcessEvent(event1) )
88 {
89 // and then send a pseudo mouse-move event to refresh the selection
90 wxMouseEvent event2(wxEVT_MOTION);
91 wxGetMousePosition(&event2.m_x, &event2.m_y);
92
93 // the mouse event coordinates should be client, not screen as
94 // returned by wxGetMousePosition
95 wxWindow *parentTop = m_win;
96 while ( parentTop->GetParent() )
97 parentTop = parentTop->GetParent();
98 wxPoint ptOrig = parentTop->GetPosition();
99 event2.m_x -= ptOrig.x;
100 event2.m_y -= ptOrig.y;
101
102 event2.SetEventObject(m_win);
103
104 // FIXME: we don't fill in the other members - ok?
105 m_win->GetEventHandler()->ProcessEvent(event2);
106 }
107 else // can't scroll further, stop
108 {
109 Stop();
110 }
111 }
112 }
113
114 #endif // wxUSE_CLIPBOARD
115
116
117
118 //-----------------------------------------------------------------------------
119 // wxHtmlHistoryItem
120 //-----------------------------------------------------------------------------
121
122 // item of history list
123 class WXDLLIMPEXP_HTML wxHtmlHistoryItem
124 {
125 public:
126 wxHtmlHistoryItem(const wxString& p, const wxString& a) {m_Page = p, m_Anchor = a, m_Pos = 0;}
127 int GetPos() const {return m_Pos;}
128 void SetPos(int p) {m_Pos = p;}
129 const wxString& GetPage() const {return m_Page;}
130 const wxString& GetAnchor() const {return m_Anchor;}
131
132 private:
133 wxString m_Page;
134 wxString m_Anchor;
135 int m_Pos;
136 };
137
138
139 //-----------------------------------------------------------------------------
140 // our private arrays:
141 //-----------------------------------------------------------------------------
142
143 WX_DECLARE_OBJARRAY(wxHtmlHistoryItem, wxHtmlHistoryArray);
144 WX_DEFINE_OBJARRAY(wxHtmlHistoryArray);
145
146 WX_DECLARE_LIST(wxHtmlProcessor, wxHtmlProcessorList);
147 WX_DEFINE_LIST(wxHtmlProcessorList);
148
149 //-----------------------------------------------------------------------------
150 // wxHtmlWindow
151 //-----------------------------------------------------------------------------
152
153
154 void wxHtmlWindow::Init()
155 {
156 m_tmpMouseMoved = FALSE;
157 m_tmpLastLink = NULL;
158 m_tmpLastCell = NULL;
159 m_tmpCanDrawLocks = 0;
160 m_FS = new wxFileSystem();
161 m_RelatedStatusBar = -1;
162 m_RelatedFrame = NULL;
163 m_TitleFormat = wxT("%s");
164 m_OpenedPage = m_OpenedAnchor = m_OpenedPageTitle = wxEmptyString;
165 m_Cell = NULL;
166 m_Parser = new wxHtmlWinParser(this);
167 m_Parser->SetFS(m_FS);
168 m_HistoryPos = -1;
169 m_HistoryOn = TRUE;
170 m_History = new wxHtmlHistoryArray;
171 m_Processors = NULL;
172 m_Style = 0;
173 SetBorders(10);
174 m_selection = NULL;
175 m_makingSelection = false;
176 #if wxUSE_CLIPBOARD
177 m_timerAutoScroll = NULL;
178 m_lastDoubleClick = 0;
179 #endif // wxUSE_CLIPBOARD
180 m_backBuffer = NULL;
181 }
182
183 bool wxHtmlWindow::Create(wxWindow *parent, wxWindowID id,
184 const wxPoint& pos, const wxSize& size,
185 long style, const wxString& name)
186 {
187 if (!wxScrolledWindow::Create(parent, id, pos, size,
188 style | wxVSCROLL | wxHSCROLL, name))
189 return FALSE;
190
191 m_Style = style;
192 SetPage(wxT("<html><body></body></html>"));
193 return TRUE;
194 }
195
196
197 wxHtmlWindow::~wxHtmlWindow()
198 {
199 #if wxUSE_CLIPBOARD
200 StopAutoScrolling();
201 #endif // wxUSE_CLIPBOARD
202 HistoryClear();
203
204 delete m_selection;
205
206 delete m_Cell;
207
208 if ( m_Processors )
209 {
210 WX_CLEAR_LIST(wxHtmlProcessorList, *m_Processors);
211 }
212
213 delete m_Parser;
214 delete m_FS;
215 delete m_History;
216 delete m_Processors;
217 delete m_backBuffer;
218 }
219
220
221
222 void wxHtmlWindow::SetRelatedFrame(wxFrame* frame, const wxString& format)
223 {
224 m_RelatedFrame = frame;
225 m_TitleFormat = format;
226 }
227
228
229
230 void wxHtmlWindow::SetRelatedStatusBar(int bar)
231 {
232 m_RelatedStatusBar = bar;
233 }
234
235
236
237 void wxHtmlWindow::SetFonts(wxString normal_face, wxString fixed_face, const int *sizes)
238 {
239 wxString op = m_OpenedPage;
240
241 m_Parser->SetFonts(normal_face, fixed_face, sizes);
242 // fonts changed => contents invalid, so reload the page:
243 SetPage(wxT("<html><body></body></html>"));
244 if (!op.IsEmpty()) LoadPage(op);
245 }
246
247
248
249 bool wxHtmlWindow::SetPage(const wxString& source)
250 {
251 wxString newsrc(source);
252
253 wxDELETE(m_selection);
254
255 // pass HTML through registered processors:
256 if (m_Processors || m_GlobalProcessors)
257 {
258 wxHtmlProcessorList::compatibility_iterator nodeL, nodeG;
259 int prL, prG;
260
261 nodeL = (m_Processors) ? m_Processors->GetFirst() : wxHtmlProcessorList::compatibility_iterator();
262 nodeG = (m_GlobalProcessors) ? m_GlobalProcessors->GetFirst() : wxHtmlProcessorList::compatibility_iterator();
263
264 // VS: there are two lists, global and local, both of them sorted by
265 // priority. Since we have to go through _both_ lists with
266 // decreasing priority, we "merge-sort" the lists on-line by
267 // processing that one of the two heads that has higher priority
268 // in every iteration
269 while (nodeL || nodeG)
270 {
271 prL = (nodeL) ? nodeL->GetData()->GetPriority() : -1;
272 prG = (nodeG) ? nodeG->GetData()->GetPriority() : -1;
273 if (prL > prG)
274 {
275 if (nodeL->GetData()->IsEnabled())
276 newsrc = nodeL->GetData()->Process(newsrc);
277 nodeL = nodeL->GetNext();
278 }
279 else // prL <= prG
280 {
281 if (nodeG->GetData()->IsEnabled())
282 newsrc = nodeG->GetData()->Process(newsrc);
283 nodeG = nodeG->GetNext();
284 }
285 }
286 }
287
288 // ...and run the parser on it:
289 wxClientDC *dc = new wxClientDC(this);
290 dc->SetMapMode(wxMM_TEXT);
291 SetBackgroundColour(wxColour(0xFF, 0xFF, 0xFF));
292 m_OpenedPage = m_OpenedAnchor = m_OpenedPageTitle = wxEmptyString;
293 m_Parser->SetDC(dc);
294 if (m_Cell)
295 {
296 delete m_Cell;
297 m_Cell = NULL;
298 }
299 m_Cell = (wxHtmlContainerCell*) m_Parser->Parse(newsrc);
300 delete dc;
301 m_Cell->SetIndent(m_Borders, wxHTML_INDENT_ALL, wxHTML_UNITS_PIXELS);
302 m_Cell->SetAlignHor(wxHTML_ALIGN_CENTER);
303 CreateLayout();
304 if (m_tmpCanDrawLocks == 0)
305 Refresh();
306 return TRUE;
307 }
308
309 bool wxHtmlWindow::AppendToPage(const wxString& source)
310 {
311 return SetPage(*(GetParser()->GetSource()) + source);
312 }
313
314 bool wxHtmlWindow::LoadPage(const wxString& location)
315 {
316 wxBusyCursor busyCursor;
317
318 wxFSFile *f;
319 bool rt_val;
320 bool needs_refresh = FALSE;
321
322 m_tmpCanDrawLocks++;
323 if (m_HistoryOn && (m_HistoryPos != -1))
324 {
325 // store scroll position into history item:
326 int x, y;
327 GetViewStart(&x, &y);
328 (*m_History)[m_HistoryPos].SetPos(y);
329 }
330
331 if (location[0] == wxT('#'))
332 {
333 // local anchor:
334 wxString anch = location.Mid(1) /*1 to end*/;
335 m_tmpCanDrawLocks--;
336 rt_val = ScrollToAnchor(anch);
337 m_tmpCanDrawLocks++;
338 }
339 else if (location.Find(wxT('#')) != wxNOT_FOUND && location.BeforeFirst(wxT('#')) == m_OpenedPage)
340 {
341 wxString anch = location.AfterFirst(wxT('#'));
342 m_tmpCanDrawLocks--;
343 rt_val = ScrollToAnchor(anch);
344 m_tmpCanDrawLocks++;
345 }
346 else if (location.Find(wxT('#')) != wxNOT_FOUND &&
347 (m_FS->GetPath() + location.BeforeFirst(wxT('#'))) == m_OpenedPage)
348 {
349 wxString anch = location.AfterFirst(wxT('#'));
350 m_tmpCanDrawLocks--;
351 rt_val = ScrollToAnchor(anch);
352 m_tmpCanDrawLocks++;
353 }
354
355 else
356 {
357 needs_refresh = TRUE;
358 // load&display it:
359 if (m_RelatedStatusBar != -1)
360 {
361 m_RelatedFrame->SetStatusText(_("Connecting..."), m_RelatedStatusBar);
362 Refresh(FALSE);
363 }
364
365 f = m_Parser->OpenURL(wxHTML_URL_PAGE, location);
366
367 // try to interpret 'location' as filename instead of URL:
368 if (f == NULL)
369 {
370 wxFileName fn(location);
371 wxString location2 = wxFileSystem::FileNameToURL(fn);
372 f = m_Parser->OpenURL(wxHTML_URL_PAGE, location2);
373 }
374
375 if (f == NULL)
376 {
377 wxLogError(_("Unable to open requested HTML document: %s"), location.c_str());
378 m_tmpCanDrawLocks--;
379 return FALSE;
380 }
381
382 else
383 {
384 wxList::compatibility_iterator node;
385 wxString src = wxEmptyString;
386
387 if (m_RelatedStatusBar != -1)
388 {
389 wxString msg = _("Loading : ") + location;
390 m_RelatedFrame->SetStatusText(msg, m_RelatedStatusBar);
391 Refresh(FALSE);
392 }
393
394 node = m_Filters.GetFirst();
395 while (node)
396 {
397 wxHtmlFilter *h = (wxHtmlFilter*) node->GetData();
398 if (h->CanRead(*f))
399 {
400 src = h->ReadFile(*f);
401 break;
402 }
403 node = node->GetNext();
404 }
405 if (src == wxEmptyString)
406 {
407 if (m_DefaultFilter == NULL) m_DefaultFilter = GetDefaultFilter();
408 src = m_DefaultFilter->ReadFile(*f);
409 }
410
411 m_FS->ChangePathTo(f->GetLocation());
412 rt_val = SetPage(src);
413 m_OpenedPage = f->GetLocation();
414 if (f->GetAnchor() != wxEmptyString)
415 {
416 ScrollToAnchor(f->GetAnchor());
417 }
418
419 delete f;
420
421 if (m_RelatedStatusBar != -1) m_RelatedFrame->SetStatusText(_("Done"), m_RelatedStatusBar);
422 }
423 }
424
425 if (m_HistoryOn) // add this page to history there:
426 {
427 int c = m_History->GetCount() - (m_HistoryPos + 1);
428
429 if (m_HistoryPos < 0 ||
430 (*m_History)[m_HistoryPos].GetPage() != m_OpenedPage ||
431 (*m_History)[m_HistoryPos].GetAnchor() != m_OpenedAnchor)
432 {
433 m_HistoryPos++;
434 for (int i = 0; i < c; i++)
435 m_History->RemoveAt(m_HistoryPos);
436 m_History->Add(new wxHtmlHistoryItem(m_OpenedPage, m_OpenedAnchor));
437 }
438 }
439
440 if (m_OpenedPageTitle == wxEmptyString)
441 OnSetTitle(wxFileNameFromPath(m_OpenedPage));
442
443 if (needs_refresh)
444 {
445 m_tmpCanDrawLocks--;
446 Refresh();
447 }
448 else
449 m_tmpCanDrawLocks--;
450
451 return rt_val;
452 }
453
454
455 bool wxHtmlWindow::LoadFile(const wxFileName& filename)
456 {
457 wxString url = wxFileSystem::FileNameToURL(filename);
458 return LoadPage(url);
459 }
460
461
462 bool wxHtmlWindow::ScrollToAnchor(const wxString& anchor)
463 {
464 const wxHtmlCell *c = m_Cell->Find(wxHTML_COND_ISANCHOR, &anchor);
465 if (!c)
466 {
467 wxLogWarning(_("HTML anchor %s does not exist."), anchor.c_str());
468 return FALSE;
469 }
470 else
471 {
472 int y;
473
474 for (y = 0; c != NULL; c = c->GetParent()) y += c->GetPosY();
475 Scroll(-1, y / wxHTML_SCROLL_STEP);
476 m_OpenedAnchor = anchor;
477 return TRUE;
478 }
479 }
480
481
482 void wxHtmlWindow::OnSetTitle(const wxString& title)
483 {
484 if (m_RelatedFrame)
485 {
486 wxString tit;
487 tit.Printf(m_TitleFormat, title.c_str());
488 m_RelatedFrame->SetTitle(tit);
489 }
490 m_OpenedPageTitle = title;
491 }
492
493
494
495
496
497 void wxHtmlWindow::CreateLayout()
498 {
499 int ClientWidth, ClientHeight;
500
501 if (!m_Cell) return;
502
503 if (m_Style & wxHW_SCROLLBAR_NEVER)
504 {
505 SetScrollbars(wxHTML_SCROLL_STEP, 1, m_Cell->GetWidth() / wxHTML_SCROLL_STEP, 0); // always off
506 GetClientSize(&ClientWidth, &ClientHeight);
507 m_Cell->Layout(ClientWidth);
508 }
509
510 else {
511 GetClientSize(&ClientWidth, &ClientHeight);
512 m_Cell->Layout(ClientWidth);
513 if (ClientHeight < m_Cell->GetHeight() + GetCharHeight())
514 {
515 SetScrollbars(
516 wxHTML_SCROLL_STEP, wxHTML_SCROLL_STEP,
517 m_Cell->GetWidth() / wxHTML_SCROLL_STEP,
518 (m_Cell->GetHeight() + GetCharHeight()) / wxHTML_SCROLL_STEP
519 /*cheat: top-level frag is always container*/);
520 }
521 else /* we fit into window, no need for scrollbars */
522 {
523 SetScrollbars(wxHTML_SCROLL_STEP, 1, m_Cell->GetWidth() / wxHTML_SCROLL_STEP, 0); // disable...
524 GetClientSize(&ClientWidth, &ClientHeight);
525 m_Cell->Layout(ClientWidth); // ...and relayout
526 }
527 }
528 }
529
530
531
532 void wxHtmlWindow::ReadCustomization(wxConfigBase *cfg, wxString path)
533 {
534 wxString oldpath;
535 wxString tmp;
536 int p_fontsizes[7];
537 wxString p_fff, p_ffn;
538
539 if (path != wxEmptyString)
540 {
541 oldpath = cfg->GetPath();
542 cfg->SetPath(path);
543 }
544
545 m_Borders = cfg->Read(wxT("wxHtmlWindow/Borders"), m_Borders);
546 p_fff = cfg->Read(wxT("wxHtmlWindow/FontFaceFixed"), m_Parser->m_FontFaceFixed);
547 p_ffn = cfg->Read(wxT("wxHtmlWindow/FontFaceNormal"), m_Parser->m_FontFaceNormal);
548 for (int i = 0; i < 7; i++)
549 {
550 tmp.Printf(wxT("wxHtmlWindow/FontsSize%i"), i);
551 p_fontsizes[i] = cfg->Read(tmp, m_Parser->m_FontsSizes[i]);
552 }
553 SetFonts(p_ffn, p_fff, p_fontsizes);
554
555 if (path != wxEmptyString)
556 cfg->SetPath(oldpath);
557 }
558
559
560
561 void wxHtmlWindow::WriteCustomization(wxConfigBase *cfg, wxString path)
562 {
563 wxString oldpath;
564 wxString tmp;
565
566 if (path != wxEmptyString)
567 {
568 oldpath = cfg->GetPath();
569 cfg->SetPath(path);
570 }
571
572 cfg->Write(wxT("wxHtmlWindow/Borders"), (long) m_Borders);
573 cfg->Write(wxT("wxHtmlWindow/FontFaceFixed"), m_Parser->m_FontFaceFixed);
574 cfg->Write(wxT("wxHtmlWindow/FontFaceNormal"), m_Parser->m_FontFaceNormal);
575 for (int i = 0; i < 7; i++)
576 {
577 tmp.Printf(wxT("wxHtmlWindow/FontsSize%i"), i);
578 cfg->Write(tmp, (long) m_Parser->m_FontsSizes[i]);
579 }
580
581 if (path != wxEmptyString)
582 cfg->SetPath(oldpath);
583 }
584
585
586
587 bool wxHtmlWindow::HistoryBack()
588 {
589 wxString a, l;
590
591 if (m_HistoryPos < 1) return FALSE;
592
593 // store scroll position into history item:
594 int x, y;
595 GetViewStart(&x, &y);
596 (*m_History)[m_HistoryPos].SetPos(y);
597
598 // go to previous position:
599 m_HistoryPos--;
600
601 l = (*m_History)[m_HistoryPos].GetPage();
602 a = (*m_History)[m_HistoryPos].GetAnchor();
603 m_HistoryOn = FALSE;
604 m_tmpCanDrawLocks++;
605 if (a == wxEmptyString) LoadPage(l);
606 else LoadPage(l + wxT("#") + a);
607 m_HistoryOn = TRUE;
608 m_tmpCanDrawLocks--;
609 Scroll(0, (*m_History)[m_HistoryPos].GetPos());
610 Refresh();
611 return TRUE;
612 }
613
614 bool wxHtmlWindow::HistoryCanBack()
615 {
616 if (m_HistoryPos < 1) return FALSE;
617 return TRUE ;
618 }
619
620
621 bool wxHtmlWindow::HistoryForward()
622 {
623 wxString a, l;
624
625 if (m_HistoryPos == -1) return FALSE;
626 if (m_HistoryPos >= (int)m_History->GetCount() - 1)return FALSE;
627
628 m_OpenedPage = wxEmptyString; // this will disable adding new entry into history in LoadPage()
629
630 m_HistoryPos++;
631 l = (*m_History)[m_HistoryPos].GetPage();
632 a = (*m_History)[m_HistoryPos].GetAnchor();
633 m_HistoryOn = FALSE;
634 m_tmpCanDrawLocks++;
635 if (a == wxEmptyString) LoadPage(l);
636 else LoadPage(l + wxT("#") + a);
637 m_HistoryOn = TRUE;
638 m_tmpCanDrawLocks--;
639 Scroll(0, (*m_History)[m_HistoryPos].GetPos());
640 Refresh();
641 return TRUE;
642 }
643
644 bool wxHtmlWindow::HistoryCanForward()
645 {
646 if (m_HistoryPos == -1) return FALSE;
647 if (m_HistoryPos >= (int)m_History->GetCount() - 1)return FALSE;
648 return TRUE ;
649 }
650
651
652 void wxHtmlWindow::HistoryClear()
653 {
654 m_History->Empty();
655 m_HistoryPos = -1;
656 }
657
658 void wxHtmlWindow::AddProcessor(wxHtmlProcessor *processor)
659 {
660 if (!m_Processors)
661 {
662 m_Processors = new wxHtmlProcessorList;
663 }
664 wxHtmlProcessorList::compatibility_iterator node;
665
666 for (node = m_Processors->GetFirst(); node; node = node->GetNext())
667 {
668 if (processor->GetPriority() > node->GetData()->GetPriority())
669 {
670 m_Processors->Insert(node, processor);
671 return;
672 }
673 }
674 m_Processors->Append(processor);
675 }
676
677 /*static */ void wxHtmlWindow::AddGlobalProcessor(wxHtmlProcessor *processor)
678 {
679 if (!m_GlobalProcessors)
680 {
681 m_GlobalProcessors = new wxHtmlProcessorList;
682 }
683 wxHtmlProcessorList::compatibility_iterator node;
684
685 for (node = m_GlobalProcessors->GetFirst(); node; node = node->GetNext())
686 {
687 if (processor->GetPriority() > node->GetData()->GetPriority())
688 {
689 m_GlobalProcessors->Insert(node, processor);
690 return;
691 }
692 }
693 m_GlobalProcessors->Append(processor);
694 }
695
696
697
698 wxList wxHtmlWindow::m_Filters;
699 wxHtmlFilter *wxHtmlWindow::m_DefaultFilter = NULL;
700 wxHtmlProcessorList *wxHtmlWindow::m_GlobalProcessors = NULL;
701
702 void wxHtmlWindow::CleanUpStatics()
703 {
704 wxDELETE(m_DefaultFilter);
705 WX_CLEAR_LIST(wxList, m_Filters);
706 if (m_GlobalProcessors)
707 WX_CLEAR_LIST(wxHtmlProcessorList, *m_GlobalProcessors);
708 wxDELETE(m_GlobalProcessors);
709 }
710
711
712
713 void wxHtmlWindow::AddFilter(wxHtmlFilter *filter)
714 {
715 m_Filters.Append(filter);
716 }
717
718
719 bool wxHtmlWindow::IsSelectionEnabled() const
720 {
721 #if wxUSE_CLIPBOARD
722 return !(m_Style & wxHW_NO_SELECTION);
723 #else
724 return false;
725 #endif
726 }
727
728
729 #if wxUSE_CLIPBOARD
730 wxString wxHtmlWindow::SelectionToText()
731 {
732 if ( !m_selection )
733 return wxEmptyString;
734
735 wxClientDC dc(this);
736
737 const wxHtmlCell *end = m_selection->GetToCell();
738 wxString text;
739 wxHtmlTerminalCellsInterator i(m_selection->GetFromCell(), end);
740 if ( i )
741 {
742 text << i->ConvertToText(m_selection);
743 ++i;
744 }
745 const wxHtmlCell *prev = *i;
746 while ( i )
747 {
748 if ( prev->GetParent() != i->GetParent() )
749 text << _T('\n');
750 text << i->ConvertToText(*i == end ? m_selection : NULL);
751 prev = *i;
752 ++i;
753 }
754 return text;
755 }
756
757 #endif // wxUSE_CLIPBOARD
758
759 void wxHtmlWindow::CopySelection(ClipboardType t)
760 {
761 #if wxUSE_CLIPBOARD
762 if ( m_selection )
763 {
764 #ifdef __UNIX__
765 wxTheClipboard->UsePrimarySelection(t == Primary);
766 #else // !__UNIX__
767 // Primary selection exists only under X11, so don't do anything under
768 // the other platforms when we try to access it
769 //
770 // TODO: this should be abstracted at wxClipboard level!
771 if ( t == Primary )
772 return;
773 #endif // __UNIX__/!__UNIX__
774
775 if ( wxTheClipboard->Open() )
776 {
777 const wxString txt(SelectionToText());
778 wxTheClipboard->SetData(new wxTextDataObject(txt));
779 wxTheClipboard->Close();
780 wxLogTrace(_T("wxhtmlselection"),
781 _("Copied to clipboard:\"%s\""), txt.c_str());
782 }
783 }
784 #endif // wxUSE_CLIPBOARD
785 }
786
787
788 void wxHtmlWindow::OnLinkClicked(const wxHtmlLinkInfo& link)
789 {
790 const wxMouseEvent *e = link.GetEvent();
791 if (e == NULL || e->LeftUp())
792 LoadPage(link.GetHref());
793 }
794
795 void wxHtmlWindow::OnCellClicked(wxHtmlCell *cell,
796 wxCoord x, wxCoord y,
797 const wxMouseEvent& event)
798 {
799 wxCHECK_RET( cell, _T("can't be called with NULL cell") );
800
801 cell->OnMouseClick(this, x, y, event);
802 }
803
804 void wxHtmlWindow::OnCellMouseHover(wxHtmlCell * WXUNUSED(cell),
805 wxCoord WXUNUSED(x), wxCoord WXUNUSED(y))
806 {
807 // do nothing here
808 }
809
810 void wxHtmlWindow::OnEraseBackground(wxEraseEvent& WXUNUSED(event))
811 {
812 }
813
814 void wxHtmlWindow::OnPaint(wxPaintEvent& WXUNUSED(event))
815 {
816 wxPaintDC dc(this);
817
818 if (m_tmpCanDrawLocks > 0 || m_Cell == NULL) return;
819
820 int x, y;
821 GetViewStart(&x, &y);
822 wxRect rect = GetUpdateRegion().GetBox();
823 wxSize sz = GetSize();
824
825 wxMemoryDC dcm;
826 if ( !m_backBuffer )
827 m_backBuffer = new wxBitmap(sz.x, sz.y);
828 dcm.SelectObject(*m_backBuffer);
829 dcm.SetBackground(wxBrush(GetBackgroundColour(), wxSOLID));
830 dcm.Clear();
831 PrepareDC(dcm);
832 dcm.SetMapMode(wxMM_TEXT);
833 dcm.SetBackgroundMode(wxTRANSPARENT);
834
835 wxHtmlRenderingInfo rinfo;
836 wxDefaultHtmlRenderingStyle rstyle;
837 rinfo.SetSelection(m_selection);
838 rinfo.SetStyle(&rstyle);
839 m_Cell->Draw(dcm, 0, 0,
840 y * wxHTML_SCROLL_STEP + rect.GetTop(),
841 y * wxHTML_SCROLL_STEP + rect.GetBottom(),
842 rinfo);
843
844 //#define DEBUG_HTML_SELECTION
845 #ifdef DEBUG_HTML_SELECTION
846 {
847 int xc, yc, x, y;
848 wxGetMousePosition(&xc, &yc);
849 ScreenToClient(&xc, &yc);
850 CalcUnscrolledPosition(xc, yc, &x, &y);
851 wxHtmlCell *at = m_Cell->FindCellByPos(x, y);
852 wxHtmlCell *before =
853 m_Cell->FindCellByPos(x, y, wxHTML_FIND_NEAREST_BEFORE);
854 wxHtmlCell *after =
855 m_Cell->FindCellByPos(x, y, wxHTML_FIND_NEAREST_AFTER);
856
857 dcm.SetBrush(*wxTRANSPARENT_BRUSH);
858 dcm.SetPen(*wxBLACK_PEN);
859 if (at)
860 dcm.DrawRectangle(at->GetAbsPos(),
861 wxSize(at->GetWidth(),at->GetHeight()));
862 dcm.SetPen(*wxGREEN_PEN);
863 if (before)
864 dcm.DrawRectangle(before->GetAbsPos().x+1, before->GetAbsPos().y+1,
865 before->GetWidth()-2,before->GetHeight()-2);
866 dcm.SetPen(*wxRED_PEN);
867 if (after)
868 dcm.DrawRectangle(after->GetAbsPos().x+2, after->GetAbsPos().y+2,
869 after->GetWidth()-4,after->GetHeight()-4);
870 }
871 #endif
872
873 dcm.SetDeviceOrigin(0,0);
874 dc.Blit(0, rect.GetTop(),
875 sz.x, rect.GetBottom() - rect.GetTop() + 1,
876 &dcm,
877 0, rect.GetTop());
878 }
879
880
881
882
883 void wxHtmlWindow::OnSize(wxSizeEvent& event)
884 {
885 wxDELETE(m_backBuffer);
886
887 wxScrolledWindow::OnSize(event);
888 CreateLayout();
889
890 // Recompute selection if necessary:
891 if ( m_selection )
892 {
893 m_selection->Set(m_selection->GetFromCell(),
894 m_selection->GetToCell());
895 m_selection->ClearPrivPos();
896 }
897
898 Refresh();
899 }
900
901
902 void wxHtmlWindow::OnMouseMove(wxMouseEvent& WXUNUSED(event))
903 {
904 m_tmpMouseMoved = true;
905 }
906
907 void wxHtmlWindow::OnMouseDown(wxMouseEvent& event)
908 {
909 #if wxUSE_CLIPBOARD
910 if ( event.LeftDown() && IsSelectionEnabled() )
911 {
912 const long TRIPLECLICK_LEN = 200; // 0.2 sec after doubleclick
913 if ( wxGetLocalTimeMillis() - m_lastDoubleClick <= TRIPLECLICK_LEN )
914 {
915 SelectLine(CalcUnscrolledPosition(event.GetPosition()));
916
917 CopySelection();
918 }
919 else
920 {
921 m_makingSelection = true;
922
923 if ( m_selection )
924 {
925 wxDELETE(m_selection);
926 Refresh();
927 }
928 m_tmpSelFromPos = CalcUnscrolledPosition(event.GetPosition());
929 m_tmpSelFromCell = NULL;
930
931 CaptureMouse();
932 }
933 }
934 #endif // wxUSE_CLIPBOARD
935 }
936
937 void wxHtmlWindow::OnMouseUp(wxMouseEvent& event)
938 {
939 #if wxUSE_CLIPBOARD
940 if ( m_makingSelection )
941 {
942 ReleaseMouse();
943 m_makingSelection = false;
944
945 // did the user move the mouse far enough from starting point?
946 if ( m_selection )
947 {
948 CopySelection(Primary);
949
950 // we don't want mouse up event that ended selecting to be
951 // handled as mouse click and e.g. follow hyperlink:
952 return;
953 }
954 }
955 #endif // wxUSE_CLIPBOARD
956
957 SetFocus();
958 if ( m_Cell )
959 {
960 wxPoint pos = CalcUnscrolledPosition(event.GetPosition());
961 wxHtmlCell *cell = m_Cell->FindCellByPos(pos.x, pos.y);
962
963 // check is needed because FindCellByPos returns terminal cell and
964 // containers may have empty borders -- in this case NULL will be
965 // returned
966 if ( cell )
967 OnCellClicked(cell, pos.x, pos.y, event);
968 }
969 }
970
971
972
973 void wxHtmlWindow::OnInternalIdle()
974 {
975 wxWindow::OnInternalIdle();
976
977 if (m_tmpMouseMoved && (m_Cell != NULL))
978 {
979 #ifdef DEBUG_HTML_SELECTION
980 Refresh();
981 #endif
982 int xc, yc, x, y;
983 wxGetMousePosition(&xc, &yc);
984 ScreenToClient(&xc, &yc);
985 CalcUnscrolledPosition(xc, yc, &x, &y);
986
987 wxHtmlCell *cell = m_Cell->FindCellByPos(x, y);
988
989 // handle selection update:
990 if ( m_makingSelection )
991 {
992 if ( !m_tmpSelFromCell )
993 m_tmpSelFromCell = m_Cell->FindCellByPos(
994 m_tmpSelFromPos.x,m_tmpSelFromPos.y);
995
996 // NB: a trick - we adjust selFromPos to be upper left or bottom
997 // right corner of the first cell of the selection depending
998 // on whether the mouse is moving to the right or to the left.
999 // This gives us more "natural" behaviour when selecting
1000 // a line (specifically, first cell of the next line is not
1001 // included if you drag selection from left to right over
1002 // entire line):
1003 wxPoint dirFromPos;
1004 if ( !m_tmpSelFromCell )
1005 {
1006 dirFromPos = m_tmpSelFromPos;
1007 }
1008 else
1009 {
1010 dirFromPos = m_tmpSelFromCell->GetAbsPos();
1011 if ( x < m_tmpSelFromPos.x )
1012 {
1013 dirFromPos.x += m_tmpSelFromCell->GetWidth();
1014 dirFromPos.y += m_tmpSelFromCell->GetHeight();
1015 }
1016 }
1017 bool goingDown = dirFromPos.y < y ||
1018 (dirFromPos.y == y && dirFromPos.x < x);
1019
1020 // determine selection span:
1021 if ( /*still*/ !m_tmpSelFromCell )
1022 {
1023 if (goingDown)
1024 {
1025 m_tmpSelFromCell = m_Cell->FindCellByPos(
1026 m_tmpSelFromPos.x,m_tmpSelFromPos.y,
1027 wxHTML_FIND_NEAREST_AFTER);
1028 if (!m_tmpSelFromCell)
1029 m_tmpSelFromCell = m_Cell->GetFirstTerminal();
1030 }
1031 else
1032 {
1033 m_tmpSelFromCell = m_Cell->FindCellByPos(
1034 m_tmpSelFromPos.x,m_tmpSelFromPos.y,
1035 wxHTML_FIND_NEAREST_BEFORE);
1036 if (!m_tmpSelFromCell)
1037 m_tmpSelFromCell = m_Cell->GetLastTerminal();
1038 }
1039 }
1040
1041 wxHtmlCell *selcell = cell;
1042 if (!selcell)
1043 {
1044 if (goingDown)
1045 {
1046 selcell = m_Cell->FindCellByPos(x, y,
1047 wxHTML_FIND_NEAREST_BEFORE);
1048 if (!selcell)
1049 selcell = m_Cell->GetLastTerminal();
1050 }
1051 else
1052 {
1053 selcell = m_Cell->FindCellByPos(x, y,
1054 wxHTML_FIND_NEAREST_AFTER);
1055 if (!selcell)
1056 selcell = m_Cell->GetFirstTerminal();
1057 }
1058 }
1059
1060 // NB: it may *rarely* happen that the code above didn't find one
1061 // of the cells, e.g. if wxHtmlWindow doesn't contain any
1062 // visible cells.
1063 if ( selcell && m_tmpSelFromCell )
1064 {
1065 if ( !m_selection )
1066 {
1067 // start selecting only if mouse movement was big enough
1068 // (otherwise it was meant as mouse click, not selection):
1069 const int PRECISION = 2;
1070 wxPoint diff = m_tmpSelFromPos - wxPoint(x,y);
1071 if (abs(diff.x) > PRECISION || abs(diff.y) > PRECISION)
1072 {
1073 m_selection = new wxHtmlSelection();
1074 }
1075 }
1076 if ( m_selection )
1077 {
1078 if ( m_tmpSelFromCell->IsBefore(selcell) )
1079 {
1080 m_selection->Set(m_tmpSelFromPos, m_tmpSelFromCell,
1081 wxPoint(x,y), selcell); }
1082 else
1083 {
1084 m_selection->Set(wxPoint(x,y), selcell,
1085 m_tmpSelFromPos, m_tmpSelFromCell);
1086 }
1087 m_selection->ClearPrivPos();
1088 Refresh();
1089 }
1090 }
1091 }
1092
1093 // handle cursor and status bar text changes:
1094 if ( cell != m_tmpLastCell )
1095 {
1096 wxHtmlLinkInfo *lnk = cell ? cell->GetLink(x, y) : NULL;
1097 wxCursor cur;
1098 if (cell)
1099 cur = cell->GetCursor();
1100 else
1101 cur = *wxSTANDARD_CURSOR;
1102 SetCursor(cur);
1103
1104 if (lnk != m_tmpLastLink)
1105 {
1106 if (lnk == NULL)
1107 {
1108 if (m_RelatedStatusBar != -1)
1109 m_RelatedFrame->SetStatusText(wxEmptyString,
1110 m_RelatedStatusBar);
1111 }
1112 else
1113 {
1114 if (m_RelatedStatusBar != -1)
1115 m_RelatedFrame->SetStatusText(lnk->GetHref(),
1116 m_RelatedStatusBar);
1117 }
1118 m_tmpLastLink = lnk;
1119 }
1120
1121 m_tmpLastCell = cell;
1122 }
1123 else // mouse moved but stayed in the same cell
1124 {
1125 if ( cell )
1126 OnCellMouseHover(cell, x, y);
1127 }
1128
1129 m_tmpMouseMoved = FALSE;
1130 }
1131 }
1132
1133 #if wxUSE_CLIPBOARD
1134 void wxHtmlWindow::StopAutoScrolling()
1135 {
1136 if ( m_timerAutoScroll )
1137 {
1138 wxDELETE(m_timerAutoScroll);
1139 }
1140 }
1141
1142 void wxHtmlWindow::OnMouseEnter(wxMouseEvent& event)
1143 {
1144 StopAutoScrolling();
1145 event.Skip();
1146 }
1147
1148 void wxHtmlWindow::OnMouseLeave(wxMouseEvent& event)
1149 {
1150 // don't prevent the usual processing of the event from taking place
1151 event.Skip();
1152
1153 // when a captured mouse leave a scrolled window we start generate
1154 // scrolling events to allow, for example, extending selection beyond the
1155 // visible area in some controls
1156 if ( wxWindow::GetCapture() == this )
1157 {
1158 // where is the mouse leaving?
1159 int pos, orient;
1160 wxPoint pt = event.GetPosition();
1161 if ( pt.x < 0 )
1162 {
1163 orient = wxHORIZONTAL;
1164 pos = 0;
1165 }
1166 else if ( pt.y < 0 )
1167 {
1168 orient = wxVERTICAL;
1169 pos = 0;
1170 }
1171 else // we're lower or to the right of the window
1172 {
1173 wxSize size = GetClientSize();
1174 if ( pt.x > size.x )
1175 {
1176 orient = wxHORIZONTAL;
1177 pos = GetVirtualSize().x / wxHTML_SCROLL_STEP;
1178 }
1179 else if ( pt.y > size.y )
1180 {
1181 orient = wxVERTICAL;
1182 pos = GetVirtualSize().y / wxHTML_SCROLL_STEP;
1183 }
1184 else // this should be impossible
1185 {
1186 // but seems to happen sometimes under wxMSW - maybe it's a bug
1187 // there but for now just ignore it
1188
1189 //wxFAIL_MSG( _T("can't understand where has mouse gone") );
1190
1191 return;
1192 }
1193 }
1194
1195 // only start the auto scroll timer if the window can be scrolled in
1196 // this direction
1197 if ( !HasScrollbar(orient) )
1198 return;
1199
1200 delete m_timerAutoScroll;
1201 m_timerAutoScroll = new wxHtmlWinAutoScrollTimer
1202 (
1203 this,
1204 pos == 0 ? wxEVT_SCROLLWIN_LINEUP
1205 : wxEVT_SCROLLWIN_LINEDOWN,
1206 pos,
1207 orient
1208 );
1209 m_timerAutoScroll->Start(50); // FIXME: make configurable
1210 }
1211 }
1212
1213 void wxHtmlWindow::OnKeyUp(wxKeyEvent& event)
1214 {
1215 if ( IsSelectionEnabled() &&
1216 event.GetKeyCode() == 'C' && event.ControlDown() )
1217 {
1218 if ( m_selection )
1219 CopySelection();
1220 }
1221 }
1222
1223 void wxHtmlWindow::OnCopy(wxCommandEvent& WXUNUSED(event))
1224 {
1225 if ( m_selection )
1226 CopySelection();
1227 }
1228
1229 void wxHtmlWindow::OnDoubleClick(wxMouseEvent& event)
1230 {
1231 // select word under cursor:
1232 if ( IsSelectionEnabled() )
1233 {
1234 SelectWord(CalcUnscrolledPosition(event.GetPosition()));
1235
1236 CopySelection(Primary);
1237
1238 m_lastDoubleClick = wxGetLocalTimeMillis();
1239 }
1240 else
1241 event.Skip();
1242 }
1243
1244 void wxHtmlWindow::SelectWord(const wxPoint& pos)
1245 {
1246 wxHtmlCell *cell = m_Cell->FindCellByPos(pos.x, pos.y);
1247 if ( cell )
1248 {
1249 delete m_selection;
1250 m_selection = new wxHtmlSelection();
1251 m_selection->Set(cell, cell);
1252 RefreshRect(wxRect(CalcScrolledPosition(cell->GetAbsPos()),
1253 wxSize(cell->GetWidth(), cell->GetHeight())));
1254 }
1255 }
1256
1257 void wxHtmlWindow::SelectLine(const wxPoint& pos)
1258 {
1259 wxHtmlCell *cell = m_Cell->FindCellByPos(pos.x, pos.y);
1260 if ( cell )
1261 {
1262 // We use following heuristic to find a "line": let the line be all
1263 // cells in same container as the cell under mouse cursor that are
1264 // neither completely above nor completely bellow the clicked cell
1265 // (i.e. are likely to be words positioned on same line of text).
1266
1267 int y1 = cell->GetAbsPos().y;
1268 int y2 = y1 + cell->GetHeight();
1269 int y;
1270 const wxHtmlCell *c;
1271 const wxHtmlCell *before = NULL;
1272 const wxHtmlCell *after = NULL;
1273
1274 // find last cell of line:
1275 for ( c = cell->GetNext(); c; c = c->GetNext())
1276 {
1277 y = c->GetAbsPos().y;
1278 if ( y + c->GetHeight() > y1 && y < y2 )
1279 after = c;
1280 else
1281 break;
1282 }
1283 if ( !after )
1284 after = cell;
1285
1286 // find first cell of line:
1287 for ( c = cell->GetParent()->GetFirstChild();
1288 c && c != cell; c = c->GetNext())
1289 {
1290 y = c->GetAbsPos().y;
1291 if ( y + c->GetHeight() > y1 && y < y2 )
1292 {
1293 if ( ! before )
1294 before = c;
1295 }
1296 else
1297 before = NULL;
1298 }
1299 if ( !before )
1300 before = cell;
1301
1302 delete m_selection;
1303 m_selection = new wxHtmlSelection();
1304 m_selection->Set(before, after);
1305
1306 Refresh();
1307 }
1308 }
1309 #endif // wxUSE_CLIPBOARD
1310
1311
1312
1313 IMPLEMENT_ABSTRACT_CLASS(wxHtmlProcessor,wxObject)
1314
1315 #if wxUSE_EXTENDED_RTTI
1316 IMPLEMENT_DYNAMIC_CLASS_XTI(wxHtmlWindow, wxScrolledWindow,"wx/html/htmlwin.h")
1317
1318 wxBEGIN_PROPERTIES_TABLE(wxHtmlWindow)
1319 /*
1320 TODO PROPERTIES
1321 style , wxHW_SCROLLBAR_AUTO
1322 borders , (dimension)
1323 url , string
1324 htmlcode , string
1325 */
1326 wxEND_PROPERTIES_TABLE()
1327
1328 wxBEGIN_HANDLERS_TABLE(wxHtmlWindow)
1329 wxEND_HANDLERS_TABLE()
1330
1331 wxCONSTRUCTOR_5( wxHtmlWindow , wxWindow* , Parent , wxWindowID , Id , wxPoint , Position , wxSize , Size , long , WindowStyle )
1332 #else
1333 IMPLEMENT_DYNAMIC_CLASS(wxHtmlWindow,wxScrolledWindow)
1334 #endif
1335
1336 BEGIN_EVENT_TABLE(wxHtmlWindow, wxScrolledWindow)
1337 EVT_SIZE(wxHtmlWindow::OnSize)
1338 EVT_LEFT_DOWN(wxHtmlWindow::OnMouseDown)
1339 EVT_LEFT_UP(wxHtmlWindow::OnMouseUp)
1340 EVT_RIGHT_UP(wxHtmlWindow::OnMouseUp)
1341 EVT_MOTION(wxHtmlWindow::OnMouseMove)
1342 EVT_ERASE_BACKGROUND(wxHtmlWindow::OnEraseBackground)
1343 EVT_PAINT(wxHtmlWindow::OnPaint)
1344 #if wxUSE_CLIPBOARD
1345 EVT_LEFT_DCLICK(wxHtmlWindow::OnDoubleClick)
1346 EVT_ENTER_WINDOW(wxHtmlWindow::OnMouseEnter)
1347 EVT_LEAVE_WINDOW(wxHtmlWindow::OnMouseLeave)
1348 EVT_KEY_UP(wxHtmlWindow::OnKeyUp)
1349 EVT_MENU(wxID_COPY, wxHtmlWindow::OnCopy)
1350 #endif // wxUSE_CLIPBOARD
1351 END_EVENT_TABLE()
1352
1353
1354
1355
1356
1357 // A module to allow initialization/cleanup
1358 // without calling these functions from app.cpp or from
1359 // the user's application.
1360
1361 class wxHtmlWinModule: public wxModule
1362 {
1363 DECLARE_DYNAMIC_CLASS(wxHtmlWinModule)
1364 public:
1365 wxHtmlWinModule() : wxModule() {}
1366 bool OnInit() { return TRUE; }
1367 void OnExit() { wxHtmlWindow::CleanUpStatics(); }
1368 };
1369
1370 IMPLEMENT_DYNAMIC_CLASS(wxHtmlWinModule, wxModule)
1371
1372
1373 // This hack forces the linker to always link in m_* files
1374 // (wxHTML doesn't work without handlers from these files)
1375 #include "wx/html/forcelnk.h"
1376 FORCE_WXHTML_MODULES()
1377
1378 #endif // wxUSE_HTML
1379