]> git.saurik.com Git - wxWidgets.git/blob - src/osx/webview_webkit.mm
Add start of selection api, support for HasSelection, SelectAll and DeleteSelection...
[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 inline int wxNavTypeFromWebNavType(int type){
327 if (type == WebNavigationTypeLinkClicked)
328 return wxWEBKIT_NAV_LINK_CLICKED;
329
330 if (type == WebNavigationTypeFormSubmitted)
331 return wxWEBKIT_NAV_FORM_SUBMITTED;
332
333 if (type == WebNavigationTypeBackForward)
334 return wxWEBKIT_NAV_BACK_NEXT;
335
336 if (type == WebNavigationTypeReload)
337 return wxWEBKIT_NAV_RELOAD;
338
339 if (type == WebNavigationTypeFormResubmitted)
340 return wxWEBKIT_NAV_FORM_RESUBMITTED;
341
342 return wxWEBKIT_NAV_OTHER;
343 }
344
345 @interface MyFrameLoadMonitor : NSObject
346 {
347 wxWebViewWebKit* webKitWindow;
348 }
349
350 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
351
352 @end
353
354 @interface MyPolicyDelegate : NSObject
355 {
356 wxWebViewWebKit* webKitWindow;
357 }
358
359 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
360
361 @end
362
363 // ----------------------------------------------------------------------------
364 // creation/destruction
365 // ----------------------------------------------------------------------------
366
367 bool wxWebViewWebKit::Create(wxWindow *parent,
368 wxWindowID winID,
369 const wxString& strURL,
370 const wxPoint& pos,
371 const wxSize& size, long style,
372 const wxString& name)
373 {
374 m_busy = false;
375 //m_pageTitle = _("Untitled Page");
376
377 //still needed for wxCocoa??
378 /*
379 int width, height;
380 wxSize sizeInstance;
381 if (size.x == wxDefaultCoord || size.y == wxDefaultCoord)
382 {
383 m_parent->GetClientSize(&width, &height);
384 sizeInstance.x = width;
385 sizeInstance.y = height;
386 }
387 else
388 {
389 sizeInstance.x = size.x;
390 sizeInstance.y = size.y;
391 }
392 */
393 // now create and attach WebKit view...
394 #ifdef __WXCOCOA__
395 wxControl::Create(parent, m_windowID, pos, sizeInstance, style, name);
396 SetSize(pos.x, pos.y, sizeInstance.x, sizeInstance.y);
397
398 wxTopLevelWindowCocoa *topWin = wxDynamicCast(this, wxTopLevelWindowCocoa);
399 NSWindow* nsWin = topWin->GetNSWindow();
400 NSRect rect;
401 rect.origin.x = pos.x;
402 rect.origin.y = pos.y;
403 rect.size.width = sizeInstance.x;
404 rect.size.height = sizeInstance.y;
405 m_webView = (WebView*)[[WebView alloc] initWithFrame:rect
406 frameName:@"webkitFrame"
407 groupName:@"webkitGroup"];
408 SetNSView(m_webView);
409 [m_cocoaNSView release];
410
411 if(m_parent) m_parent->CocoaAddChild(this);
412 SetInitialFrameRect(pos,sizeInstance);
413 #else
414 m_macIsUserPane = false;
415 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
416
417 #if wxOSX_USE_CARBON
418 m_peer = new wxMacControl(this);
419 WebInitForCarbon();
420 HIWebViewCreate( m_peer->GetControlRefAddr() );
421
422 m_webView = (WebView*) HIWebViewGetWebView( m_peer->GetControlRef() );
423
424 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
425 if ( UMAGetSystemVersion() >= 0x1030 )
426 HIViewChangeFeatures( m_peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
427 #endif
428 InstallControlEventHandler(m_peer->GetControlRef(),
429 GetwxWebViewWebKitEventHandlerUPP(),
430 GetEventTypeCount(eventList), eventList, this,
431 (EventHandlerRef *)&m_webKitCtrlEventHandler);
432 #else
433 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
434 m_webView = [[WebView alloc] initWithFrame:r
435 frameName:@"webkitFrame"
436 groupName:@"webkitGroup"];
437 m_peer = new wxWidgetCocoaImpl( this, m_webView );
438 #endif
439
440 wx_webviewctrls[m_webView] = this;
441
442 MacPostControlCreate(pos, size);
443
444 #if wxOSX_USE_CARBON
445 HIViewSetVisible( m_peer->GetControlRef(), true );
446 #endif
447 [m_webView setHidden:false];
448
449 #endif
450
451 // Register event listener interfaces
452 MyFrameLoadMonitor* myFrameLoadMonitor =
453 [[MyFrameLoadMonitor alloc] initWithWxWindow: this];
454
455 [m_webView setFrameLoadDelegate:myFrameLoadMonitor];
456
457 // this is used to veto page loads, etc.
458 MyPolicyDelegate* myPolicyDelegate =
459 [[MyPolicyDelegate alloc] initWithWxWindow: this];
460
461 [m_webView setPolicyDelegate:myPolicyDelegate];
462
463 InternalLoadURL(strURL);
464 return true;
465 }
466
467 wxWebViewWebKit::~wxWebViewWebKit()
468 {
469 MyFrameLoadMonitor* myFrameLoadMonitor = [m_webView frameLoadDelegate];
470 MyPolicyDelegate* myPolicyDelegate = [m_webView policyDelegate];
471 [m_webView setFrameLoadDelegate: nil];
472 [m_webView setPolicyDelegate: nil];
473
474 if (myFrameLoadMonitor)
475 [myFrameLoadMonitor release];
476
477 if (myPolicyDelegate)
478 [myPolicyDelegate release];
479 }
480
481 // ----------------------------------------------------------------------------
482 // public methods
483 // ----------------------------------------------------------------------------
484
485 void wxWebViewWebKit::InternalLoadURL(const wxString &url)
486 {
487 if( !m_webView )
488 return;
489
490 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
491 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
492 }
493
494 bool wxWebViewWebKit::CanGoBack()
495 {
496 if ( !m_webView )
497 return false;
498
499 return [m_webView canGoBack];
500 }
501
502 bool wxWebViewWebKit::CanGoForward()
503 {
504 if ( !m_webView )
505 return false;
506
507 return [m_webView canGoForward];
508 }
509
510 void wxWebViewWebKit::GoBack()
511 {
512 if ( !m_webView )
513 return;
514
515 bool result = [(WebView*)m_webView goBack];
516
517 // TODO: return result (if it also exists in other backends...)
518 //return result;
519 }
520
521 void wxWebViewWebKit::GoForward()
522 {
523 if ( !m_webView )
524 return;
525
526 bool result = [(WebView*)m_webView goForward];
527
528 // TODO: return result (if it also exists in other backends...)
529 //return result;
530 }
531
532 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
533 {
534 if ( !m_webView )
535 return;
536
537 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
538 {
539 // TODO: test this indeed bypasses the cache
540 [[m_webView preferences] setUsesPageCache:NO];
541 [[m_webView mainFrame] reload];
542 [[m_webView preferences] setUsesPageCache:YES];
543 }
544 else
545 {
546 [[m_webView mainFrame] reload];
547 }
548 }
549
550 void wxWebViewWebKit::Stop()
551 {
552 if ( !m_webView )
553 return;
554
555 [[m_webView mainFrame] stopLoading];
556 }
557
558 bool wxWebViewWebKit::CanGetPageSource()
559 {
560 if ( !m_webView )
561 return false;
562
563 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
564 return ( [[dataSource representation] canProvideDocumentSource] );
565 }
566
567 wxString wxWebViewWebKit::GetPageSource()
568 {
569
570 if (CanGetPageSource())
571 {
572 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
573 wxASSERT (dataSource != nil);
574
575 id<WebDocumentRepresentation> representation = [dataSource representation];
576 wxASSERT (representation != nil);
577
578 NSString* source = [representation documentSource];
579 if (source == nil)
580 {
581 return wxEmptyString;
582 }
583
584 return wxStringWithNSString( source );
585 }
586
587 return wxEmptyString;
588 }
589
590 wxString wxWebViewWebKit::GetSelection()
591 {
592 if ( !m_webView )
593 return wxEmptyString;
594
595 NSString* selectedText = [[m_webView selectedDOMRange] toString];
596 return wxStringWithNSString( selectedText );
597 }
598
599 bool wxWebViewWebKit::CanIncreaseTextSize()
600 {
601 if ( !m_webView )
602 return false;
603
604 if ([m_webView canMakeTextLarger])
605 return true;
606 else
607 return false;
608 }
609
610 void wxWebViewWebKit::IncreaseTextSize()
611 {
612 if ( !m_webView )
613 return;
614
615 if (CanIncreaseTextSize())
616 [m_webView makeTextLarger:(WebView*)m_webView];
617 }
618
619 bool wxWebViewWebKit::CanDecreaseTextSize()
620 {
621 if ( !m_webView )
622 return false;
623
624 if ([m_webView canMakeTextSmaller])
625 return true;
626 else
627 return false;
628 }
629
630 void wxWebViewWebKit::DecreaseTextSize()
631 {
632 if ( !m_webView )
633 return;
634
635 if (CanDecreaseTextSize())
636 [m_webView makeTextSmaller:(WebView*)m_webView];
637 }
638
639 void wxWebViewWebKit::Print()
640 {
641
642 // TODO: allow specifying the "show prompt" parameter in Print() ?
643 bool showPrompt = true;
644
645 if ( !m_webView )
646 return;
647
648 id view = [[[m_webView mainFrame] frameView] documentView];
649 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
650 printInfo: [NSPrintInfo sharedPrintInfo]];
651 if (showPrompt)
652 {
653 [op setShowsPrintPanel: showPrompt];
654 // in my tests, the progress bar always freezes and it stops the whole
655 // print operation. do not turn this to true unless there is a
656 // workaround for the bug.
657 [op setShowsProgressPanel: false];
658 }
659 // Print it.
660 [op runOperation];
661 }
662
663 void wxWebViewWebKit::SetEditable(bool enable)
664 {
665 if ( !m_webView )
666 return;
667
668 [m_webView setEditable:enable ];
669 }
670
671 bool wxWebViewWebKit::IsEditable()
672 {
673 if ( !m_webView )
674 return false;
675
676 return [m_webView isEditable];
677 }
678
679 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
680 {
681 // there is only one supported zoom type at the moment so this setter
682 // does nothing beyond checking sanity
683 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
684 }
685
686 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
687 {
688 // for now that's the only one that is supported
689 // FIXME: does the default zoom type change depending on webkit versions? :S
690 // Then this will be wrong
691 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
692 }
693
694 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
695 {
696 switch (type)
697 {
698 // for now that's the only one that is supported
699 // TODO: I know recent versions of webkit support layout zoom too,
700 // check if we can support it
701 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
702 return true;
703
704 default:
705 return false;
706 }
707 }
708
709 int wxWebViewWebKit::GetScrollPos()
710 {
711 id result = [[m_webView windowScriptObject]
712 evaluateWebScript:@"document.body.scrollTop"];
713 return [result intValue];
714 }
715
716 void wxWebViewWebKit::SetScrollPos(int pos)
717 {
718 if ( !m_webView )
719 return;
720
721 wxString javascript;
722 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
723 [[m_webView windowScriptObject] evaluateWebScript:
724 (NSString*)wxNSStringWithWxString( javascript )];
725 }
726
727 wxString wxWebViewWebKit::GetSelectedText()
728 {
729 NSString* selection = [[m_webView selectedDOMRange] markupString];
730 if (!selection) return wxEmptyString;
731
732 return wxStringWithNSString(selection);
733 }
734
735 wxString wxWebViewWebKit::RunScript(const wxString& javascript)
736 {
737 if ( !m_webView )
738 return wxEmptyString;
739
740 id result = [[m_webView windowScriptObject] evaluateWebScript:
741 (NSString*)wxNSStringWithWxString( javascript )];
742
743 NSString* resultAsString;
744 NSString* className = NSStringFromClass([result class]);
745
746 if ([className isEqualToString:@"NSCFNumber"])
747 {
748 resultAsString = [NSString stringWithFormat:@"%@", result];
749 }
750 else if ([className isEqualToString:@"NSCFString"])
751 {
752 resultAsString = result;
753 }
754 else if ([className isEqualToString:@"NSCFBoolean"])
755 {
756 if ([result boolValue])
757 resultAsString = @"true";
758 else
759 resultAsString = @"false";
760 }
761 else if ([className isEqualToString:@"WebScriptObject"])
762 {
763 resultAsString = [result stringRepresentation];
764 }
765 else
766 {
767 return wxString();
768 }
769
770 return wxStringWithNSString( resultAsString );
771 }
772
773 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
774 {
775 #if defined(__WXMAC_) && wxOSX_USE_CARBON
776 // This is a nasty hack because WebKit seems to lose its position when it is
777 // embedded in a control that is not itself the content view for a TLW.
778 // I put it in OnSize because these calcs are not perfect, and in fact are
779 // basically guesses based on reverse engineering, so it's best to give
780 // people the option of overriding OnSize with their own calcs if need be.
781 // I also left some test debugging print statements as a convenience if
782 // a(nother) problem crops up.
783
784 wxWindow* tlw = MacGetTopLevelWindow();
785
786 NSRect frame = [(WebView*)m_webView frame];
787 NSRect bounds = [(WebView*)m_webView bounds];
788
789 #if DEBUG_WEBKIT_SIZING
790 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
791 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
792 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
793 frame.origin.x, frame.origin.y,
794 frame.size.width, frame.size.height);
795 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
796 bounds.origin.x, bounds.origin.y,
797 bounds.size.width, bounds.size.height);
798 #endif
799
800 // This must be the case that Apple tested with, because well, in this one case
801 // we don't need to do anything! It just works. ;)
802 if (GetParent() == tlw) return;
803
804 // since we no longer use parent coordinates, we always want 0,0.
805 int x = 0;
806 int y = 0;
807
808 HIRect rect;
809 rect.origin.x = x;
810 rect.origin.y = y;
811
812 #if DEBUG_WEBKIT_SIZING
813 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
814 #endif
815
816 // NB: In most cases, when calling HIViewConvertRect, what people want is to
817 // use GetRootControl(), and this tripped me up at first. But in fact, what
818 // we want is the root view, because we need to make the y origin relative
819 // to the very top of the window, not its contents, since we later flip
820 // the y coordinate for Cocoa.
821 HIViewConvertRect (&rect, m_peer->GetControlRef(),
822 HIViewGetRoot(
823 (WindowRef) MacGetTopLevelWindowRef()
824 ));
825
826 x = (int)rect.origin.x;
827 y = (int)rect.origin.y;
828
829 #if DEBUG_WEBKIT_SIZING
830 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
831 #endif
832
833 if (tlw){
834 //flip the y coordinate to convert to Cocoa coordinates
835 y = tlw->GetSize().y - ((GetSize().y) + y);
836 }
837
838 #if DEBUG_WEBKIT_SIZING
839 printf("y = %d after flipping value\n", y);
840 #endif
841
842 frame.origin.x = x;
843 frame.origin.y = y;
844 [(WebView*)m_webView setFrame:frame];
845
846 if (IsShown())
847 [(WebView*)m_webView display];
848 event.Skip();
849 #endif
850 }
851
852 void wxWebViewWebKit::MacVisibilityChanged(){
853 #if defined(__WXMAC__) && wxOSX_USE_CARBON
854 bool isHidden = !IsControlVisible( m_peer->GetControlRef());
855 if (!isHidden)
856 [(WebView*)m_webView display];
857
858 [m_webView setHidden:isHidden];
859 #endif
860 }
861
862 void wxWebViewWebKit::LoadUrl(const wxString& url)
863 {
864 InternalLoadURL(url);
865 }
866
867 wxString wxWebViewWebKit::GetCurrentURL()
868 {
869 return wxStringWithNSString([m_webView mainFrameURL]);
870 }
871
872 wxString wxWebViewWebKit::GetCurrentTitle()
873 {
874 return GetPageTitle();
875 }
876
877 float wxWebViewWebKit::GetWebkitZoom()
878 {
879 return [m_webView textSizeMultiplier];
880 }
881
882 void wxWebViewWebKit::SetWebkitZoom(float zoom)
883 {
884 [m_webView setTextSizeMultiplier:zoom];
885 }
886
887 wxWebViewZoom wxWebViewWebKit::GetZoom()
888 {
889 float zoom = GetWebkitZoom();
890
891 // arbitrary way to map float zoom to our common zoom enum
892 if (zoom <= 0.55)
893 {
894 return wxWEB_VIEW_ZOOM_TINY;
895 }
896 else if (zoom > 0.55 && zoom <= 0.85)
897 {
898 return wxWEB_VIEW_ZOOM_SMALL;
899 }
900 else if (zoom > 0.85 && zoom <= 1.15)
901 {
902 return wxWEB_VIEW_ZOOM_MEDIUM;
903 }
904 else if (zoom > 1.15 && zoom <= 1.45)
905 {
906 return wxWEB_VIEW_ZOOM_LARGE;
907 }
908 else if (zoom > 1.45)
909 {
910 return wxWEB_VIEW_ZOOM_LARGEST;
911 }
912
913 // to shut up compilers, this can never be reached logically
914 wxASSERT(false);
915 return wxWEB_VIEW_ZOOM_MEDIUM;
916 }
917
918 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
919 {
920 // arbitrary way to map our common zoom enum to float zoom
921 switch (zoom)
922 {
923 case wxWEB_VIEW_ZOOM_TINY:
924 SetWebkitZoom(0.4f);
925 break;
926
927 case wxWEB_VIEW_ZOOM_SMALL:
928 SetWebkitZoom(0.7f);
929 break;
930
931 case wxWEB_VIEW_ZOOM_MEDIUM:
932 SetWebkitZoom(1.0f);
933 break;
934
935 case wxWEB_VIEW_ZOOM_LARGE:
936 SetWebkitZoom(1.3);
937 break;
938
939 case wxWEB_VIEW_ZOOM_LARGEST:
940 SetWebkitZoom(1.6);
941 break;
942
943 default:
944 wxASSERT(false);
945 }
946
947 }
948
949 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
950 {
951 if ( !m_webView )
952 return;
953
954 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
955 baseURL:[NSURL URLWithString:
956 wxNSStringWithWxString( baseUrl )]];
957 }
958
959 void wxWebViewWebKit::Cut()
960 {
961 if ( !m_webView )
962 return;
963
964 [(WebView*)m_webView cut];
965 }
966
967 void wxWebViewWebKit::Copy()
968 {
969 if ( !m_webView )
970 return;
971
972 [(WebView*)m_webView copy];
973 }
974
975 void wxWebViewWebKit::Paste()
976 {
977 if ( !m_webView )
978 return;
979
980 [(WebView*)m_webView paste];
981 }
982
983 void wxWebViewWebKit::DeleteSelection()
984 {
985 if ( !m_webView )
986 return;
987
988 [(WebView*)m_webView deleteSelection];
989 }
990
991 //------------------------------------------------------------
992 // Listener interfaces
993 //------------------------------------------------------------
994
995 // NB: I'm still tracking this down, but it appears the Cocoa window
996 // still has these events fired on it while the Carbon control is being
997 // destroyed. Therefore, we must be careful to check both the existence
998 // of the Carbon control and the event handler before firing events.
999
1000 @implementation MyFrameLoadMonitor
1001
1002 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1003 {
1004 [super init];
1005 webKitWindow = inWindow; // non retained
1006 return self;
1007 }
1008
1009 - (void)webView:(WebView *)sender
1010 didStartProvisionalLoadForFrame:(WebFrame *)frame
1011 {
1012 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1013 wx_webviewctrls[sender]->m_busy = true;
1014 }
1015
1016 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1017 {
1018 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1019 wx_webviewctrls[sender]->m_busy = true;
1020
1021 if (webKitWindow && frame == [sender mainFrame]){
1022 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1023 wxString target = wxStringWithNSString([frame name]);
1024 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1025 wx_webviewctrls[sender]->GetId(),
1026 wxStringWithNSString( url ),
1027 target, false);
1028
1029 if (webKitWindow && webKitWindow->GetEventHandler())
1030 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1031 }
1032 }
1033
1034 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1035 {
1036 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1037 wx_webviewctrls[sender]->m_busy = false;
1038
1039 if (webKitWindow && frame == [sender mainFrame]){
1040 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1041
1042 wxString target = wxStringWithNSString([frame name]);
1043 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1044 wx_webviewctrls[sender]->GetId(),
1045 wxStringWithNSString( url ),
1046 target, false);
1047
1048 if (webKitWindow && webKitWindow->GetEventHandler())
1049 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1050 }
1051 }
1052
1053 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1054 {
1055 *out = wxWEB_NAV_ERR_OTHER;
1056
1057 if ([[error domain] isEqualToString:NSURLErrorDomain])
1058 {
1059 switch ([error code])
1060 {
1061 case NSURLErrorCannotFindHost:
1062 case NSURLErrorFileDoesNotExist:
1063 case NSURLErrorRedirectToNonExistentLocation:
1064 *out = wxWEB_NAV_ERR_NOT_FOUND;
1065 break;
1066
1067 case NSURLErrorResourceUnavailable:
1068 case NSURLErrorHTTPTooManyRedirects:
1069 case NSURLErrorDataLengthExceedsMaximum:
1070 case NSURLErrorBadURL:
1071 case NSURLErrorFileIsDirectory:
1072 *out = wxWEB_NAV_ERR_REQUEST;
1073 break;
1074
1075 case NSURLErrorTimedOut:
1076 case NSURLErrorDNSLookupFailed:
1077 case NSURLErrorNetworkConnectionLost:
1078 case NSURLErrorCannotConnectToHost:
1079 case NSURLErrorNotConnectedToInternet:
1080 //case NSURLErrorInternationalRoamingOff:
1081 //case NSURLErrorCallIsActive:
1082 //case NSURLErrorDataNotAllowed:
1083 *out = wxWEB_NAV_ERR_CONNECTION;
1084 break;
1085
1086 case NSURLErrorCancelled:
1087 case NSURLErrorUserCancelledAuthentication:
1088 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1089 break;
1090
1091 case NSURLErrorCannotDecodeRawData:
1092 case NSURLErrorCannotDecodeContentData:
1093 case NSURLErrorBadServerResponse:
1094 case NSURLErrorCannotParseResponse:
1095 *out = wxWEB_NAV_ERR_REQUEST;
1096 break;
1097
1098 case NSURLErrorUserAuthenticationRequired:
1099 case NSURLErrorSecureConnectionFailed:
1100 case NSURLErrorClientCertificateRequired:
1101 *out = wxWEB_NAV_ERR_AUTH;
1102 break;
1103
1104 case NSURLErrorNoPermissionsToReadFile:
1105 *out = wxWEB_NAV_ERR_SECURITY;
1106 break;
1107
1108 case NSURLErrorServerCertificateHasBadDate:
1109 case NSURLErrorServerCertificateUntrusted:
1110 case NSURLErrorServerCertificateHasUnknownRoot:
1111 case NSURLErrorServerCertificateNotYetValid:
1112 case NSURLErrorClientCertificateRejected:
1113 *out = wxWEB_NAV_ERR_CERTIFICATE;
1114 break;
1115 }
1116 }
1117
1118 wxString message = wxStringWithNSString([error localizedDescription]);
1119 NSString* detail = [error localizedFailureReason];
1120 if (detail != NULL)
1121 {
1122 message = message + " (" + wxStringWithNSString(detail) + ")";
1123 }
1124 return message;
1125 }
1126
1127 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1128 forFrame:(WebFrame *)frame
1129 {
1130 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1131 wx_webviewctrls[sender]->m_busy = false;
1132
1133 if (webKitWindow && frame == [sender mainFrame]){
1134 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1135
1136 wxWebNavigationError type;
1137 wxString description = nsErrorToWxHtmlError(error, &type);
1138 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1139 wx_webviewctrls[sender]->GetId(),
1140 wxStringWithNSString( url ),
1141 wxEmptyString, false);
1142 thisEvent.SetString(description);
1143 thisEvent.SetInt(type);
1144
1145 if (webKitWindow && webKitWindow->GetEventHandler())
1146 {
1147 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1148 }
1149 }
1150 }
1151
1152 - (void)webView:(WebView *)sender
1153 didFailProvisionalLoadWithError:(NSError*)error
1154 forFrame:(WebFrame *)frame
1155 {
1156 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1157 wx_webviewctrls[sender]->m_busy = false;
1158
1159 if (webKitWindow && frame == [sender mainFrame]){
1160 NSString *url = [[[[frame provisionalDataSource] request] URL]
1161 absoluteString];
1162
1163 wxWebNavigationError type;
1164 wxString description = nsErrorToWxHtmlError(error, &type);
1165 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1166 wx_webviewctrls[sender]->GetId(),
1167 wxStringWithNSString( url ),
1168 wxEmptyString, false);
1169 thisEvent.SetString(description);
1170 thisEvent.SetInt(type);
1171
1172 if (webKitWindow && webKitWindow->GetEventHandler())
1173 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1174 }
1175 }
1176
1177 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1178 forFrame:(WebFrame *)frame
1179 {
1180 if (webKitWindow && frame == [sender mainFrame])
1181 {
1182 webKitWindow->SetPageTitle(wxStringWithNSString( title ));
1183 }
1184 }
1185 @end
1186
1187 @implementation MyPolicyDelegate
1188
1189 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1190 {
1191 [super init];
1192 webKitWindow = inWindow; // non retained
1193 return self;
1194 }
1195
1196 - (void)webView:(WebView *)sender
1197 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1198 request:(NSURLRequest *)request
1199 frame:(WebFrame *)frame
1200 decisionListener:(id<WebPolicyDecisionListener>)listener
1201 {
1202 //wxUnusedVar(sender);
1203 wxUnusedVar(frame);
1204
1205 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1206 wx_webviewctrls[sender]->m_busy = true;
1207 NSString *url = [[request URL] absoluteString];
1208 wxString target = wxStringWithNSString([frame name]);
1209 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1210 wx_webviewctrls[sender]->GetId(),
1211 wxStringWithNSString( url ), target, true);
1212
1213 if (webKitWindow && webKitWindow->GetEventHandler())
1214 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1215
1216 if (thisEvent.IsVetoed())
1217 {
1218 wx_webviewctrls[sender]->m_busy = false;
1219 [listener ignore];
1220 }
1221 else
1222 {
1223 [listener use];
1224 }
1225 }
1226
1227 - (void)webView:(WebView *)sender
1228 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1229 request:(NSURLRequest *)request
1230 newFrameName:(NSString *)frameName
1231 decisionListener:(id < WebPolicyDecisionListener >)listener
1232 {
1233 wxUnusedVar(sender);
1234 wxUnusedVar(actionInformation);
1235
1236 [listener ignore];
1237 }
1238 @end
1239
1240 #endif //wxHAVE_WEB_BACKEND_OSX_WEBKIT