Rename source files for consistency
[wxWidgets.git] / src / osx / webview_webkit.mm
1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/osx/webview_webkit.mm
3 // Purpose:     wxOSXWebKitCtrl - 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*, wxOSXWebKitCtrl*> wx_webviewctrls;
41
42 #define DEBUG_WEBKIT_SIZING 0
43
44 // ----------------------------------------------------------------------------
45 // macros
46 // ----------------------------------------------------------------------------
47
48 IMPLEMENT_DYNAMIC_CLASS(wxOSXWebKitCtrl, wxControl)
49
50 BEGIN_EVENT_TABLE(wxOSXWebKitCtrl, wxControl)
51 #if defined(__WXMAC__) && wxOSX_USE_CARBON
52     EVT_SIZE(wxOSXWebKitCtrl::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     wxOSXWebKitCtrl* thisWindow = (wxOSXWebKitCtrl*) 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 wxOSXWebKitCtrlEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
233 {
234     OSStatus result = eventNotHandledErr ;
235
236     wxMacCarbonEvent cEvent( event ) ;
237
238     ControlRef controlRef ;
239     wxOSXWebKitCtrl* thisWindow = (wxOSXWebKitCtrl*) 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( wxOSXWebKitCtrlEventHandler )
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     wxOSXWebKitCtrl* webKitWindow;
348 }
349
350 - initWithWxWindow: (wxOSXWebKitCtrl*)inWindow;
351
352 @end
353
354 @interface MyPolicyDelegate : NSObject
355 {
356     wxOSXWebKitCtrl* webKitWindow;
357 }
358
359 - initWithWxWindow: (wxOSXWebKitCtrl*)inWindow;
360
361 @end
362
363 // ----------------------------------------------------------------------------
364 // creation/destruction
365 // ----------------------------------------------------------------------------
366
367 bool wxOSXWebKitCtrl::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                                GetwxOSXWebKitCtrlEventHandlerUPP(),
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 wxOSXWebKitCtrl::~wxOSXWebKitCtrl()
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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::CanGoBack()
495 {
496     if ( !m_webView )
497         return false;
498
499     return [m_webView canGoBack];
500 }
501
502 bool wxOSXWebKitCtrl::CanGoForward()
503 {
504     if ( !m_webView )
505         return false;
506
507     return [m_webView canGoForward];
508 }
509
510 void wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::Stop()
551 {
552     if ( !m_webView )
553         return;
554
555     [[m_webView mainFrame] stopLoading];
556 }
557
558 bool wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::IncreaseTextSize()
611 {
612     if ( !m_webView )
613         return;
614
615     if (CanIncreaseTextSize())
616         [m_webView makeTextLarger:(WebView*)m_webView];
617 }
618
619 bool wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::DecreaseTextSize()
631 {
632     if ( !m_webView )
633         return;
634
635     if (CanDecreaseTextSize())
636         [m_webView makeTextSmaller:(WebView*)m_webView];
637 }
638
639 void wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::MakeEditable(bool enable)
664 {
665     if ( !m_webView )
666         return;
667
668     [m_webView setEditable:enable ];
669 }
670
671 bool wxOSXWebKitCtrl::IsEditable()
672 {
673     if ( !m_webView )
674         return false;
675
676     return [m_webView isEditable];
677 }
678
679 void wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::GetScrollPos()
710 {
711     id result = [[m_webView windowScriptObject]
712                     evaluateWebScript:@"document.body.scrollTop"];
713     return [result intValue];
714 }
715
716 void wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::GetSelectedText()
728 {
729     NSString* selection = [[m_webView selectedDOMRange] markupString];
730     if (!selection) return wxEmptyString;
731
732     return wxStringWithNSString(selection);
733 }
734
735 wxString wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::LoadUrl(const wxString& url)
863 {
864     InternalLoadURL(url);
865 }
866
867 wxString wxOSXWebKitCtrl::GetCurrentURL()
868 {
869     return wxStringWithNSString([m_webView mainFrameURL]);
870 }
871
872 wxString wxOSXWebKitCtrl::GetCurrentTitle()
873 {
874     return GetPageTitle();
875 }
876
877 float wxOSXWebKitCtrl::GetWebkitZoom()
878 {
879     return [m_webView textSizeMultiplier];
880 }
881
882 void wxOSXWebKitCtrl::SetWebkitZoom(float zoom)
883 {
884     [m_webView setTextSizeMultiplier:zoom];
885 }
886
887 wxWebViewZoom wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 //------------------------------------------------------------
960 // Listener interfaces
961 //------------------------------------------------------------
962
963 // NB: I'm still tracking this down, but it appears the Cocoa window
964 // still has these events fired on it while the Carbon control is being
965 // destroyed. Therefore, we must be careful to check both the existence
966 // of the Carbon control and the event handler before firing events.
967
968 @implementation MyFrameLoadMonitor
969
970 - initWithWxWindow: (wxOSXWebKitCtrl*)inWindow
971 {
972     [super init];
973     webKitWindow = inWindow;    // non retained
974     return self;
975 }
976
977 - (void)webView:(WebView *)sender
978     didStartProvisionalLoadForFrame:(WebFrame *)frame
979 {
980         wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
981     wx_webviewctrls[sender]->m_busy = true;
982 }
983
984 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
985 {
986         wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
987     wx_webviewctrls[sender]->m_busy = true;
988
989     if (webKitWindow && frame == [sender mainFrame]){
990         NSString *url = [[[[frame dataSource] request] URL] absoluteString];
991         wxString target = wxStringWithNSString([frame name]);
992         wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
993                                        wx_webviewctrls[sender]->GetId(),
994                                        wxStringWithNSString( url ),
995                                        target, false);
996
997         if (webKitWindow && webKitWindow->GetEventHandler())
998             webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
999     }
1000 }
1001
1002 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1003 {
1004         wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1005     wx_webviewctrls[sender]->m_busy = false;
1006
1007     if (webKitWindow && frame == [sender mainFrame]){
1008         NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1009
1010         wxString target = wxStringWithNSString([frame name]);
1011         wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1012                                        wx_webviewctrls[sender]->GetId(),
1013                                        wxStringWithNSString( url ),
1014                                        target, false);
1015
1016         if (webKitWindow && webKitWindow->GetEventHandler())
1017             webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1018     }
1019 }
1020
1021 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1022 {
1023     *out = wxWEB_NAV_ERR_OTHER;
1024
1025     if ([[error domain] isEqualToString:NSURLErrorDomain])
1026     {
1027         switch ([error code])
1028         {
1029             case NSURLErrorCannotFindHost:
1030             case NSURLErrorFileDoesNotExist:
1031             case NSURLErrorRedirectToNonExistentLocation:
1032                 *out = wxWEB_NAV_ERR_NOT_FOUND;
1033                 break;
1034
1035             case NSURLErrorResourceUnavailable:
1036             case NSURLErrorHTTPTooManyRedirects:
1037             case NSURLErrorDataLengthExceedsMaximum:
1038             case NSURLErrorBadURL:
1039             case NSURLErrorFileIsDirectory:
1040                 *out = wxWEB_NAV_ERR_REQUEST;
1041                 break;
1042
1043             case NSURLErrorTimedOut:
1044             case NSURLErrorDNSLookupFailed:
1045             case NSURLErrorNetworkConnectionLost:
1046             case NSURLErrorCannotConnectToHost:
1047             case NSURLErrorNotConnectedToInternet:
1048             //case NSURLErrorInternationalRoamingOff:
1049             //case NSURLErrorCallIsActive:
1050             //case NSURLErrorDataNotAllowed:
1051                 *out = wxWEB_NAV_ERR_CONNECTION;
1052                 break;
1053
1054             case NSURLErrorCancelled:
1055             case NSURLErrorUserCancelledAuthentication:
1056                 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1057                 break;
1058
1059             case NSURLErrorCannotDecodeRawData:
1060             case NSURLErrorCannotDecodeContentData:
1061             case NSURLErrorBadServerResponse:
1062             case NSURLErrorCannotParseResponse:
1063                 *out = wxWEB_NAV_ERR_REQUEST;
1064                 break;
1065
1066             case NSURLErrorUserAuthenticationRequired:
1067             case NSURLErrorSecureConnectionFailed:
1068             case NSURLErrorClientCertificateRequired:
1069                 *out = wxWEB_NAV_ERR_AUTH;
1070                 break;
1071
1072             case NSURLErrorNoPermissionsToReadFile:
1073                                 *out = wxWEB_NAV_ERR_SECURITY;
1074                 break;
1075
1076             case NSURLErrorServerCertificateHasBadDate:
1077             case NSURLErrorServerCertificateUntrusted:
1078             case NSURLErrorServerCertificateHasUnknownRoot:
1079             case NSURLErrorServerCertificateNotYetValid:
1080             case NSURLErrorClientCertificateRejected:
1081                 *out = wxWEB_NAV_ERR_CERTIFICATE;
1082                 break;
1083         }
1084     }
1085
1086     wxString message = wxStringWithNSString([error localizedDescription]);
1087     NSString* detail = [error localizedFailureReason];
1088     if (detail != NULL)
1089     {
1090         message = message + " (" + wxStringWithNSString(detail) + ")";
1091     }
1092     return message;
1093 }
1094
1095 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1096         forFrame:(WebFrame *)frame
1097 {
1098         wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1099     wx_webviewctrls[sender]->m_busy = false;
1100
1101     if (webKitWindow && frame == [sender mainFrame]){
1102         NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1103
1104         wxWebNavigationError type;
1105         wxString description = nsErrorToWxHtmlError(error, &type);
1106                 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1107                                                wx_webviewctrls[sender]->GetId(),
1108                                        wxStringWithNSString( url ),
1109                                        wxEmptyString, false);
1110                 thisEvent.SetString(description);
1111                 thisEvent.SetInt(type);
1112
1113                 if (webKitWindow && webKitWindow->GetEventHandler())
1114                 {
1115                         webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1116                 }
1117     }
1118 }
1119
1120 - (void)webView:(WebView *)sender
1121         didFailProvisionalLoadWithError:(NSError*)error
1122                                forFrame:(WebFrame *)frame
1123 {
1124         wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1125     wx_webviewctrls[sender]->m_busy = false;
1126
1127     if (webKitWindow && frame == [sender mainFrame]){
1128         NSString *url = [[[[frame provisionalDataSource] request] URL]
1129                             absoluteString];
1130
1131                 wxWebNavigationError type;
1132         wxString description = nsErrorToWxHtmlError(error, &type);
1133                 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1134                                                wx_webviewctrls[sender]->GetId(),
1135                                        wxStringWithNSString( url ),
1136                                        wxEmptyString, false);
1137                 thisEvent.SetString(description);
1138                 thisEvent.SetInt(type);
1139
1140                 if (webKitWindow && webKitWindow->GetEventHandler())
1141                         webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1142     }
1143 }
1144
1145 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1146                                          forFrame:(WebFrame *)frame
1147 {
1148     if (webKitWindow && frame == [sender mainFrame])
1149     {
1150         webKitWindow->SetPageTitle(wxStringWithNSString( title ));
1151     }
1152 }
1153 @end
1154
1155 @implementation MyPolicyDelegate
1156
1157 - initWithWxWindow: (wxOSXWebKitCtrl*)inWindow
1158 {
1159     [super init];
1160     webKitWindow = inWindow;    // non retained
1161     return self;
1162 }
1163
1164 - (void)webView:(WebView *)sender
1165         decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1166                                 request:(NSURLRequest *)request
1167                                   frame:(WebFrame *)frame
1168                        decisionListener:(id<WebPolicyDecisionListener>)listener
1169 {
1170     //wxUnusedVar(sender);
1171     wxUnusedVar(frame);
1172
1173     wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1174     wx_webviewctrls[sender]->m_busy = true;
1175     NSString *url = [[request URL] absoluteString];
1176     wxString target = wxStringWithNSString([frame name]);
1177     wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1178                                    wx_webviewctrls[sender]->GetId(),
1179                                    wxStringWithNSString( url ), target, true);
1180
1181     if (webKitWindow && webKitWindow->GetEventHandler())
1182         webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1183
1184     if (thisEvent.IsVetoed())
1185     {
1186         wx_webviewctrls[sender]->m_busy = false;
1187         [listener ignore];
1188     }
1189     else
1190     {
1191         [listener use];
1192     }
1193 }
1194
1195 - (void)webView:(WebView *)sender 
1196       decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1197                              request:(NSURLRequest *)request
1198                         newFrameName:(NSString *)frameName
1199                     decisionListener:(id < WebPolicyDecisionListener >)listener
1200 {
1201     wxUnusedVar(sender);
1202     wxUnusedVar(actionInformation);
1203
1204     [listener ignore];
1205 }
1206 @end
1207
1208 #endif //wxHAVE_WEB_BACKEND_OSX_WEBKIT