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