]> git.saurik.com Git - wxWidgets.git/blob - src/osx/webview_webkit.mm
Remove now unnecessary comment.
[wxWidgets.git] / src / osx / webview_webkit.mm
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/webview_webkit.mm
3 // Purpose: wxWebViewWebKit - embeddable web kit control,
4 // OS X implementation of web view component
5 // Author: Jethro Grassie / Kevin Ollivier / Marianne Gagnon
6 // Modified by:
7 // Created: 2004-4-16
8 // RCS-ID: $Id$
9 // Copyright: (c) Jethro Grassie / Kevin Ollivier / Marianne Gagnon
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
12
13 // http://developer.apple.com/mac/library/documentation/Cocoa/Reference/WebKit/Classes/WebView_Class/Reference/Reference.html
14
15 #include "wx/osx/webview_webkit.h"
16
17 #if wxUSE_WEBVIEW_WEBKIT && (defined(__WXOSX_COCOA__) \
18 || defined(__WXOSX_CARBON__))
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifndef WX_PRECOMP
24 #include "wx/wx.h"
25 #endif
26
27 #ifdef __WXCOCOA__
28 #include "wx/cocoa/autorelease.h"
29 #else
30 #include "wx/osx/private.h"
31
32 #include <WebKit/WebKit.h>
33 #include <WebKit/HIWebView.h>
34 #include <WebKit/CarbonUtils.h>
35 #endif
36
37 #include <Foundation/NSURLError.h>
38
39 // FIXME: find cleaner way to find the wxWidgets ID of a webview than this hack
40 #include <map>
41 std::map<WebView*, wxWebViewWebKit*> wx_webviewctrls;
42
43 #define DEBUG_WEBKIT_SIZING 0
44
45 // ----------------------------------------------------------------------------
46 // macros
47 // ----------------------------------------------------------------------------
48
49 wxIMPLEMENT_DYNAMIC_CLASS(wxWebViewWebKit, wxWebView);
50
51 BEGIN_EVENT_TABLE(wxWebViewWebKit, wxControl)
52 #if defined(__WXMAC__) && wxOSX_USE_CARBON
53 EVT_SIZE(wxWebViewWebKit::OnSize)
54 #endif
55 END_EVENT_TABLE()
56
57 #if defined(__WXOSX__) && wxOSX_USE_CARBON
58
59 // ----------------------------------------------------------------------------
60 // Carbon Events handlers
61 // ----------------------------------------------------------------------------
62
63 // prototype for function in src/osx/carbon/nonownedwnd.cpp
64 void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent );
65
66 static const EventTypeSpec eventList[] =
67 {
68 //{ kEventClassControl, kEventControlTrack } ,
69 { kEventClassMouse, kEventMouseUp },
70 { kEventClassMouse, kEventMouseDown },
71 { kEventClassMouse, kEventMouseMoved },
72 { kEventClassMouse, kEventMouseDragged },
73
74 { kEventClassKeyboard, kEventRawKeyDown } ,
75 { kEventClassKeyboard, kEventRawKeyRepeat } ,
76 { kEventClassKeyboard, kEventRawKeyUp } ,
77 { kEventClassKeyboard, kEventRawKeyModifiersChanged } ,
78
79 { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
80 { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
81
82 #if DEBUG_WEBKIT_SIZING == 1
83 { kEventClassControl, kEventControlBoundsChanged } ,
84 #endif
85 };
86
87 // mix this in from window.cpp
88 pascal OSStatus wxMacUnicodeTextEventHandler(EventHandlerCallRef handler,
89 EventRef event, void *data) ;
90
91 // NOTE: This is mostly taken from KeyboardEventHandler in toplevel.cpp, but
92 // that expects the data pointer is a top-level window, so I needed to change
93 // that in this case. However, once 2.8 is out, we should factor out the common
94 // logic among the two functions and merge them.
95 static pascal OSStatus wxWebKitKeyEventHandler(EventHandlerCallRef handler,
96 EventRef event, void *data)
97 {
98 OSStatus result = eventNotHandledErr ;
99 wxMacCarbonEvent cEvent( event ) ;
100
101 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
102 wxWindow* focus = thisWindow ;
103
104 unsigned char charCode ;
105 wxChar uniChar[2] ;
106 uniChar[0] = 0;
107 uniChar[1] = 0;
108
109 UInt32 keyCode ;
110 UInt32 modifiers ;
111 Point point ;
112 UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
113
114 #if wxUSE_UNICODE
115 ByteCount dataSize = 0 ;
116 if ( GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText,
117 NULL, 0 , &dataSize, NULL ) == noErr)
118 {
119 UniChar buf[2] ;
120 int numChars = dataSize / sizeof( UniChar) + 1;
121
122 UniChar* charBuf = buf ;
123
124 if ( numChars * 2 > 4 )
125 charBuf = new UniChar[ numChars ] ;
126 GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText, NULL,
127 dataSize , NULL , charBuf) ;
128 charBuf[ numChars - 1 ] = 0;
129
130 #if SIZEOF_WCHAR_T == 2
131 uniChar = charBuf[0] ;
132 #else
133 wxMBConvUTF16 converter ;
134 converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ;
135 #endif
136
137 if ( numChars * 2 > 4 )
138 delete[] charBuf ;
139 }
140 #endif
141
142 GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL,
143 sizeof(char), NULL, &charCode );
144 GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL,
145 sizeof(UInt32), NULL, &keyCode );
146 GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL,
147 sizeof(UInt32), NULL, &modifiers );
148 GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, NULL,
149 sizeof(Point), NULL, &point );
150
151 UInt32 message = (keyCode << 8) + charCode;
152 switch ( GetEventKind( event ) )
153 {
154 case kEventRawKeyRepeat :
155 case kEventRawKeyDown :
156 {
157 WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
158 WXEVENTHANDLERCALLREF formerHandler =
159 wxTheApp->MacGetCurrentEventHandlerCallRef() ;
160
161 wxTheApp->MacSetCurrentEvent( event , handler ) ;
162 if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
163 focus, message, modifiers, when, point.h, point.v, uniChar[0]))
164 {
165 result = noErr ;
166 }
167 wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
168 }
169 break ;
170
171 case kEventRawKeyUp :
172 if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
173 focus , message , modifiers , when , point.h , point.v , uniChar[0] ) )
174 {
175 result = noErr ;
176 }
177 break ;
178
179 case kEventRawKeyModifiersChanged :
180 {
181 wxKeyEvent event(wxEVT_KEY_DOWN);
182
183 event.m_shiftDown = modifiers & shiftKey;
184 event.m_controlDown = modifiers & controlKey;
185 event.m_altDown = modifiers & optionKey;
186 event.m_metaDown = modifiers & cmdKey;
187 event.m_x = point.h;
188 event.m_y = point.v;
189
190 #if wxUSE_UNICODE
191 event.m_uniChar = uniChar[0] ;
192 #endif
193
194 event.SetTimestamp(when);
195 event.SetEventObject(focus);
196
197 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
198 {
199 event.m_keyCode = WXK_CONTROL ;
200 event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
201 focus->GetEventHandler()->ProcessEvent( event ) ;
202 }
203 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
204 {
205 event.m_keyCode = WXK_SHIFT ;
206 event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
207 focus->GetEventHandler()->ProcessEvent( event ) ;
208 }
209 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
210 {
211 event.m_keyCode = WXK_ALT ;
212 event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
213 focus->GetEventHandler()->ProcessEvent( event ) ;
214 }
215 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
216 {
217 event.m_keyCode = WXK_COMMAND ;
218 event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
219 focus->GetEventHandler()->ProcessEvent( event ) ;
220 }
221
222 wxApp::s_lastModifiers = modifiers ;
223 }
224 break ;
225
226 default:
227 break;
228 }
229
230 return result ;
231 }
232
233 static pascal OSStatus wxWebViewWebKitEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
234 {
235 OSStatus result = eventNotHandledErr ;
236
237 wxMacCarbonEvent cEvent( event ) ;
238
239 ControlRef controlRef ;
240 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
241 wxNonOwnedWindow* tlw = NULL;
242 if (thisWindow)
243 tlw = thisWindow->MacGetTopLevelWindow();
244
245 cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
246
247 wxWindow* currentMouseWindow = thisWindow ;
248
249 if ( wxApp::s_captureWindow )
250 currentMouseWindow = wxApp::s_captureWindow;
251
252 switch ( GetEventClass( event ) )
253 {
254 case kEventClassKeyboard:
255 {
256 result = wxWebKitKeyEventHandler(handler, event, data);
257 break;
258 }
259
260 case kEventClassTextInput:
261 {
262 result = wxMacUnicodeTextEventHandler(handler, event, data);
263 break;
264 }
265
266 case kEventClassMouse:
267 {
268 switch ( GetEventKind( event ) )
269 {
270 case kEventMouseDragged :
271 case kEventMouseMoved :
272 case kEventMouseDown :
273 case kEventMouseUp :
274 {
275 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
276 SetupMouseEvent( wxevent , cEvent ) ;
277
278 currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
279 wxevent.SetEventObject( currentMouseWindow ) ;
280 wxevent.SetId( currentMouseWindow->GetId() ) ;
281
282 if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
283 {
284 result = noErr;
285 }
286
287 break; // this should enable WebKit to fire mouse dragged and mouse up events...
288 }
289 default :
290 break ;
291 }
292 }
293 default:
294 break;
295 }
296
297 result = CallNextEventHandler(handler, event);
298 return result ;
299 }
300
301 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebViewWebKitEventHandler )
302
303 #endif
304
305 //---------------------------------------------------------
306 // helper functions for NSString<->wxString conversion
307 //---------------------------------------------------------
308
309 inline wxString wxStringWithNSString(NSString *nsstring)
310 {
311 #if wxUSE_UNICODE
312 return wxString([nsstring UTF8String], wxConvUTF8);
313 #else
314 return wxString([nsstring lossyCString]);
315 #endif // wxUSE_UNICODE
316 }
317
318 inline NSString* wxNSStringWithWxString(const wxString &wxstring)
319 {
320 #if wxUSE_UNICODE
321 return [NSString stringWithUTF8String: wxstring.mb_str(wxConvUTF8)];
322 #else
323 return [NSString stringWithCString: wxstring.c_str() length:wxstring.Len()];
324 #endif // wxUSE_UNICODE
325 }
326
327 @interface MyFrameLoadMonitor : NSObject
328 {
329 wxWebViewWebKit* webKitWindow;
330 }
331
332 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
333
334 @end
335
336 @interface MyPolicyDelegate : NSObject
337 {
338 wxWebViewWebKit* webKitWindow;
339 }
340
341 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
342
343 @end
344
345 // ----------------------------------------------------------------------------
346 // creation/destruction
347 // ----------------------------------------------------------------------------
348
349 bool wxWebViewWebKit::Create(wxWindow *parent,
350 wxWindowID winID,
351 const wxString& strURL,
352 const wxPoint& pos,
353 const wxSize& size, long style,
354 const wxString& name)
355 {
356 m_busy = false;
357
358 //still needed for wxCocoa??
359 /*
360 int width, height;
361 wxSize sizeInstance;
362 if (size.x == wxDefaultCoord || size.y == wxDefaultCoord)
363 {
364 m_parent->GetClientSize(&width, &height);
365 sizeInstance.x = width;
366 sizeInstance.y = height;
367 }
368 else
369 {
370 sizeInstance.x = size.x;
371 sizeInstance.y = size.y;
372 }
373 */
374 // now create and attach WebKit view...
375 #ifdef __WXCOCOA__
376 wxControl::Create(parent, m_windowID, pos, sizeInstance, style, name);
377 SetSize(pos.x, pos.y, sizeInstance.x, sizeInstance.y);
378
379 wxTopLevelWindowCocoa *topWin = wxDynamicCast(this, wxTopLevelWindowCocoa);
380 NSWindow* nsWin = topWin->GetNSWindow();
381 NSRect rect;
382 rect.origin.x = pos.x;
383 rect.origin.y = pos.y;
384 rect.size.width = sizeInstance.x;
385 rect.size.height = sizeInstance.y;
386 m_webView = (WebView*)[[WebView alloc] initWithFrame:rect
387 frameName:@"webkitFrame"
388 groupName:@"webkitGroup"];
389 SetNSView(m_webView);
390 [m_cocoaNSView release];
391
392 if(m_parent) m_parent->CocoaAddChild(this);
393 SetInitialFrameRect(pos,sizeInstance);
394 #else
395 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
396
397 #if wxOSX_USE_CARBON
398 m_peer = new wxMacControl(this);
399 WebInitForCarbon();
400 HIWebViewCreate( m_peer->GetControlRefAddr() );
401
402 m_webView = (WebView*) HIWebViewGetWebView( m_peer->GetControlRef() );
403
404 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
405 if ( UMAGetSystemVersion() >= 0x1030 )
406 HIViewChangeFeatures( m_peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
407 #endif
408 InstallControlEventHandler(m_peer->GetControlRef(),
409 GetwxWebViewWebKitEventHandlerUPP(),
410 GetEventTypeCount(eventList), eventList, this,
411 (EventHandlerRef *)&m_webKitCtrlEventHandler);
412 #else
413 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
414 m_webView = [[WebView alloc] initWithFrame:r
415 frameName:@"webkitFrame"
416 groupName:@"webkitGroup"];
417 m_peer = new wxWidgetCocoaImpl( this, m_webView );
418 #endif
419
420 wx_webviewctrls[m_webView] = this;
421
422 MacPostControlCreate(pos, size);
423
424 #if wxOSX_USE_CARBON
425 HIViewSetVisible( m_peer->GetControlRef(), true );
426 #endif
427 [m_webView setHidden:false];
428
429 #endif
430
431 // Register event listener interfaces
432 MyFrameLoadMonitor* myFrameLoadMonitor =
433 [[MyFrameLoadMonitor alloc] initWithWxWindow: this];
434
435 [m_webView setFrameLoadDelegate:myFrameLoadMonitor];
436
437 // this is used to veto page loads, etc.
438 MyPolicyDelegate* myPolicyDelegate =
439 [[MyPolicyDelegate alloc] initWithWxWindow: this];
440
441 [m_webView setPolicyDelegate:myPolicyDelegate];
442
443 InternalLoadURL(strURL);
444 return true;
445 }
446
447 wxWebViewWebKit::~wxWebViewWebKit()
448 {
449 MyFrameLoadMonitor* myFrameLoadMonitor = [m_webView frameLoadDelegate];
450 MyPolicyDelegate* myPolicyDelegate = [m_webView policyDelegate];
451 [m_webView setFrameLoadDelegate: nil];
452 [m_webView setPolicyDelegate: nil];
453
454 if (myFrameLoadMonitor)
455 [myFrameLoadMonitor release];
456
457 if (myPolicyDelegate)
458 [myPolicyDelegate release];
459 }
460
461 // ----------------------------------------------------------------------------
462 // public methods
463 // ----------------------------------------------------------------------------
464
465 void wxWebViewWebKit::InternalLoadURL(const wxString &url)
466 {
467 if( !m_webView )
468 return;
469
470 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
471 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
472 }
473
474 bool wxWebViewWebKit::CanGoBack()
475 {
476 if ( !m_webView )
477 return false;
478
479 return [m_webView canGoBack];
480 }
481
482 bool wxWebViewWebKit::CanGoForward()
483 {
484 if ( !m_webView )
485 return false;
486
487 return [m_webView canGoForward];
488 }
489
490 void wxWebViewWebKit::GoBack()
491 {
492 if ( !m_webView )
493 return;
494
495 bool result = [(WebView*)m_webView goBack];
496
497 // TODO: return result (if it also exists in other backends...)
498 //return result;
499 }
500
501 void wxWebViewWebKit::GoForward()
502 {
503 if ( !m_webView )
504 return;
505
506 bool result = [(WebView*)m_webView goForward];
507
508 // TODO: return result (if it also exists in other backends...)
509 //return result;
510 }
511
512 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
513 {
514 if ( !m_webView )
515 return;
516
517 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
518 {
519 // TODO: test this indeed bypasses the cache
520 [[m_webView preferences] setUsesPageCache:NO];
521 [[m_webView mainFrame] reload];
522 [[m_webView preferences] setUsesPageCache:YES];
523 }
524 else
525 {
526 [[m_webView mainFrame] reload];
527 }
528 }
529
530 void wxWebViewWebKit::Stop()
531 {
532 if ( !m_webView )
533 return;
534
535 [[m_webView mainFrame] stopLoading];
536 }
537
538 bool wxWebViewWebKit::CanGetPageSource()
539 {
540 if ( !m_webView )
541 return false;
542
543 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
544 return ( [[dataSource representation] canProvideDocumentSource] );
545 }
546
547 wxString wxWebViewWebKit::GetPageSource()
548 {
549
550 if (CanGetPageSource())
551 {
552 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
553 wxASSERT (dataSource != nil);
554
555 id<WebDocumentRepresentation> representation = [dataSource representation];
556 wxASSERT (representation != nil);
557
558 NSString* source = [representation documentSource];
559 if (source == nil)
560 {
561 return wxEmptyString;
562 }
563
564 return wxStringWithNSString( source );
565 }
566
567 return wxEmptyString;
568 }
569
570 bool wxWebViewWebKit::CanIncreaseTextSize()
571 {
572 if ( !m_webView )
573 return false;
574
575 if ([m_webView canMakeTextLarger])
576 return true;
577 else
578 return false;
579 }
580
581 void wxWebViewWebKit::IncreaseTextSize()
582 {
583 if ( !m_webView )
584 return;
585
586 if (CanIncreaseTextSize())
587 [m_webView makeTextLarger:(WebView*)m_webView];
588 }
589
590 bool wxWebViewWebKit::CanDecreaseTextSize()
591 {
592 if ( !m_webView )
593 return false;
594
595 if ([m_webView canMakeTextSmaller])
596 return true;
597 else
598 return false;
599 }
600
601 void wxWebViewWebKit::DecreaseTextSize()
602 {
603 if ( !m_webView )
604 return;
605
606 if (CanDecreaseTextSize())
607 [m_webView makeTextSmaller:(WebView*)m_webView];
608 }
609
610 void wxWebViewWebKit::Print()
611 {
612
613 // TODO: allow specifying the "show prompt" parameter in Print() ?
614 bool showPrompt = true;
615
616 if ( !m_webView )
617 return;
618
619 id view = [[[m_webView mainFrame] frameView] documentView];
620 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
621 printInfo: [NSPrintInfo sharedPrintInfo]];
622 if (showPrompt)
623 {
624 [op setShowsPrintPanel: showPrompt];
625 // in my tests, the progress bar always freezes and it stops the whole
626 // print operation. do not turn this to true unless there is a
627 // workaround for the bug.
628 [op setShowsProgressPanel: false];
629 }
630 // Print it.
631 [op runOperation];
632 }
633
634 void wxWebViewWebKit::SetEditable(bool enable)
635 {
636 if ( !m_webView )
637 return;
638
639 [m_webView setEditable:enable ];
640 }
641
642 bool wxWebViewWebKit::IsEditable()
643 {
644 if ( !m_webView )
645 return false;
646
647 return [m_webView isEditable];
648 }
649
650 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
651 {
652 // there is only one supported zoom type at the moment so this setter
653 // does nothing beyond checking sanity
654 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
655 }
656
657 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
658 {
659 // for now that's the only one that is supported
660 // FIXME: does the default zoom type change depending on webkit versions? :S
661 // Then this will be wrong
662 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
663 }
664
665 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
666 {
667 switch (type)
668 {
669 // for now that's the only one that is supported
670 // TODO: I know recent versions of webkit support layout zoom too,
671 // check if we can support it
672 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
673 return true;
674
675 default:
676 return false;
677 }
678 }
679
680 int wxWebViewWebKit::GetScrollPos()
681 {
682 id result = [[m_webView windowScriptObject]
683 evaluateWebScript:@"document.body.scrollTop"];
684 return [result intValue];
685 }
686
687 void wxWebViewWebKit::SetScrollPos(int pos)
688 {
689 if ( !m_webView )
690 return;
691
692 wxString javascript;
693 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
694 [[m_webView windowScriptObject] evaluateWebScript:
695 (NSString*)wxNSStringWithWxString( javascript )];
696 }
697
698 wxString wxWebViewWebKit::GetSelectedText()
699 {
700 NSString* selection = [[m_webView selectedDOMRange] markupString];
701 if (!selection) return wxEmptyString;
702
703 return wxStringWithNSString(selection);
704 }
705
706 void wxWebViewWebKit::RunScript(const wxString& javascript)
707 {
708 if ( !m_webView )
709 return;
710
711 [[m_webView windowScriptObject] evaluateWebScript:
712 (NSString*)wxNSStringWithWxString( javascript )];
713 }
714
715 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
716 {
717 #if defined(__WXMAC_) && wxOSX_USE_CARBON
718 // This is a nasty hack because WebKit seems to lose its position when it is
719 // embedded in a control that is not itself the content view for a TLW.
720 // I put it in OnSize because these calcs are not perfect, and in fact are
721 // basically guesses based on reverse engineering, so it's best to give
722 // people the option of overriding OnSize with their own calcs if need be.
723 // I also left some test debugging print statements as a convenience if
724 // a(nother) problem crops up.
725
726 wxWindow* tlw = MacGetTopLevelWindow();
727
728 NSRect frame = [(WebView*)m_webView frame];
729 NSRect bounds = [(WebView*)m_webView bounds];
730
731 #if DEBUG_WEBKIT_SIZING
732 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
733 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
734 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
735 frame.origin.x, frame.origin.y,
736 frame.size.width, frame.size.height);
737 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
738 bounds.origin.x, bounds.origin.y,
739 bounds.size.width, bounds.size.height);
740 #endif
741
742 // This must be the case that Apple tested with, because well, in this one case
743 // we don't need to do anything! It just works. ;)
744 if (GetParent() == tlw) return;
745
746 // since we no longer use parent coordinates, we always want 0,0.
747 int x = 0;
748 int y = 0;
749
750 HIRect rect;
751 rect.origin.x = x;
752 rect.origin.y = y;
753
754 #if DEBUG_WEBKIT_SIZING
755 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
756 #endif
757
758 // NB: In most cases, when calling HIViewConvertRect, what people want is to
759 // use GetRootControl(), and this tripped me up at first. But in fact, what
760 // we want is the root view, because we need to make the y origin relative
761 // to the very top of the window, not its contents, since we later flip
762 // the y coordinate for Cocoa.
763 HIViewConvertRect (&rect, m_peer->GetControlRef(),
764 HIViewGetRoot(
765 (WindowRef) MacGetTopLevelWindowRef()
766 ));
767
768 x = (int)rect.origin.x;
769 y = (int)rect.origin.y;
770
771 #if DEBUG_WEBKIT_SIZING
772 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
773 #endif
774
775 if (tlw){
776 //flip the y coordinate to convert to Cocoa coordinates
777 y = tlw->GetSize().y - ((GetSize().y) + y);
778 }
779
780 #if DEBUG_WEBKIT_SIZING
781 printf("y = %d after flipping value\n", y);
782 #endif
783
784 frame.origin.x = x;
785 frame.origin.y = y;
786 [(WebView*)m_webView setFrame:frame];
787
788 if (IsShown())
789 [(WebView*)m_webView display];
790 event.Skip();
791 #endif
792 }
793
794 void wxWebViewWebKit::MacVisibilityChanged(){
795 #if defined(__WXMAC__) && wxOSX_USE_CARBON
796 bool isHidden = !IsControlVisible( m_peer->GetControlRef());
797 if (!isHidden)
798 [(WebView*)m_webView display];
799
800 [m_webView setHidden:isHidden];
801 #endif
802 }
803
804 void wxWebViewWebKit::LoadUrl(const wxString& url)
805 {
806 InternalLoadURL(url);
807 }
808
809 wxString wxWebViewWebKit::GetCurrentURL()
810 {
811 return wxStringWithNSString([m_webView mainFrameURL]);
812 }
813
814 wxString wxWebViewWebKit::GetCurrentTitle()
815 {
816 return wxStringWithNSString([m_webView mainFrameTitle]);
817 }
818
819 float wxWebViewWebKit::GetWebkitZoom()
820 {
821 return [m_webView textSizeMultiplier];
822 }
823
824 void wxWebViewWebKit::SetWebkitZoom(float zoom)
825 {
826 [m_webView setTextSizeMultiplier:zoom];
827 }
828
829 wxWebViewZoom wxWebViewWebKit::GetZoom()
830 {
831 float zoom = GetWebkitZoom();
832
833 // arbitrary way to map float zoom to our common zoom enum
834 if (zoom <= 0.55)
835 {
836 return wxWEB_VIEW_ZOOM_TINY;
837 }
838 else if (zoom > 0.55 && zoom <= 0.85)
839 {
840 return wxWEB_VIEW_ZOOM_SMALL;
841 }
842 else if (zoom > 0.85 && zoom <= 1.15)
843 {
844 return wxWEB_VIEW_ZOOM_MEDIUM;
845 }
846 else if (zoom > 1.15 && zoom <= 1.45)
847 {
848 return wxWEB_VIEW_ZOOM_LARGE;
849 }
850 else if (zoom > 1.45)
851 {
852 return wxWEB_VIEW_ZOOM_LARGEST;
853 }
854
855 // to shut up compilers, this can never be reached logically
856 wxASSERT(false);
857 return wxWEB_VIEW_ZOOM_MEDIUM;
858 }
859
860 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
861 {
862 // arbitrary way to map our common zoom enum to float zoom
863 switch (zoom)
864 {
865 case wxWEB_VIEW_ZOOM_TINY:
866 SetWebkitZoom(0.4f);
867 break;
868
869 case wxWEB_VIEW_ZOOM_SMALL:
870 SetWebkitZoom(0.7f);
871 break;
872
873 case wxWEB_VIEW_ZOOM_MEDIUM:
874 SetWebkitZoom(1.0f);
875 break;
876
877 case wxWEB_VIEW_ZOOM_LARGE:
878 SetWebkitZoom(1.3);
879 break;
880
881 case wxWEB_VIEW_ZOOM_LARGEST:
882 SetWebkitZoom(1.6);
883 break;
884
885 default:
886 wxASSERT(false);
887 }
888
889 }
890
891 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
892 {
893 if ( !m_webView )
894 return;
895
896 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
897 baseURL:[NSURL URLWithString:
898 wxNSStringWithWxString( baseUrl )]];
899 }
900
901 void wxWebViewWebKit::Cut()
902 {
903 if ( !m_webView )
904 return;
905
906 [(WebView*)m_webView cut:m_webView];
907 }
908
909 void wxWebViewWebKit::Copy()
910 {
911 if ( !m_webView )
912 return;
913
914 [(WebView*)m_webView copy:m_webView];
915 }
916
917 void wxWebViewWebKit::Paste()
918 {
919 if ( !m_webView )
920 return;
921
922 [(WebView*)m_webView paste:m_webView];
923 }
924
925 void wxWebViewWebKit::DeleteSelection()
926 {
927 if ( !m_webView )
928 return;
929
930 [(WebView*)m_webView deleteSelection];
931 }
932
933 bool wxWebViewWebKit::HasSelection()
934 {
935 DOMRange* range = [m_webView selectedDOMRange];
936 if(!range)
937 {
938 return false;
939 }
940 else
941 {
942 return true;
943 }
944 }
945
946 void wxWebViewWebKit::EnableHistory(bool enable)
947 {
948 if ( !m_webView )
949 return;
950
951 [m_webView setMaintainsBackForwardList:enable];
952 }
953
954 void wxWebViewWebKit::ClearHistory()
955 {
956 [m_webView setMaintainsBackForwardList:NO];
957 [m_webView setMaintainsBackForwardList:YES];
958 }
959
960 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
961 {
962 wxVector<wxSharedPtr<wxWebHistoryItem> > backhist;
963 WebBackForwardList* history = [m_webView backForwardList];
964 int count = [history backListCount];
965 for(int i = -count; i < 0; i++)
966 {
967 WebHistoryItem* item = [history itemAtIndex:i];
968 wxString url = wxStringWithNSString([item URLString]);
969 wxString title = wxStringWithNSString([item title]);
970 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
971 wxitem->m_histItem = item;
972 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
973 backhist.push_back(itemptr);
974 }
975 return backhist;
976 }
977
978 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetForwardHistory()
979 {
980 wxVector<wxSharedPtr<wxWebHistoryItem> > forwardhist;
981 WebBackForwardList* history = [m_webView backForwardList];
982 int count = [history forwardListCount];
983 for(int i = 1; i <= count; i++)
984 {
985 WebHistoryItem* item = [history itemAtIndex:i];
986 wxString url = wxStringWithNSString([item URLString]);
987 wxString title = wxStringWithNSString([item title]);
988 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
989 wxitem->m_histItem = item;
990 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
991 forwardhist.push_back(itemptr);
992 }
993 return forwardhist;
994 }
995
996 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebHistoryItem> item)
997 {
998 [m_webView goToBackForwardItem:item->m_histItem];
999 }
1000
1001 bool wxWebViewWebKit::CanUndo()
1002 {
1003 return [[m_webView undoManager] canUndo];
1004 }
1005
1006 bool wxWebViewWebKit::CanRedo()
1007 {
1008 return [[m_webView undoManager] canRedo];
1009 }
1010
1011 void wxWebViewWebKit::Undo()
1012 {
1013 [[m_webView undoManager] undo];
1014 }
1015
1016 void wxWebViewWebKit::Redo()
1017 {
1018 [[m_webView undoManager] redo];
1019 }
1020
1021 //------------------------------------------------------------
1022 // Listener interfaces
1023 //------------------------------------------------------------
1024
1025 // NB: I'm still tracking this down, but it appears the Cocoa window
1026 // still has these events fired on it while the Carbon control is being
1027 // destroyed. Therefore, we must be careful to check both the existence
1028 // of the Carbon control and the event handler before firing events.
1029
1030 @implementation MyFrameLoadMonitor
1031
1032 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1033 {
1034 [super init];
1035 webKitWindow = inWindow; // non retained
1036 return self;
1037 }
1038
1039 - (void)webView:(WebView *)sender
1040 didStartProvisionalLoadForFrame:(WebFrame *)frame
1041 {
1042 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1043 wx_webviewctrls[sender]->m_busy = true;
1044 }
1045
1046 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1047 {
1048 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1049 wx_webviewctrls[sender]->m_busy = true;
1050
1051 if (webKitWindow && frame == [sender mainFrame]){
1052 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1053 wxString target = wxStringWithNSString([frame name]);
1054 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1055 wx_webviewctrls[sender]->GetId(),
1056 wxStringWithNSString( url ),
1057 target, false);
1058
1059 if (webKitWindow && webKitWindow->GetEventHandler())
1060 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1061 }
1062 }
1063
1064 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1065 {
1066 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1067 wx_webviewctrls[sender]->m_busy = false;
1068
1069 if (webKitWindow && frame == [sender mainFrame]){
1070 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1071
1072 wxString target = wxStringWithNSString([frame name]);
1073 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1074 wx_webviewctrls[sender]->GetId(),
1075 wxStringWithNSString( url ),
1076 target, false);
1077
1078 if (webKitWindow && webKitWindow->GetEventHandler())
1079 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1080 }
1081 }
1082
1083 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1084 {
1085 *out = wxWEB_NAV_ERR_OTHER;
1086
1087 if ([[error domain] isEqualToString:NSURLErrorDomain])
1088 {
1089 switch ([error code])
1090 {
1091 case NSURLErrorCannotFindHost:
1092 case NSURLErrorFileDoesNotExist:
1093 case NSURLErrorRedirectToNonExistentLocation:
1094 *out = wxWEB_NAV_ERR_NOT_FOUND;
1095 break;
1096
1097 case NSURLErrorResourceUnavailable:
1098 case NSURLErrorHTTPTooManyRedirects:
1099 case NSURLErrorDataLengthExceedsMaximum:
1100 case NSURLErrorBadURL:
1101 case NSURLErrorFileIsDirectory:
1102 *out = wxWEB_NAV_ERR_REQUEST;
1103 break;
1104
1105 case NSURLErrorTimedOut:
1106 case NSURLErrorDNSLookupFailed:
1107 case NSURLErrorNetworkConnectionLost:
1108 case NSURLErrorCannotConnectToHost:
1109 case NSURLErrorNotConnectedToInternet:
1110 //case NSURLErrorInternationalRoamingOff:
1111 //case NSURLErrorCallIsActive:
1112 //case NSURLErrorDataNotAllowed:
1113 *out = wxWEB_NAV_ERR_CONNECTION;
1114 break;
1115
1116 case NSURLErrorCancelled:
1117 case NSURLErrorUserCancelledAuthentication:
1118 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1119 break;
1120
1121 case NSURLErrorCannotDecodeRawData:
1122 case NSURLErrorCannotDecodeContentData:
1123 case NSURLErrorBadServerResponse:
1124 case NSURLErrorCannotParseResponse:
1125 *out = wxWEB_NAV_ERR_REQUEST;
1126 break;
1127
1128 case NSURLErrorUserAuthenticationRequired:
1129 case NSURLErrorSecureConnectionFailed:
1130 case NSURLErrorClientCertificateRequired:
1131 *out = wxWEB_NAV_ERR_AUTH;
1132 break;
1133
1134 case NSURLErrorNoPermissionsToReadFile:
1135 *out = wxWEB_NAV_ERR_SECURITY;
1136 break;
1137
1138 case NSURLErrorServerCertificateHasBadDate:
1139 case NSURLErrorServerCertificateUntrusted:
1140 case NSURLErrorServerCertificateHasUnknownRoot:
1141 case NSURLErrorServerCertificateNotYetValid:
1142 case NSURLErrorClientCertificateRejected:
1143 *out = wxWEB_NAV_ERR_CERTIFICATE;
1144 break;
1145 }
1146 }
1147
1148 wxString message = wxStringWithNSString([error localizedDescription]);
1149 NSString* detail = [error localizedFailureReason];
1150 if (detail != NULL)
1151 {
1152 message = message + " (" + wxStringWithNSString(detail) + ")";
1153 }
1154 return message;
1155 }
1156
1157 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1158 forFrame:(WebFrame *)frame
1159 {
1160 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1161 wx_webviewctrls[sender]->m_busy = false;
1162
1163 if (webKitWindow && frame == [sender mainFrame]){
1164 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1165
1166 wxWebNavigationError type;
1167 wxString description = nsErrorToWxHtmlError(error, &type);
1168 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1169 wx_webviewctrls[sender]->GetId(),
1170 wxStringWithNSString( url ),
1171 wxEmptyString, false);
1172 thisEvent.SetString(description);
1173 thisEvent.SetInt(type);
1174
1175 if (webKitWindow && webKitWindow->GetEventHandler())
1176 {
1177 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1178 }
1179 }
1180 }
1181
1182 - (void)webView:(WebView *)sender
1183 didFailProvisionalLoadWithError:(NSError*)error
1184 forFrame:(WebFrame *)frame
1185 {
1186 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1187 wx_webviewctrls[sender]->m_busy = false;
1188
1189 if (webKitWindow && frame == [sender mainFrame]){
1190 NSString *url = [[[[frame provisionalDataSource] request] URL]
1191 absoluteString];
1192
1193 wxWebNavigationError type;
1194 wxString description = nsErrorToWxHtmlError(error, &type);
1195 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1196 wx_webviewctrls[sender]->GetId(),
1197 wxStringWithNSString( url ),
1198 wxEmptyString, false);
1199 thisEvent.SetString(description);
1200 thisEvent.SetInt(type);
1201
1202 if (webKitWindow && webKitWindow->GetEventHandler())
1203 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1204 }
1205 }
1206
1207 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1208 forFrame:(WebFrame *)frame
1209 {
1210 wxString target = wxStringWithNSString([frame name]);
1211 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1212 wx_webviewctrls[sender]->GetId(),
1213 wx_webviewctrls[sender]->GetCurrentURL(),
1214 target, true);
1215
1216 thisEvent.SetString(wxStringWithNSString(title));
1217
1218 if (webKitWindow && webKitWindow->GetEventHandler())
1219 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1220 }
1221 @end
1222
1223 @implementation MyPolicyDelegate
1224
1225 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1226 {
1227 [super init];
1228 webKitWindow = inWindow; // non retained
1229 return self;
1230 }
1231
1232 - (void)webView:(WebView *)sender
1233 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1234 request:(NSURLRequest *)request
1235 frame:(WebFrame *)frame
1236 decisionListener:(id<WebPolicyDecisionListener>)listener
1237 {
1238 wxUnusedVar(frame);
1239
1240 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1241 wx_webviewctrls[sender]->m_busy = true;
1242 NSString *url = [[request URL] absoluteString];
1243 wxString target = wxStringWithNSString([frame name]);
1244 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1245 wx_webviewctrls[sender]->GetId(),
1246 wxStringWithNSString( url ), target, true);
1247
1248 if (webKitWindow && webKitWindow->GetEventHandler())
1249 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1250
1251 if (thisEvent.IsVetoed())
1252 {
1253 wx_webviewctrls[sender]->m_busy = false;
1254 [listener ignore];
1255 }
1256 else
1257 {
1258 [listener use];
1259 }
1260 }
1261
1262 - (void)webView:(WebView *)sender
1263 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1264 request:(NSURLRequest *)request
1265 newFrameName:(NSString *)frameName
1266 decisionListener:(id < WebPolicyDecisionListener >)listener
1267 {
1268 wxUnusedVar(actionInformation);
1269
1270 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1271 NSString *url = [[request URL] absoluteString];
1272 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1273 wx_webviewctrls[sender]->GetId(),
1274 wxStringWithNSString( url ), "", true);
1275
1276 if (webKitWindow && webKitWindow->GetEventHandler())
1277 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1278
1279 [listener ignore];
1280 }
1281 @end
1282
1283 #endif //wxUSE_WEBVIEW_WEBKIT