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