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