]> git.saurik.com Git - wxWidgets.git/blob - samples/web/web.cpp
Update the sample to show how to block navigation and new window events
[wxWidgets.git] / samples / web / web.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: web.cpp
3 // Purpose: wxWebView sample
4 // Author: Marianne Gagnon
5 // Id: $Id$
6 // Copyright: (c) 2010 Marianne Gagnon, Steven Lamerton
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 // ----------------------------------------------------------------------------
11 // headers
12 // ----------------------------------------------------------------------------
13
14 // For compilers that support precompilation, includes "wx/wx.h".
15 #include "wx/wxprec.h"
16
17 #ifdef __BORLANDC__
18 #pragma hdrstop
19 #endif
20
21 #ifndef WX_PRECOMP
22 #include "wx/wx.h"
23 #endif
24
25 #include <wx/artprov.h>
26 #include <wx/notifmsg.h>
27 #include <wx/settings.h>
28 #include <wx/webview.h>
29 #include <wx/infobar.h>
30
31 #if !defined(__WXMSW__) && !defined(__WXPM__)
32 #include "../sample.xpm"
33 #endif
34
35 #if wxUSE_STC
36 #include <wx/stc/stc.h>
37 #else
38 #error "wxStyledTextControl is needed by this sample"
39 #endif
40
41 #include "stop.xpm"
42 #include "refresh.xpm"
43 #include "wxlogo.xpm"
44
45 class WebApp : public wxApp
46 {
47 public:
48 virtual bool OnInit();
49 };
50
51 class WebFrame : public wxFrame
52 {
53 public:
54 WebFrame();
55
56 void OnAnimationTimer(wxTimerEvent& evt);
57 void UpdateState();
58 void OnUrl(wxCommandEvent& evt);
59 void OnBack(wxCommandEvent& evt);
60 void OnForward(wxCommandEvent& evt);
61 void OnStop(wxCommandEvent& evt);
62 void OnReload(wxCommandEvent& evt);
63 void OnNavigationRequest(wxWebNavigationEvent& evt);
64 void OnNavigationComplete(wxWebNavigationEvent& evt);
65 void OnDocumentLoaded(wxWebNavigationEvent& evt);
66 void OnNewWindow(wxWebNavigationEvent& evt);
67 void OnViewSourceRequest(wxCommandEvent& evt);
68 void OnToolsClicked(wxCommandEvent& evt);
69 void OnSetZoom(wxCommandEvent& evt);
70 void OnError(wxWebNavigationEvent& evt);
71 void OnPrint(wxCommandEvent& evt);
72
73 private:
74 wxTextCtrl* m_url;
75 wxWebView* m_browser;
76
77 wxToolBar* m_toolbar;
78 wxToolBarToolBase* m_toolbar_back;
79 wxToolBarToolBase* m_toolbar_forward;
80 wxToolBarToolBase* m_toolbar_stop;
81 wxToolBarToolBase* m_toolbar_reload;
82 wxToolBarToolBase* m_toolbar_tools;
83
84 wxMenu* m_tools_menu;
85 wxMenuItem* m_tools_tiny;
86 wxMenuItem* m_tools_small;
87 wxMenuItem* m_tools_medium;
88 wxMenuItem* m_tools_large;
89 wxMenuItem* m_tools_largest;
90 wxMenuItem* m_tools_handle_navigation;
91 wxMenuItem* m_tools_handle_new_window;
92
93 wxTimer* m_timer;
94 int m_animation_angle;
95
96 wxInfoBar *m_info;
97 wxStaticText* m_info_text;
98 };
99
100 class SourceViewDialog : public wxDialog
101 {
102 public:
103 SourceViewDialog(wxWindow* parent, wxString source);
104 };
105
106 IMPLEMENT_APP(WebApp)
107
108 // ============================================================================
109 // implementation
110 // ============================================================================
111
112 bool WebApp::OnInit()
113 {
114 if ( !wxApp::OnInit() )
115 return false;
116
117 WebFrame *frame = new WebFrame();
118 frame->Show();
119
120 return true;
121 }
122
123 WebFrame::WebFrame() : wxFrame(NULL, wxID_ANY, "wxWebView Sample")
124 {
125 // set the frame icon
126 SetIcon(wxICON(sample));
127 SetTitle("wxWebView Sample");
128
129 m_timer = NULL;
130 m_animation_angle = 0;
131
132
133 wxBoxSizer* topsizer = new wxBoxSizer(wxVERTICAL);
134
135 // Create the toolbar
136 m_toolbar = CreateToolBar(wxTB_TEXT);
137 m_toolbar->SetToolBitmapSize(wxSize(32, 32));
138
139 wxBitmap back = wxArtProvider::GetBitmap(wxART_GO_BACK , wxART_TOOLBAR);
140 wxBitmap forward = wxArtProvider::GetBitmap(wxART_GO_FORWARD , wxART_TOOLBAR);
141 #ifdef __WXGTK__
142 wxBitmap stop = wxArtProvider::GetBitmap("gtk-stop", wxART_TOOLBAR);
143 #else
144 wxBitmap stop = wxBitmap(stop_xpm);
145 #endif
146 #ifdef __WXGTK__
147 wxBitmap refresh = wxArtProvider::GetBitmap("gtk-refresh", wxART_TOOLBAR);
148 #else
149 wxBitmap refresh = wxBitmap(refresh_xpm);
150 #endif
151
152 m_toolbar_back = m_toolbar->AddTool(wxID_ANY, _("Back"), back);
153 m_toolbar_forward = m_toolbar->AddTool(wxID_ANY, _("Forward"), forward);
154 m_toolbar_stop = m_toolbar->AddTool(wxID_ANY, _("Stop"), stop);
155 m_toolbar_reload = m_toolbar->AddTool(wxID_ANY, _("Reload"), refresh);
156 m_url = new wxTextCtrl(m_toolbar, wxID_ANY, wxT(""), wxDefaultPosition, wxSize(400, -1), wxTE_PROCESS_ENTER );
157 m_toolbar->AddControl(m_url, _("URL"));
158 m_toolbar_tools = m_toolbar->AddTool(wxID_ANY, _("Menu"), wxBitmap(wxlogo_xpm));
159
160 m_toolbar->Realize();
161
162 // Create the info panel
163 m_info = new wxInfoBar(this);
164 topsizer->Add(m_info, wxSizerFlags().Expand());
165
166 // Create the webview
167 m_browser = wxWebView::New(this, wxID_ANY, "http://www.wxwidgets.org");
168 topsizer->Add(m_browser, wxSizerFlags().Expand().Proportion(1));
169
170 SetSizer(topsizer);
171
172 // Create a log window
173 new wxLogWindow(this, _("Logging"));
174
175 // Create the Tools menu
176 m_tools_menu = new wxMenu();
177 wxMenuItem* print = m_tools_menu->Append(wxID_ANY , _("Print"));
178 wxMenuItem* viewSource = m_tools_menu->Append(wxID_ANY , _("View Source"));
179 m_tools_menu->AppendSeparator();
180 m_tools_tiny = m_tools_menu->AppendCheckItem(wxID_ANY, _("Tiny"));
181 m_tools_small = m_tools_menu->AppendCheckItem(wxID_ANY, _("Small"));
182 m_tools_medium = m_tools_menu->AppendCheckItem(wxID_ANY, _("Medium"));
183 m_tools_large = m_tools_menu->AppendCheckItem(wxID_ANY, _("Large"));
184 m_tools_largest = m_tools_menu->AppendCheckItem(wxID_ANY, _("Largest"));
185 m_tools_menu->AppendSeparator();
186 m_tools_handle_navigation = m_tools_menu->AppendCheckItem(wxID_ANY, _("Handle Navigation"));
187 m_tools_handle_new_window = m_tools_menu->AppendCheckItem(wxID_ANY, _("Handle New Windows"));
188
189 //By default we want to handle naigation and new windows
190 m_tools_handle_navigation->Check();
191 m_tools_handle_new_window->Check();
192
193
194 // Connect the toolbar events
195 Connect(m_toolbar_back->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
196 wxCommandEventHandler(WebFrame::OnBack), NULL, this );
197 Connect(m_toolbar_forward->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
198 wxCommandEventHandler(WebFrame::OnForward), NULL, this );
199 Connect(m_toolbar_stop->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
200 wxCommandEventHandler(WebFrame::OnStop), NULL, this );
201 Connect(m_toolbar_reload->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
202 wxCommandEventHandler(WebFrame::OnReload),NULL, this );
203 Connect(m_toolbar_tools->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
204 wxCommandEventHandler(WebFrame::OnToolsClicked), NULL, this );
205
206 Connect(m_url->GetId(), wxEVT_COMMAND_TEXT_ENTER,
207 wxCommandEventHandler(WebFrame::OnUrl), NULL, this );
208
209 // Connect the webview events
210 Connect(m_browser->GetId(), wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
211 wxWebNavigationEventHandler(WebFrame::OnNavigationRequest), NULL, this);
212 Connect(m_browser->GetId(), wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
213 wxWebNavigationEventHandler(WebFrame::OnNavigationComplete), NULL, this);
214 Connect(m_browser->GetId(), wxEVT_COMMAND_WEB_VIEW_LOADED,
215 wxWebNavigationEventHandler(WebFrame::OnDocumentLoaded), NULL, this);
216 Connect(m_browser->GetId(), wxEVT_COMMAND_WEB_VIEW_ERROR,
217 wxWebNavigationEventHandler(WebFrame::OnError), NULL, this);
218 Connect(m_browser->GetId(), wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
219 wxWebNavigationEventHandler(WebFrame::OnNewWindow), NULL, this);
220
221 // Connect the menu events
222 Connect(viewSource->GetId(), wxEVT_COMMAND_MENU_SELECTED,
223 wxCommandEventHandler(WebFrame::OnViewSourceRequest), NULL, this );
224 Connect(print->GetId(), wxEVT_COMMAND_MENU_SELECTED,
225 wxCommandEventHandler(WebFrame::OnPrint), NULL, this );
226 Connect(m_tools_tiny->GetId(), wxEVT_COMMAND_MENU_SELECTED,
227 wxCommandEventHandler(WebFrame::OnSetZoom), NULL, this );
228 Connect(m_tools_small->GetId(), wxEVT_COMMAND_MENU_SELECTED,
229 wxCommandEventHandler(WebFrame::OnSetZoom), NULL, this );
230 Connect(m_tools_medium->GetId(), wxEVT_COMMAND_MENU_SELECTED,
231 wxCommandEventHandler(WebFrame::OnSetZoom), NULL, this );
232 Connect(m_tools_large->GetId(), wxEVT_COMMAND_MENU_SELECTED,
233 wxCommandEventHandler(WebFrame::OnSetZoom), NULL, this );
234 Connect(m_tools_largest->GetId(), wxEVT_COMMAND_MENU_SELECTED,
235 wxCommandEventHandler(WebFrame::OnSetZoom), NULL, this );
236 }
237
238 void WebFrame::OnAnimationTimer(wxTimerEvent& evt)
239 {
240 m_animation_angle += 15;
241 if (m_animation_angle > 360) m_animation_angle -= 360;
242
243 wxBitmap image(32, 32);
244 {
245 wxMemoryDC dc;
246 dc.SelectObject(image);
247 dc.SetBackground(wxBrush(wxColour(255,0,255)));
248 dc.Clear();
249
250 if (m_animation_angle >= 0 && m_animation_angle <= 180)
251 {
252 dc.SetBrush(*wxYELLOW_BRUSH);
253 dc.SetPen(*wxYELLOW_PEN);
254 dc.DrawCircle(16 - int(sin(m_animation_angle*0.01745f /* convert to radians */)*14.0f),
255 16 + int(cos(m_animation_angle*0.01745f /* convert to radians */)*14.0f), 3 );
256 }
257
258 dc.DrawBitmap(wxBitmap(wxlogo_xpm), 0, 0, true);
259
260 if (m_animation_angle > 180)
261 {
262 dc.SetBrush(*wxYELLOW_BRUSH);
263 dc.SetPen(*wxYELLOW_PEN);
264 dc.DrawCircle(16 - int(sin(m_animation_angle*0.01745f /* convert to radians */)*14.0f),
265 16 + int(cos(m_animation_angle*0.01745f /* convert to radians */)*14.0f), 3 );
266 }
267 }
268 image.SetMask(new wxMask(image, wxColour(255,0,255)));
269 m_toolbar->SetToolNormalBitmap(m_toolbar_tools->GetId(), image);
270 }
271
272 /**
273 * Method that retrieves the current state from the web control and updates the GUI
274 * the reflect this current state.
275 */
276 void WebFrame::UpdateState()
277 {
278 m_toolbar->EnableTool( m_toolbar_back->GetId(), m_browser->CanGoBack() );
279 m_toolbar->EnableTool( m_toolbar_forward->GetId(), m_browser->CanGoForward() );
280
281 if (m_browser->IsBusy())
282 {
283 if (m_timer == NULL)
284 {
285 m_timer = new wxTimer(this);
286 this->Connect(wxEVT_TIMER, wxTimerEventHandler(WebFrame::OnAnimationTimer), NULL, this);
287 }
288 m_timer->Start(100); // start animation timer
289
290 m_toolbar->EnableTool( m_toolbar_stop->GetId(), true );
291 }
292 else
293 {
294 if (m_timer != NULL) m_timer->Stop(); // stop animation timer
295 m_toolbar->SetToolNormalBitmap(m_toolbar_tools->GetId(), wxBitmap(wxlogo_xpm));
296 m_toolbar->EnableTool( m_toolbar_stop->GetId(), false );
297 }
298
299 SetTitle( m_browser->GetCurrentTitle() );
300 m_url->SetValue( m_browser->GetCurrentURL() );
301 }
302
303 /**
304 * Callback invoked when user entered an URL and pressed enter
305 */
306 void WebFrame::OnUrl(wxCommandEvent& evt)
307 {
308 m_browser->LoadUrl( m_url->GetValue() );
309 UpdateState();
310 }
311
312 /**
313 * Callback invoked when user pressed the "back" button
314 */
315 void WebFrame::OnBack(wxCommandEvent& evt)
316 {
317 m_browser->GoBack();
318 UpdateState();
319 }
320
321 /**
322 * Callback invoked when user pressed the "forward" button
323 */
324 void WebFrame::OnForward(wxCommandEvent& evt)
325 {
326 m_browser->GoForward();
327 UpdateState();
328 }
329
330 /**
331 * Callback invoked when user pressed the "stop" button
332 */
333 void WebFrame::OnStop(wxCommandEvent& evt)
334 {
335 m_browser->Stop();
336 UpdateState();
337 }
338
339 /**
340 * Callback invoked when user pressed the "reload" button
341 */
342 void WebFrame::OnReload(wxCommandEvent& evt)
343 {
344 m_browser->Reload();
345 UpdateState();
346 }
347
348 /**
349 * Callback invoked when there is a request to load a new page (for instance
350 * when the user clicks a link)
351 */
352 void WebFrame::OnNavigationRequest(wxWebNavigationEvent& evt)
353 {
354 wxLogMessage("%s", "Navigation request to '" + evt.GetHref() + "' (target='" +
355 evt.GetTarget() + "')");
356
357 wxASSERT(m_browser->IsBusy());
358
359 //If we don't want to handle navigation then veto the event and navigation
360 //will not take place
361 if(!m_tools_handle_navigation->IsChecked())
362 evt.Veto();
363
364 UpdateState();
365 }
366
367 /**
368 * Callback invoked when a navigation request was accepted
369 */
370 void WebFrame::OnNavigationComplete(wxWebNavigationEvent& evt)
371 {
372 wxLogMessage("%s", "Navigation complete; url='" + evt.GetHref() + "'");
373 UpdateState();
374 }
375
376 /**
377 * Callback invoked when a page is finished loading
378 */
379 void WebFrame::OnDocumentLoaded(wxWebNavigationEvent& evt)
380 {
381 wxLogMessage("%s", "Document loaded; url='" + evt.GetHref() + "'");
382 UpdateState();
383 }
384
385 /**
386 * On new window, we veto to stop extra windows appearing
387 */
388 void WebFrame::OnNewWindow(wxWebNavigationEvent& evt)
389 {
390 wxLogMessage("%s", "New window; url='" + evt.GetHref() + "'");
391
392 //If we handle new window events then just load them in this window as we
393 //are a single window browser
394 if(m_tools_handle_new_window->IsChecked())
395 m_browser->LoadUrl(evt.GetHref());
396
397 //We always veto because we handle the event, otherwise under windows a new
398 //internet explorer windowis created
399 evt.Veto();
400
401 UpdateState();
402 }
403
404 /**
405 * Invoked when user selects the "View Source" menu item
406 */
407 void WebFrame::OnViewSourceRequest(wxCommandEvent& evt)
408 {
409 SourceViewDialog dlg(this, m_browser->GetPageSource());
410 dlg.ShowModal();
411 }
412
413 /**
414 * Invoked when user selects the "Menu" item
415 */
416 void WebFrame::OnToolsClicked(wxCommandEvent& evt)
417 {
418 if(m_browser->GetCurrentURL() == "")
419 return;
420
421 m_tools_tiny->Check(false);
422 m_tools_small->Check(false);
423 m_tools_medium->Check(false);
424 m_tools_large->Check(false);
425 m_tools_largest->Check(false);
426
427 wxWebViewZoom zoom = m_browser->GetZoom();
428 switch (zoom)
429 {
430 case wxWEB_VIEW_ZOOM_TINY:
431 m_tools_tiny->Check();
432 break;
433 case wxWEB_VIEW_ZOOM_SMALL:
434 m_tools_small->Check();
435 break;
436 case wxWEB_VIEW_ZOOM_MEDIUM:
437 m_tools_medium->Check();
438 break;
439 case wxWEB_VIEW_ZOOM_LARGE:
440 m_tools_large->Check();
441 break;
442 case wxWEB_VIEW_ZOOM_LARGEST:
443 m_tools_largest->Check();
444 break;
445 }
446
447 wxPoint position = ScreenToClient( wxGetMousePosition() );
448 PopupMenu(m_tools_menu, position.x, position.y);
449 }
450
451 /**
452 * Invoked when user selects the zoom size in the menu
453 */
454 void WebFrame::OnSetZoom(wxCommandEvent& evt)
455 {
456 if (evt.GetId() == m_tools_tiny->GetId())
457 {
458 m_browser->SetZoom(wxWEB_VIEW_ZOOM_TINY);
459 }
460 else if (evt.GetId() == m_tools_small->GetId())
461 {
462 m_browser->SetZoom(wxWEB_VIEW_ZOOM_SMALL);
463 }
464 else if (evt.GetId() == m_tools_medium->GetId())
465 {
466 m_browser->SetZoom(wxWEB_VIEW_ZOOM_MEDIUM);
467 }
468 else if (evt.GetId() == m_tools_large->GetId())
469 {
470 m_browser->SetZoom(wxWEB_VIEW_ZOOM_LARGE);
471 }
472 else if (evt.GetId() == m_tools_largest->GetId())
473 {
474 m_browser->SetZoom(wxWEB_VIEW_ZOOM_LARGEST);
475 }
476 else
477 {
478 wxFAIL;
479 }
480 }
481
482 /**
483 * Callback invoked when a loading error occurs
484 */
485 void WebFrame::OnError(wxWebNavigationEvent& evt)
486 {
487 wxString errorCategory;
488 switch (evt.GetInt())
489 {
490 case wxWEB_NAV_ERR_CONNECTION:
491 errorCategory = "wxWEB_NAV_ERR_CONNECTION";
492 break;
493
494 case wxWEB_NAV_ERR_CERTIFICATE:
495 errorCategory = "wxWEB_NAV_ERR_CERTIFICATE";
496 break;
497
498 case wxWEB_NAV_ERR_AUTH:
499 errorCategory = "wxWEB_NAV_ERR_AUTH";
500 break;
501
502 case wxWEB_NAV_ERR_SECURITY:
503 errorCategory = "wxWEB_NAV_ERR_SECURITY";
504 break;
505
506 case wxWEB_NAV_ERR_NOT_FOUND:
507 errorCategory = "wxWEB_NAV_ERR_NOT_FOUND";
508 break;
509
510 case wxWEB_NAV_ERR_REQUEST:
511 errorCategory = "wxWEB_NAV_ERR_REQUEST";
512 break;
513
514 case wxWEB_NAV_ERR_USER_CANCELLED:
515 errorCategory = "wxWEB_NAV_ERR_USER_CANCELLED";
516 break;
517
518 case wxWEB_NAV_ERR_OTHER:
519 errorCategory = "wxWEB_NAV_ERR_OTHER";
520 break;
521 }
522
523 wxLogMessage("Error; url='" + evt.GetHref() + "', error='" + errorCategory + "' (" + evt.GetString() + ")");
524
525 //Show the info bar with an error
526 m_info->ShowMessage(_("An error occurred loading ") + evt.GetHref() + "\n" +
527 "'" + errorCategory + "' (" + evt.GetString() + ")", wxICON_ERROR);
528
529 UpdateState();
530 }
531
532 /**
533 * Invoked when user selects "Print" from the menu
534 */
535 void WebFrame::OnPrint(wxCommandEvent& evt)
536 {
537 m_browser->Print();
538 }
539
540 SourceViewDialog::SourceViewDialog(wxWindow* parent, wxString source) :
541 wxDialog(parent, wxID_ANY, "Source Code",
542 wxDefaultPosition, wxSize(700,500),
543 wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
544 {
545 wxStyledTextCtrl* text = new wxStyledTextCtrl(this, wxID_ANY);
546 text->SetMarginWidth(1, 30);
547 text->SetMarginType(1, wxSTC_MARGIN_NUMBER);
548 text->SetText(source);
549
550 text->StyleClearAll();
551 text->SetLexer(wxSTC_LEX_HTML);
552 text->StyleSetForeground(wxSTC_H_DOUBLESTRING, wxColour(255,0,0));
553 text->StyleSetForeground(wxSTC_H_SINGLESTRING, wxColour(255,0,0));
554 text->StyleSetForeground(wxSTC_H_ENTITY, wxColour(255,0,0));
555 text->StyleSetForeground(wxSTC_H_TAG, wxColour(0,150,0));
556 text->StyleSetForeground(wxSTC_H_TAGUNKNOWN, wxColour(0,150,0));
557 text->StyleSetForeground(wxSTC_H_ATTRIBUTE, wxColour(0,0,150));
558 text->StyleSetForeground(wxSTC_H_ATTRIBUTEUNKNOWN, wxColour(0,0,150));
559 text->StyleSetForeground(wxSTC_H_COMMENT, wxColour(150,150,150));
560
561 wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
562 sizer->Add(text, 1, wxEXPAND);
563 SetSizer(sizer);
564 }