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