]> git.saurik.com Git - wxWidgets.git/blob - src/osx/webview_webkit.mm
Fix compilation errors under OSX.
[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 // For compilers that support precompilation, includes "wx.h".
18 #include "wx/wxprec.h"
19
20 #ifndef WX_PRECOMP
21 #include "wx/wx.h"
22 #endif
23
24 //#if wxHAVE_WEB_BACKEND_OSX_WEBKIT
25
26 #ifdef __WXCOCOA__
27 #include "wx/cocoa/autorelease.h"
28 #else
29 #include "wx/osx/private.h"
30
31 #include <WebKit/WebKit.h>
32 #include <WebKit/HIWebView.h>
33 #include <WebKit/CarbonUtils.h>
34 #endif
35
36 #include <Foundation/NSURLError.h>
37
38 // FIXME: find cleaner way to find the wxWidgets ID of a webview than this hack
39 #include <map>
40 std::map<WebView*, wxWebViewWebKit*> wx_webviewctrls;
41
42 #define DEBUG_WEBKIT_SIZING 0
43
44 // ----------------------------------------------------------------------------
45 // macros
46 // ----------------------------------------------------------------------------
47
48 IMPLEMENT_DYNAMIC_CLASS(wxWebViewWebKit, wxControl)
49
50 BEGIN_EVENT_TABLE(wxWebViewWebKit, wxControl)
51 #if defined(__WXMAC__) && wxOSX_USE_CARBON
52 EVT_SIZE(wxWebViewWebKit::OnSize)
53 #endif
54 END_EVENT_TABLE()
55
56 #if defined(__WXOSX__) && wxOSX_USE_CARBON
57
58 // ----------------------------------------------------------------------------
59 // Carbon Events handlers
60 // ----------------------------------------------------------------------------
61
62 // prototype for function in src/osx/carbon/nonownedwnd.cpp
63 void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent );
64
65 static const EventTypeSpec eventList[] =
66 {
67 //{ kEventClassControl, kEventControlTrack } ,
68 { kEventClassMouse, kEventMouseUp },
69 { kEventClassMouse, kEventMouseDown },
70 { kEventClassMouse, kEventMouseMoved },
71 { kEventClassMouse, kEventMouseDragged },
72
73 { kEventClassKeyboard, kEventRawKeyDown } ,
74 { kEventClassKeyboard, kEventRawKeyRepeat } ,
75 { kEventClassKeyboard, kEventRawKeyUp } ,
76 { kEventClassKeyboard, kEventRawKeyModifiersChanged } ,
77
78 { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
79 { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
80
81 #if DEBUG_WEBKIT_SIZING == 1
82 { kEventClassControl, kEventControlBoundsChanged } ,
83 #endif
84 };
85
86 // mix this in from window.cpp
87 pascal OSStatus wxMacUnicodeTextEventHandler(EventHandlerCallRef handler,
88 EventRef event, void *data) ;
89
90 // NOTE: This is mostly taken from KeyboardEventHandler in toplevel.cpp, but
91 // that expects the data pointer is a top-level window, so I needed to change
92 // that in this case. However, once 2.8 is out, we should factor out the common
93 // logic among the two functions and merge them.
94 static pascal OSStatus wxWebKitKeyEventHandler(EventHandlerCallRef handler,
95 EventRef event, void *data)
96 {
97 OSStatus result = eventNotHandledErr ;
98 wxMacCarbonEvent cEvent( event ) ;
99
100 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
101 wxWindow* focus = thisWindow ;
102
103 unsigned char charCode ;
104 wxChar uniChar[2] ;
105 uniChar[0] = 0;
106 uniChar[1] = 0;
107
108 UInt32 keyCode ;
109 UInt32 modifiers ;
110 Point point ;
111 UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
112
113 #if wxUSE_UNICODE
114 ByteCount dataSize = 0 ;
115 if ( GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText,
116 NULL, 0 , &dataSize, NULL ) == noErr)
117 {
118 UniChar buf[2] ;
119 int numChars = dataSize / sizeof( UniChar) + 1;
120
121 UniChar* charBuf = buf ;
122
123 if ( numChars * 2 > 4 )
124 charBuf = new UniChar[ numChars ] ;
125 GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText, NULL,
126 dataSize , NULL , charBuf) ;
127 charBuf[ numChars - 1 ] = 0;
128
129 #if SIZEOF_WCHAR_T == 2
130 uniChar = charBuf[0] ;
131 #else
132 wxMBConvUTF16 converter ;
133 converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ;
134 #endif
135
136 if ( numChars * 2 > 4 )
137 delete[] charBuf ;
138 }
139 #endif
140
141 GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL,
142 sizeof(char), NULL, &charCode );
143 GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL,
144 sizeof(UInt32), NULL, &keyCode );
145 GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL,
146 sizeof(UInt32), NULL, &modifiers );
147 GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, NULL,
148 sizeof(Point), NULL, &point );
149
150 UInt32 message = (keyCode << 8) + charCode;
151 switch ( GetEventKind( event ) )
152 {
153 case kEventRawKeyRepeat :
154 case kEventRawKeyDown :
155 {
156 WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
157 WXEVENTHANDLERCALLREF formerHandler =
158 wxTheApp->MacGetCurrentEventHandlerCallRef() ;
159
160 wxTheApp->MacSetCurrentEvent( event , handler ) ;
161 if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
162 focus, message, modifiers, when, point.h, point.v, uniChar[0]))
163 {
164 result = noErr ;
165 }
166 wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
167 }
168 break ;
169
170 case kEventRawKeyUp :
171 if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
172 focus , message , modifiers , when , point.h , point.v , uniChar[0] ) )
173 {
174 result = noErr ;
175 }
176 break ;
177
178 case kEventRawKeyModifiersChanged :
179 {
180 wxKeyEvent event(wxEVT_KEY_DOWN);
181
182 event.m_shiftDown = modifiers & shiftKey;
183 event.m_controlDown = modifiers & controlKey;
184 event.m_altDown = modifiers & optionKey;
185 event.m_metaDown = modifiers & cmdKey;
186 event.m_x = point.h;
187 event.m_y = point.v;
188
189 #if wxUSE_UNICODE
190 event.m_uniChar = uniChar[0] ;
191 #endif
192
193 event.SetTimestamp(when);
194 event.SetEventObject(focus);
195
196 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
197 {
198 event.m_keyCode = WXK_CONTROL ;
199 event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
200 focus->GetEventHandler()->ProcessEvent( event ) ;
201 }
202 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
203 {
204 event.m_keyCode = WXK_SHIFT ;
205 event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
206 focus->GetEventHandler()->ProcessEvent( event ) ;
207 }
208 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
209 {
210 event.m_keyCode = WXK_ALT ;
211 event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
212 focus->GetEventHandler()->ProcessEvent( event ) ;
213 }
214 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
215 {
216 event.m_keyCode = WXK_COMMAND ;
217 event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
218 focus->GetEventHandler()->ProcessEvent( event ) ;
219 }
220
221 wxApp::s_lastModifiers = modifiers ;
222 }
223 break ;
224
225 default:
226 break;
227 }
228
229 return result ;
230 }
231
232 static pascal OSStatus wxWebViewWebKitEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
233 {
234 OSStatus result = eventNotHandledErr ;
235
236 wxMacCarbonEvent cEvent( event ) ;
237
238 ControlRef controlRef ;
239 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
240 wxNonOwnedWindow* tlw = NULL;
241 if (thisWindow)
242 tlw = thisWindow->MacGetTopLevelWindow();
243
244 cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
245
246 wxWindow* currentMouseWindow = thisWindow ;
247
248 if ( wxApp::s_captureWindow )
249 currentMouseWindow = wxApp::s_captureWindow;
250
251 switch ( GetEventClass( event ) )
252 {
253 case kEventClassKeyboard:
254 {
255 result = wxWebKitKeyEventHandler(handler, event, data);
256 break;
257 }
258
259 case kEventClassTextInput:
260 {
261 result = wxMacUnicodeTextEventHandler(handler, event, data);
262 break;
263 }
264
265 case kEventClassMouse:
266 {
267 switch ( GetEventKind( event ) )
268 {
269 case kEventMouseDragged :
270 case kEventMouseMoved :
271 case kEventMouseDown :
272 case kEventMouseUp :
273 {
274 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
275 SetupMouseEvent( wxevent , cEvent ) ;
276
277 currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
278 wxevent.SetEventObject( currentMouseWindow ) ;
279 wxevent.SetId( currentMouseWindow->GetId() ) ;
280
281 if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
282 {
283 result = noErr;
284 }
285
286 break; // this should enable WebKit to fire mouse dragged and mouse up events...
287 }
288 default :
289 break ;
290 }
291 }
292 default:
293 break;
294 }
295
296 result = CallNextEventHandler(handler, event);
297 return result ;
298 }
299
300 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebViewWebKitEventHandler )
301
302 #endif
303
304 //---------------------------------------------------------
305 // helper functions for NSString<->wxString conversion
306 //---------------------------------------------------------
307
308 inline wxString wxStringWithNSString(NSString *nsstring)
309 {
310 #if wxUSE_UNICODE
311 return wxString([nsstring UTF8String], wxConvUTF8);
312 #else
313 return wxString([nsstring lossyCString]);
314 #endif // wxUSE_UNICODE
315 }
316
317 inline NSString* wxNSStringWithWxString(const wxString &wxstring)
318 {
319 #if wxUSE_UNICODE
320 return [NSString stringWithUTF8String: wxstring.mb_str(wxConvUTF8)];
321 #else
322 return [NSString stringWithCString: wxstring.c_str() length:wxstring.Len()];
323 #endif // wxUSE_UNICODE
324 }
325
326 @interface MyFrameLoadMonitor : NSObject
327 {
328 wxWebViewWebKit* webKitWindow;
329 }
330
331 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
332
333 @end
334
335 @interface MyPolicyDelegate : NSObject
336 {
337 wxWebViewWebKit* webKitWindow;
338 }
339
340 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
341
342 @end
343
344 // ----------------------------------------------------------------------------
345 // creation/destruction
346 // ----------------------------------------------------------------------------
347
348 bool wxWebViewWebKit::Create(wxWindow *parent,
349 wxWindowID winID,
350 const wxString& strURL,
351 const wxPoint& pos,
352 const wxSize& size, long style,
353 const wxString& name)
354 {
355 m_busy = false;
356 //m_pageTitle = _("Untitled Page");
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 wxString wxWebViewWebKit::GetSelection()
571 {
572 if ( !m_webView )
573 return wxEmptyString;
574
575 NSString* selectedText = [[m_webView selectedDOMRange] toString];
576 return wxStringWithNSString( selectedText );
577 }
578
579 bool wxWebViewWebKit::CanIncreaseTextSize()
580 {
581 if ( !m_webView )
582 return false;
583
584 if ([m_webView canMakeTextLarger])
585 return true;
586 else
587 return false;
588 }
589
590 void wxWebViewWebKit::IncreaseTextSize()
591 {
592 if ( !m_webView )
593 return;
594
595 if (CanIncreaseTextSize())
596 [m_webView makeTextLarger:(WebView*)m_webView];
597 }
598
599 bool wxWebViewWebKit::CanDecreaseTextSize()
600 {
601 if ( !m_webView )
602 return false;
603
604 if ([m_webView canMakeTextSmaller])
605 return true;
606 else
607 return false;
608 }
609
610 void wxWebViewWebKit::DecreaseTextSize()
611 {
612 if ( !m_webView )
613 return;
614
615 if (CanDecreaseTextSize())
616 [m_webView makeTextSmaller:(WebView*)m_webView];
617 }
618
619 void wxWebViewWebKit::Print()
620 {
621
622 // TODO: allow specifying the "show prompt" parameter in Print() ?
623 bool showPrompt = true;
624
625 if ( !m_webView )
626 return;
627
628 id view = [[[m_webView mainFrame] frameView] documentView];
629 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
630 printInfo: [NSPrintInfo sharedPrintInfo]];
631 if (showPrompt)
632 {
633 [op setShowsPrintPanel: showPrompt];
634 // in my tests, the progress bar always freezes and it stops the whole
635 // print operation. do not turn this to true unless there is a
636 // workaround for the bug.
637 [op setShowsProgressPanel: false];
638 }
639 // Print it.
640 [op runOperation];
641 }
642
643 void wxWebViewWebKit::SetEditable(bool enable)
644 {
645 if ( !m_webView )
646 return;
647
648 [m_webView setEditable:enable ];
649 }
650
651 bool wxWebViewWebKit::IsEditable()
652 {
653 if ( !m_webView )
654 return false;
655
656 return [m_webView isEditable];
657 }
658
659 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
660 {
661 // there is only one supported zoom type at the moment so this setter
662 // does nothing beyond checking sanity
663 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
664 }
665
666 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
667 {
668 // for now that's the only one that is supported
669 // FIXME: does the default zoom type change depending on webkit versions? :S
670 // Then this will be wrong
671 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
672 }
673
674 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
675 {
676 switch (type)
677 {
678 // for now that's the only one that is supported
679 // TODO: I know recent versions of webkit support layout zoom too,
680 // check if we can support it
681 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
682 return true;
683
684 default:
685 return false;
686 }
687 }
688
689 int wxWebViewWebKit::GetScrollPos()
690 {
691 id result = [[m_webView windowScriptObject]
692 evaluateWebScript:@"document.body.scrollTop"];
693 return [result intValue];
694 }
695
696 void wxWebViewWebKit::SetScrollPos(int pos)
697 {
698 if ( !m_webView )
699 return;
700
701 wxString javascript;
702 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
703 [[m_webView windowScriptObject] evaluateWebScript:
704 (NSString*)wxNSStringWithWxString( javascript )];
705 }
706
707 wxString wxWebViewWebKit::GetSelectedText()
708 {
709 NSString* selection = [[m_webView selectedDOMRange] markupString];
710 if (!selection) return wxEmptyString;
711
712 return wxStringWithNSString(selection);
713 }
714
715 void wxWebViewWebKit::RunScript(const wxString& javascript)
716 {
717 if ( !m_webView )
718 return;
719
720 [[m_webView windowScriptObject] evaluateWebScript:
721 (NSString*)wxNSStringWithWxString( javascript )];
722 }
723
724 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
725 {
726 #if defined(__WXMAC_) && wxOSX_USE_CARBON
727 // This is a nasty hack because WebKit seems to lose its position when it is
728 // embedded in a control that is not itself the content view for a TLW.
729 // I put it in OnSize because these calcs are not perfect, and in fact are
730 // basically guesses based on reverse engineering, so it's best to give
731 // people the option of overriding OnSize with their own calcs if need be.
732 // I also left some test debugging print statements as a convenience if
733 // a(nother) problem crops up.
734
735 wxWindow* tlw = MacGetTopLevelWindow();
736
737 NSRect frame = [(WebView*)m_webView frame];
738 NSRect bounds = [(WebView*)m_webView bounds];
739
740 #if DEBUG_WEBKIT_SIZING
741 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
742 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
743 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
744 frame.origin.x, frame.origin.y,
745 frame.size.width, frame.size.height);
746 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
747 bounds.origin.x, bounds.origin.y,
748 bounds.size.width, bounds.size.height);
749 #endif
750
751 // This must be the case that Apple tested with, because well, in this one case
752 // we don't need to do anything! It just works. ;)
753 if (GetParent() == tlw) return;
754
755 // since we no longer use parent coordinates, we always want 0,0.
756 int x = 0;
757 int y = 0;
758
759 HIRect rect;
760 rect.origin.x = x;
761 rect.origin.y = y;
762
763 #if DEBUG_WEBKIT_SIZING
764 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
765 #endif
766
767 // NB: In most cases, when calling HIViewConvertRect, what people want is to
768 // use GetRootControl(), and this tripped me up at first. But in fact, what
769 // we want is the root view, because we need to make the y origin relative
770 // to the very top of the window, not its contents, since we later flip
771 // the y coordinate for Cocoa.
772 HIViewConvertRect (&rect, m_peer->GetControlRef(),
773 HIViewGetRoot(
774 (WindowRef) MacGetTopLevelWindowRef()
775 ));
776
777 x = (int)rect.origin.x;
778 y = (int)rect.origin.y;
779
780 #if DEBUG_WEBKIT_SIZING
781 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
782 #endif
783
784 if (tlw){
785 //flip the y coordinate to convert to Cocoa coordinates
786 y = tlw->GetSize().y - ((GetSize().y) + y);
787 }
788
789 #if DEBUG_WEBKIT_SIZING
790 printf("y = %d after flipping value\n", y);
791 #endif
792
793 frame.origin.x = x;
794 frame.origin.y = y;
795 [(WebView*)m_webView setFrame:frame];
796
797 if (IsShown())
798 [(WebView*)m_webView display];
799 event.Skip();
800 #endif
801 }
802
803 void wxWebViewWebKit::MacVisibilityChanged(){
804 #if defined(__WXMAC__) && wxOSX_USE_CARBON
805 bool isHidden = !IsControlVisible( m_peer->GetControlRef());
806 if (!isHidden)
807 [(WebView*)m_webView display];
808
809 [m_webView setHidden:isHidden];
810 #endif
811 }
812
813 void wxWebViewWebKit::LoadUrl(const wxString& url)
814 {
815 InternalLoadURL(url);
816 }
817
818 wxString wxWebViewWebKit::GetCurrentURL()
819 {
820 return wxStringWithNSString([m_webView mainFrameURL]);
821 }
822
823 wxString wxWebViewWebKit::GetCurrentTitle()
824 {
825 return GetPageTitle();
826 }
827
828 float wxWebViewWebKit::GetWebkitZoom()
829 {
830 return [m_webView textSizeMultiplier];
831 }
832
833 void wxWebViewWebKit::SetWebkitZoom(float zoom)
834 {
835 [m_webView setTextSizeMultiplier:zoom];
836 }
837
838 wxWebViewZoom wxWebViewWebKit::GetZoom()
839 {
840 float zoom = GetWebkitZoom();
841
842 // arbitrary way to map float zoom to our common zoom enum
843 if (zoom <= 0.55)
844 {
845 return wxWEB_VIEW_ZOOM_TINY;
846 }
847 else if (zoom > 0.55 && zoom <= 0.85)
848 {
849 return wxWEB_VIEW_ZOOM_SMALL;
850 }
851 else if (zoom > 0.85 && zoom <= 1.15)
852 {
853 return wxWEB_VIEW_ZOOM_MEDIUM;
854 }
855 else if (zoom > 1.15 && zoom <= 1.45)
856 {
857 return wxWEB_VIEW_ZOOM_LARGE;
858 }
859 else if (zoom > 1.45)
860 {
861 return wxWEB_VIEW_ZOOM_LARGEST;
862 }
863
864 // to shut up compilers, this can never be reached logically
865 wxASSERT(false);
866 return wxWEB_VIEW_ZOOM_MEDIUM;
867 }
868
869 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
870 {
871 // arbitrary way to map our common zoom enum to float zoom
872 switch (zoom)
873 {
874 case wxWEB_VIEW_ZOOM_TINY:
875 SetWebkitZoom(0.4f);
876 break;
877
878 case wxWEB_VIEW_ZOOM_SMALL:
879 SetWebkitZoom(0.7f);
880 break;
881
882 case wxWEB_VIEW_ZOOM_MEDIUM:
883 SetWebkitZoom(1.0f);
884 break;
885
886 case wxWEB_VIEW_ZOOM_LARGE:
887 SetWebkitZoom(1.3);
888 break;
889
890 case wxWEB_VIEW_ZOOM_LARGEST:
891 SetWebkitZoom(1.6);
892 break;
893
894 default:
895 wxASSERT(false);
896 }
897
898 }
899
900 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
901 {
902 if ( !m_webView )
903 return;
904
905 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
906 baseURL:[NSURL URLWithString:
907 wxNSStringWithWxString( baseUrl )]];
908 }
909
910 void wxWebViewWebKit::Cut()
911 {
912 if ( !m_webView )
913 return;
914
915 [(WebView*)m_webView cut:m_webView];
916 }
917
918 void wxWebViewWebKit::Copy()
919 {
920 if ( !m_webView )
921 return;
922
923 [(WebView*)m_webView copy:m_webView];
924 }
925
926 void wxWebViewWebKit::Paste()
927 {
928 if ( !m_webView )
929 return;
930
931 [(WebView*)m_webView paste:m_webView];
932 }
933
934 void wxWebViewWebKit::DeleteSelection()
935 {
936 if ( !m_webView )
937 return;
938
939 [(WebView*)m_webView deleteSelection];
940 }
941
942 //------------------------------------------------------------
943 // Listener interfaces
944 //------------------------------------------------------------
945
946 // NB: I'm still tracking this down, but it appears the Cocoa window
947 // still has these events fired on it while the Carbon control is being
948 // destroyed. Therefore, we must be careful to check both the existence
949 // of the Carbon control and the event handler before firing events.
950
951 @implementation MyFrameLoadMonitor
952
953 - initWithWxWindow: (wxWebViewWebKit*)inWindow
954 {
955 [super init];
956 webKitWindow = inWindow; // non retained
957 return self;
958 }
959
960 - (void)webView:(WebView *)sender
961 didStartProvisionalLoadForFrame:(WebFrame *)frame
962 {
963 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
964 wx_webviewctrls[sender]->m_busy = true;
965 }
966
967 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
968 {
969 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
970 wx_webviewctrls[sender]->m_busy = true;
971
972 if (webKitWindow && frame == [sender mainFrame]){
973 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
974 wxString target = wxStringWithNSString([frame name]);
975 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
976 wx_webviewctrls[sender]->GetId(),
977 wxStringWithNSString( url ),
978 target, false);
979
980 if (webKitWindow && webKitWindow->GetEventHandler())
981 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
982 }
983 }
984
985 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
986 {
987 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
988 wx_webviewctrls[sender]->m_busy = false;
989
990 if (webKitWindow && frame == [sender mainFrame]){
991 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
992
993 wxString target = wxStringWithNSString([frame name]);
994 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
995 wx_webviewctrls[sender]->GetId(),
996 wxStringWithNSString( url ),
997 target, false);
998
999 if (webKitWindow && webKitWindow->GetEventHandler())
1000 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1001 }
1002 }
1003
1004 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1005 {
1006 *out = wxWEB_NAV_ERR_OTHER;
1007
1008 if ([[error domain] isEqualToString:NSURLErrorDomain])
1009 {
1010 switch ([error code])
1011 {
1012 case NSURLErrorCannotFindHost:
1013 case NSURLErrorFileDoesNotExist:
1014 case NSURLErrorRedirectToNonExistentLocation:
1015 *out = wxWEB_NAV_ERR_NOT_FOUND;
1016 break;
1017
1018 case NSURLErrorResourceUnavailable:
1019 case NSURLErrorHTTPTooManyRedirects:
1020 case NSURLErrorDataLengthExceedsMaximum:
1021 case NSURLErrorBadURL:
1022 case NSURLErrorFileIsDirectory:
1023 *out = wxWEB_NAV_ERR_REQUEST;
1024 break;
1025
1026 case NSURLErrorTimedOut:
1027 case NSURLErrorDNSLookupFailed:
1028 case NSURLErrorNetworkConnectionLost:
1029 case NSURLErrorCannotConnectToHost:
1030 case NSURLErrorNotConnectedToInternet:
1031 //case NSURLErrorInternationalRoamingOff:
1032 //case NSURLErrorCallIsActive:
1033 //case NSURLErrorDataNotAllowed:
1034 *out = wxWEB_NAV_ERR_CONNECTION;
1035 break;
1036
1037 case NSURLErrorCancelled:
1038 case NSURLErrorUserCancelledAuthentication:
1039 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1040 break;
1041
1042 case NSURLErrorCannotDecodeRawData:
1043 case NSURLErrorCannotDecodeContentData:
1044 case NSURLErrorBadServerResponse:
1045 case NSURLErrorCannotParseResponse:
1046 *out = wxWEB_NAV_ERR_REQUEST;
1047 break;
1048
1049 case NSURLErrorUserAuthenticationRequired:
1050 case NSURLErrorSecureConnectionFailed:
1051 case NSURLErrorClientCertificateRequired:
1052 *out = wxWEB_NAV_ERR_AUTH;
1053 break;
1054
1055 case NSURLErrorNoPermissionsToReadFile:
1056 *out = wxWEB_NAV_ERR_SECURITY;
1057 break;
1058
1059 case NSURLErrorServerCertificateHasBadDate:
1060 case NSURLErrorServerCertificateUntrusted:
1061 case NSURLErrorServerCertificateHasUnknownRoot:
1062 case NSURLErrorServerCertificateNotYetValid:
1063 case NSURLErrorClientCertificateRejected:
1064 *out = wxWEB_NAV_ERR_CERTIFICATE;
1065 break;
1066 }
1067 }
1068
1069 wxString message = wxStringWithNSString([error localizedDescription]);
1070 NSString* detail = [error localizedFailureReason];
1071 if (detail != NULL)
1072 {
1073 message = message + " (" + wxStringWithNSString(detail) + ")";
1074 }
1075 return message;
1076 }
1077
1078 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1079 forFrame:(WebFrame *)frame
1080 {
1081 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1082 wx_webviewctrls[sender]->m_busy = false;
1083
1084 if (webKitWindow && frame == [sender mainFrame]){
1085 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1086
1087 wxWebNavigationError type;
1088 wxString description = nsErrorToWxHtmlError(error, &type);
1089 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1090 wx_webviewctrls[sender]->GetId(),
1091 wxStringWithNSString( url ),
1092 wxEmptyString, false);
1093 thisEvent.SetString(description);
1094 thisEvent.SetInt(type);
1095
1096 if (webKitWindow && webKitWindow->GetEventHandler())
1097 {
1098 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1099 }
1100 }
1101 }
1102
1103 - (void)webView:(WebView *)sender
1104 didFailProvisionalLoadWithError:(NSError*)error
1105 forFrame:(WebFrame *)frame
1106 {
1107 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1108 wx_webviewctrls[sender]->m_busy = false;
1109
1110 if (webKitWindow && frame == [sender mainFrame]){
1111 NSString *url = [[[[frame provisionalDataSource] request] URL]
1112 absoluteString];
1113
1114 wxWebNavigationError type;
1115 wxString description = nsErrorToWxHtmlError(error, &type);
1116 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1117 wx_webviewctrls[sender]->GetId(),
1118 wxStringWithNSString( url ),
1119 wxEmptyString, false);
1120 thisEvent.SetString(description);
1121 thisEvent.SetInt(type);
1122
1123 if (webKitWindow && webKitWindow->GetEventHandler())
1124 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1125 }
1126 }
1127
1128 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1129 forFrame:(WebFrame *)frame
1130 {
1131 if (webKitWindow && frame == [sender mainFrame])
1132 {
1133 webKitWindow->SetPageTitle(wxStringWithNSString( title ));
1134 }
1135 }
1136 @end
1137
1138 @implementation MyPolicyDelegate
1139
1140 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1141 {
1142 [super init];
1143 webKitWindow = inWindow; // non retained
1144 return self;
1145 }
1146
1147 - (void)webView:(WebView *)sender
1148 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1149 request:(NSURLRequest *)request
1150 frame:(WebFrame *)frame
1151 decisionListener:(id<WebPolicyDecisionListener>)listener
1152 {
1153 wxUnusedVar(frame);
1154
1155 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1156 wx_webviewctrls[sender]->m_busy = true;
1157 NSString *url = [[request URL] absoluteString];
1158 wxString target = wxStringWithNSString([frame name]);
1159 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1160 wx_webviewctrls[sender]->GetId(),
1161 wxStringWithNSString( url ), target, true);
1162
1163 if (webKitWindow && webKitWindow->GetEventHandler())
1164 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1165
1166 if (thisEvent.IsVetoed())
1167 {
1168 wx_webviewctrls[sender]->m_busy = false;
1169 [listener ignore];
1170 }
1171 else
1172 {
1173 [listener use];
1174 }
1175 }
1176
1177 - (void)webView:(WebView *)sender
1178 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1179 request:(NSURLRequest *)request
1180 newFrameName:(NSString *)frameName
1181 decisionListener:(id < WebPolicyDecisionListener >)listener
1182 {
1183 wxUnusedVar(actionInformation);
1184
1185 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1186 NSString *url = [[request URL] absoluteString];
1187 wxString target = wxStringWithNSString([frame name]);
1188 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1189 wx_webviewctrls[sender]->GetId(),
1190 wxStringWithNSString( url ), target, true);
1191
1192 if (webKitWindow && webKitWindow->GetEventHandler())
1193 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1194
1195 [listener ignore];
1196 }
1197 @end
1198
1199 //#endif //wxHAVE_WEB_BACKEND_OSX_WEBKIT