Lazarus

Programming => Widgetset => Cocoa => Topic started by: MISV on July 24, 2018, 03:23:05 pm

Title: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on July 24, 2018, 03:23:05 pm
To get a better grib about how Cocoa works with LCL I decided I would like to show WebView in a control. I am aware Phil made something which I also used as a starting point. However - it seems when using widgetset compatible code things are a little different - or I am messing up badly. Either way, good learning experience.



So I have this

Code: Pascal  [Select][+][-]
  1. TmyWebBrowserCocoa = class(TWinControl)
  2. protected
  3. public
  4.   constructor Create(AOwner: TComponent);
  5.   destructor Destroy; override;
  6.   procedure Init_WebView;
  7.   procedure Navigate(const AURL: string):
  8. end;
  9.  
  10. TmyWebBrowserCocoaDelegate = objcclass(NSObject)
  11. public
  12.   // implement those we need
  13. end;
  14.  
  15. constructor TmyWebBrowserCocoa.Create(AOwner: TComponent);
  16. begin
  17.   inherited Create(AOwner);
  18. end;
  19.  
  20. procedure TmyWebBrowserCocoa.Init_WebView;
  21. var
  22.   TmpWebView: WebView;
  23.   TmpDelegate: TmyWebBrowserCocoaDelegate;
  24.   TmpParams: TCreateParams;
  25. begin
  26.   TmpParams.WndParent := Self.Handle;
  27.   TmpParams.X := 0;
  28.   TmpParams.Y := 0;
  29.   TmpParams.Width := Self.ClientWidth;
  30.   TmpParams.Width := Self.ClientHeight;
  31.   TmpWebView := WebView(NSView(WebView.alloc).lclInitWithCreateParams(TmpParams));
  32.   TmpDelegate := TmyWebBrowserCocoaDelegate.alloc.init;
  33.   TmpWebView.setFrameLoadDelegate(TmpDelegate);
  34. end;
  35.  
  36. destructor TmyWebBrowserCocoa.Destroy;
  37. begin
  38.   WebView(Self.Handle).frameLoadDelegate.release;
  39.   NSObject(Self.Handle).release;
  40.   inherited Destroy;
  41. end;
  42.  
  43. procedure TmyWebBrowserCocoa.Navigate(const AURL: string);
  44. var
  45.   ANSURL : NSURL;
  46.   ANSReq : NSURLRequest;
  47. begin
  48.   // to keep simple we are testing using https://example.com to avoid any charset and encoding problems
  49.   ANSURL := NSURL.URLWithString(NSSTR(PAnsiChar(AURL)));
  50.   ANSReq := NSURLRequest.RequestWithURL(ANSURL);
  51.   WebView(Self.Handle).mainFrame.loadRequest(ANSReq); // SIGABRT here
  52. end;
  53.  

Created and called like this

Code: Pascal  [Select][+][-]
  1. var
  2.   WebBrowser: TmyWebBrowserCocoa
  3. begin
  4.   FWebBrowser := TmyWebBrowserCocoa.Create(FBrowserHostParent);
  5.   FWebBrowser.Parent :=FBrowserHostParent;
  6.   FWebBrowser.Visible := False;
  7.   FWebBrowser.Align := alClient;
  8.   FWebBrowser.Init_WebView;
  9.   FWebBrowser.Visible := True;
  10.   FWebBrowser.Navigate('https://example.com/');
  11. end;



However, I am getting SIGABRT inside navigate... probably a handle issue
Title: Re: Minimum code for implementing WebView
Post by: Phil on July 24, 2018, 03:33:49 pm
To get a better grib about how Cocoa works with LCL I decided I would like to show WebView in a control. I am aware Phil made something which I also used as a starting point. However - it seems when using widgetset compatible code things are a little different - or I am messing up badly. Either way, good learning experience.

TWebBrowser is "widgetset compatible code".

https://macpgmr.github.io

What are you trying to do that isn't already covered in TWebBrowser?
Title: Re: Minimum code for implementing WebView
Post by: MISV on July 24, 2018, 03:45:31 pm
To get a better grib about how Cocoa works with LCL I decided I would like to show WebView in a control. I am aware Phil made something which I also used as a starting point. However - it seems when using widgetset compatible code things are a little different - or I am messing up badly. Either way, good learning experience.

TWebBrowser is "widgetset compatible code".

https://macpgmr.github.io

What are you trying to do that isn't already covered in TWebBrowser?

I explicit noted in my post your code was "widgetset compatible code" unlike mine :)

I am merely trying to learn where I have made an error in making a non-widgetset-compatible webview in cocoa.
Title: Re: Minimum code for implementing WebView
Post by: MISV on July 24, 2018, 11:50:30 pm
Okay - I got it working.

Essentially not using the handle stuff but instead keep references (e.g. FWebView) and use them helped + some fixes along the way.
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on July 26, 2018, 12:30:35 pm
Quick note: You can resize your webview when the parent-wincontrol resize using setFrameOrigin + setFrameSize

One problem though...

Seems WebKit has been deprecated for a while in favour WKWebView, so WebKit support may be ending in a later macOS version...
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: Phil on July 26, 2018, 02:04:32 pm
Quick note: You can resize your webview when the parent-wincontrol resize using setFrameOrigin + setFrameSize

One problem though...

Seems WebKit has been deprecated for a while in favour WKWebView, so WebKit support may be ending in a later macOS version...

The WebView class has been deprecated in favor of the WKWebView class. The WebKit framework has not been deprecated.

https://developer.apple.com/documentation/webkit/wkwebview

FPC's ancient WebKit unit does not include the newer WKWebView class, but the MacOS_10_10 parsed headers here does:

https://github.com/genericptr

Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: wittbo on June 05, 2021, 01:38:52 pm
i find your approach very interesting to understand what is really happening and what has to be done for it. i tried to reproduce your example (see attachment). i have a form with 2 buttons. Click on the left button should create and initialize the WebView, click on the second button should load a web page into the WebView.

The program compiles without errors. But at runtime nothing happens, neither after click on the first button nor after click on the second button, no error message, no crash, nothing.

I think it must have something to do with the handle of the parent view. Using XCode and ObjectiveC/Swift, I have to define the WebView as a subview in the parent view (....addSubview()). How does this happen in Pascal? Do you have any idea?

-wittbo-
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: wittbo on June 07, 2021, 12:44:49 pm
Some additional information:

... last line creation code:
...
myWebBrowserCocoa.Visible := True;
System is hanging.

- commenting this line and executing the loading code:
...
WebView(Self.Handle).mainFrame.loadRequest(ANSReq)
System crashes.

So, MISV, can you remember, what were the necessary tricks to get it working?
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: wittbo on June 07, 2021, 08:28:42 pm
Done!   Here is the full working demo program.  8-)

Based on the TWebBrowser component package of Phil (s.a.); really minimum code, no delegate code, only the essential code for creating the webview and loading an example https page into it.

And - in contrast to the statement of MISV above - you will really need the Handle stuff. And the most important statement is this mystic RegisterWSComponent, which -for me- does a mapping of the Cocoa specific WSWincontrol class into the general WinControl class of the webbrowser component. But I have only a poor idea of what RegisterWSComponent really does.

Without that I could not get this to work, especially the code fragments of MISV (s.a.) didn't really work.

My next steps will be:
- delete the webview component under program control
- convert the code to use the new WKWebView
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: trev on June 08, 2021, 02:55:58 am
Thanks for sharing wittbo!
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: wittbo on June 08, 2021, 06:43:32 pm
Finished work. Try the demo.
Implemented close of the webview
Implemented the newer WKWebView.

The latter wasn't a real problem, since the cocoaint webkit unit now includes the wkwebview.inc include. For creating and closing no change. Loading of a page is a little bit easier, there is no mainframe necessary. WKWebView has some new magnification methods to read and set the magnification of the page.

The demo program contains both WebView and WKWebView methods; you can choose between them by setting the compiler defines at line 15/16.

I will use the WKWebView to integrate a PDF Viewer into my app and it's really quite easy, you only need the URL-variant of the PDF file.

If anyone knows something similar for MS Windows (10 or newer), I would be interested as well.

BTW: Something seems to be wrong with line 16 of .../wkwebview.inc:
{$if defined(TARGET_OS_IPHONE)defined(interface)defined(WKWebView)defined(UIView)}
When loading this file into the Lazarus ide, you get an error at line 16: "Error: operator missing". Since I could compile and run my program anyway, I did not pursue the message further.
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on June 11, 2021, 09:12:20 am
Just for completeness here is my original code:


I have a TWinControl hosting the browser contorl


So when parent control resizes I do

Code: Pascal  [Select][+][-]
  1.   if FWebView_Cocoa <> nil then
  2.     begin
  3.       TmpPoint.x := Self.Left;
  4.       TmpPoint.y := Self.Top;
  5.       FWebView_Cocoa.setFrameOrigin(TmpPoint);
  6.       TmpSize.width := Self.ClientWidth;
  7.       TmpSize.height := Self.ClientHeight;
  8.       FWebView_Cocoa.setFrameSize(TmpSize);
  9.  

To initialize I do:

Code: Pascal  [Select][+][-]
  1.   if FWebView_Cocoa = nil then
  2.     begin
  3. //(*
  4.       TmpParams.WndParent := Self.Handle;
  5.       TmpParams.X := 0;
  6.       TmpParams.Y := 0;
  7.       TmpParams.Width := Self.ClientWidth;
  8.       TmpParams.Height := Self.ClientHeight;
  9.       TmpParams.Style := WS_VISIBLE;
  10.       FWebView_Cocoa := WebView( NSView(WebView.alloc).lclInitWithCreateParams(TmpParams) );
  11.  
  12.  
  13.       FDelegate_Cocoa_Frame := Tmsdv_cocoanative_WebBrowserCocoaDelegate_Frame.alloc.init;
  14.       FDelegate_Cocoa_Frame.FBrowserCtrlRef := Self;
  15.       FWebView_Cocoa.setFrameLoadDelegate(FDelegate_Cocoa_Frame);
  16.  


Then I have this:

Code: Pascal  [Select][+][-]
  1.   Tmsdv_cocoanative_WebBrowserCocoaDelegate_Frame = objcclass(NSObject)
  2.   private
  3.     FBrowserCtrlRef: TmsdvWebBrowserCocoa;
  4.   public
  5.   public
  6.     procedure webView_didFinishLoadForFrame(sender: WebView; frame: WebFrame); override;
  7.     procedure webView_didStartProvisionalLoadForFrame(sender: WebView; frame: WebFrame); override;
  8.     procedure webView_didFailProvisionalLoadWithError_forFrame(sender: WebView; error: NSError; frame: WebFrame); override;
  9.     procedure webView_decidePolicyForNewWindowAction_request_newFrameName_decisionListener(webView_: WebView; actionInformation: NSDictionary; request: NSURLRequest; frameName: NSString; listener: WebPolicyDecisionListenerProtocol); override;
  10.   end;
  11.  


Hope this helps


(Great work if wkwebview can be implemented now! I wonder if one needs ti support both for newer/older Mac OS and how to select between them)

Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: trev on June 11, 2021, 09:19:57 am
* WKWebView requires macOS 10.10+
* WebView is available in macOS 10.3–10.14

As for selecting between them, something like this:

Code: Pascal  [Select][+][-]
  1. procedure TForm1.Button1Click(Sender: TObject);
  2. var
  3.   aSEL : SEL;
  4. begin
  5.     // Check whether OS version responds to this selector
  6.     aSEL := objcselector('operatingSystemVersion');
  7.     if NSProcessInfo.processInfo.respondsToSelector(aSEL) then
  8.       ProcessInfo // procedure
  9.     // Otherwise fallback to the deprecated Gestalt Manager
  10.     else
  11.       GestaltInfo; // procedure
  12. end;
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: wittbo on July 31, 2021, 11:32:18 am
I have done some experiments with WKWebView in the meantime. The minimal use of the methods to open a WKWebView and load a web page are even a bit easier than with the WebView. However, I am not getting anywhere with the implementation of the delegate methods to check the loading process. With WebView you simply had to create an objcclass(NSObject) for the desired delegate methods and pass it to the Webview with setFrameLoadDelegate. This doesn't work with WKWebView now (or I didn't understand it). Here I need a WKNavigationDelegate protocol object. And that's where my options end, as I don't know how to implement this. Maybe someone has an idea?
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on August 17, 2021, 11:18:08 am
I will try return to this as well... I have begun initial work. I just have so little time, but it at top of priority for my software (however, personal matters in my life is taking higher priority than my software so this is no promise... but I will try see if I can somewhere. I have a ton of things I need to get working before I can replace the old webview)
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: ChrisR on September 04, 2021, 07:22:32 pm
Related to this, it looks like Ryan Joseph (aka genericptr) just ported MacOS 11 headers:

 https://github.com/genericptr/MacOS_11_0
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: Zoë on November 10, 2021, 10:30:56 pm
The attached file is a TWebBrowser-like control that uses WKWebView, including the delegate protocol, which we're using in Beyond Compare 4.  Any of you are welcome to use it however you want;  I updated the header to mention the LCL's modified LGPL in case it's used for a patch, but it can be whatever.

In case it's still relevant, I ran into two issues when originally writing, which are in Gitlab as #37441 and #35995
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on December 07, 2021, 01:36:07 am
By the way everyone....

"Why is WK_API_ENABLED not on by default?"

Inspecting WebKit.pas > Sources.inc > WKNavigationDelegate.inc it depends on the define being set...

But why is it not set? I suppose I can set the define in some compiler option, but just seems very odd to me.

Am I doing it wrong? :)

Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on December 08, 2021, 02:03:31 am
Example:


So first I had

Code: Pascal  [Select][+][-]
  1.   Tmsdv_cocoanative_WebBrowserCocoaWKWebViewDelegate_Navigation = objcclass(NSObject)
  2.   private
  3.     FBrowserCtrlRef: TmsdvWebBrowserCocoaWKWebView;
  4.   public
  5.     // need implement
  6.   end;
  7.  
  8.       FDelegate_Cocoa_Navigation := Tmsdv_cocoanative_WebBrowserCocoaWKWebViewDelegate_Navigation.alloc.init;
  9.       FDelegate_Cocoa_Navigation.FBrowserCtrlRef := Self;
  10.       FWebView_CocoaWKWebView.setNavigationDelegate(FDelegate_Cocoa_Navigation);
  11.  
  12.  

This gives error

Quote
Error: Incompatible type for arg no. 1: Got "Tmsdv_cocoanative_WebBrowserCocoaWKWebViewDelegate_Navigation", expected "WKNavigationDelegateProtocol"

Now this seems like a great error and easy fix

Code: Pascal  [Select][+][-]
  1.   Tmsdv_cocoanative_WebBrowserCocoaWKWebViewDelegate_Navigation = objcclass(NSObject, WKNavigationDelegateProtocol)
  2.   private
  3.     FBrowserCtrlRef: TmsdvWebBrowserCocoaWKWebView;
  4.   public
  5.     // need implement
  6.   end;
  7.  

But this will throw another error

Quote
Error: Identifier not found "WKNavigationDelegateProtocol"

.... Now I have added all units I could think of, but it won't help and the reason seems to be:

fpcsrc/packages/cocoaint/src/webkit/WebKit.pas
includes
fpcsrc/packages/cocoaint/src/webkit/src/Sources.inc
includes
fpcsrc/packages/cocoaint/src/webkit/src/webkit/WKNavigationDelegate.inc

But in this unit the WKNavigationDelegateProtocol does not get compiled in because these are not defined "WK_API_ENABLED, PROTOCOLS"


I am trying to understand how Lazarus one place can recognize the type, but then not recognize the type if I use it. Anyhow, I tried a "hack" defining the beforementioned defines them and then *including* the *WKNavigationDelegate.inc* file myself, but, well I did not get it working.


Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: Zoë on December 08, 2021, 04:29:50 am
See the patches in the bug reports I mentioned:

https://gitlab.com/freepascal.org/fpc/source/-/issues/37441

https://gitlab.com/freepascal.org/fpc/source/-/issues/35995

Still haven't heard why that hasn't been corrected, but the macOS 11 headers on GitHub are correct so if/when that gets merged it should be fixed.
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on December 08, 2021, 11:54:42 pm
Thank you for explanation and links. I missed them reading the first round. Hmmm... Let us hope it gets merged in soon albeit I can see some time passed since you submitted patches so... Crossing fingers :)


Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: trev on December 09, 2021, 12:36:31 am
No need to wait; patch your copy of FPC and recompile it. Just make a note so that you can remember to redo it if you upgrade or change versions <voice of experience>.
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on December 13, 2021, 12:05:06 pm
Okay, applying the patch no problem.

But wondering what the best way is to recompile fpc source that will not kill me.

1)
I tried "Clean all and build" but that did not work since it does not include FPC.

2)
In terminal I navigated to
/Users/%name%/%folder%/LazarusCocoa64/Lazarus
and then tried
./lazbuild --build-all --recursive "/Volumes/DiskW/%folder%/MyAppProjectOSX.lpi" (this project uses a ton of units directly or indirectly including WKWebView)

However it ends up
Error: (Lazarus) [TLazPackageGraph.CompileRequiredPackages] "Exit code 1"

...

What is the best way to force recompiliation of the fpcsrc units? :)





Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: avra on December 13, 2021, 02:32:50 pm
But wondering what the best way is to recompile fpc source that will not kill me.
Might not be the best but it works: https://wiki.freepascal.org/FPC_recompilation_automation
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on December 14, 2021, 12:21:21 am
Thank you, I will check it out :)  (Albeit it states it is for Windows, but can probably use most of it)

Two more questions:
- Is there no way to trigger Lazarus to recompile a "system" FPCSrc unit in an easier manner? Like except the .pas file?
- Could I possibly copy fixed units into my project directory as an alternative?
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: trev on December 14, 2021, 03:47:55 am
What is the best way to force recompiliation of the fpcsrc units? :)

Code: Bash  [Select][+][-]
  1.  []$ cd <wherever you have the fpc src>
  2.  []$ make clean all FPC=/usr/local/lib/fpc/3.2.2/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64 OPT="-XR/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/"
  3.  []$ sudo make install FPC=$PWD/compiler/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on December 14, 2021, 10:10:30 am
Thank you :)

I ended up using (since I used FPCDeluxe for installing)

1)
Navigated to
Code: Pascal  [Select][+][-]
  1. /Users/%name%/LazarusCocoa64/fpcsrc/
  2.  

2)
Code: Pascal  [Select][+][-]
  1. make clean all FPC=/Users/%name%/LazarusCocoa64/fpc/lib/fpc/3.3.1 OS_TARGET=darwin CPU_TARGET=x86_64 OPT="-XR/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/"

Got quite a few permission errors like
Quote
/Users/%name%/LazarusCocoa64/fpc/lib/fpc/3.3.1: Permission denied
(but process seemed to run OK for most part)

3)
Code: Pascal  [Select][+][-]
  1. sudo make install FPC=$PWD/compiler/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64

which resulted in error:
Quote
Makefile:135: *** Compiler /Users/%name%/LazarusCocoa64/fpcsrc/compiler/ppcx64 not found.  Stop.

I decided to instead try
Code: Pascal  [Select][+][-]
  1. sudo make install FPC=$PWD/../fpc/lib/fpc/3.3.1/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64

This appears to work...


Will report back later and update post if things worked out :)
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on December 14, 2021, 11:30:52 am
It seemed to compile correctly but...

I guess not because I still get the error that it does not recognize WKNavigationDelegateProtocol etc.

I have tried to do a "Cleanup and build" just to make sure it is not inside LCL that had not updated somehow to the new fpcsrc compilation.

Oh well...
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on December 14, 2021, 11:12:14 pm
In fpcsrc directory doing

ls -l

and all  files are either

-rw-r--r-- (seems to be all writeable files)
or
drwxr-xr-x (folders)

and I stand as user/owner %name% staff


I do not know...

I was starting to experiment with
sudo chmod -R ./ ...? (sorry did not get it working since day-to-day Windows user here)




I have also tried to introduce a bug into a compiletime bug into webkit ... and that did trigger error.
I have also tried to introduce a bug into a compiletime bug into wknavigationdelegate.inc  both to ensure protocol and wk_api_enabled defines are working... And yes, they are defined properly because inserting random text inside them triggered error



So what is next. Why the **** does it not work when compiling my code inside Lazarus?

Maybe related to permission errors? i.e. no new compiled files are actually generated? I will try research more... ... Open to ideas
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: trev on December 15, 2021, 12:58:11 am
I would guess that permission errors while recompiling are fatal. I have no idea why you would be getting permission errors if the source is in your home directory - maybe an FPCUpDeluxe issue.

In order of preference, you have a choice to make:

1) Find the files causing permission errors and correct the permissions and/or ownership with chmod and/or chown as necessary;
2) Run the compile command with sudo.
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on December 15, 2021, 09:42:47 am
One thing I noticed and tried...

I just tried to rename
/Users/%name%/LazarusCocoa64/fpcsrc/packages/cocoaint/units/x86_64-darwin
(got prompted which is kinda odd since I am logged in as %name%)

then create new empty folder called
/Users/%name%/LazarusCocoa64/fpcsrc/packages/cocoaint/units/x86_64-darwin
(got prompted which is kinda odd since I am logged in as %name%)

.......

New files got generated with the *make* command and I thought success...

.......

Inside Lazarus I can now navigate to  *WKNavigationDelegateProtocol* declaration (CTRL + mouse click on the identifier in my own source) and I am taken to WKNavigationDelegate.inc (this did not work before)

But I still get compiler error "Identifier not found "WKNavigationDelegateProtocol"  %)

I have tried in Lazarus "Clean and Build all"

Open to ideas... I feel a bit puzzled right now as how this combination can happen....
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: trev on December 15, 2021, 10:22:34 am
You have permission and/or ownership issues with your source files which I suspect is due to the way you installed FPC. You need to solve them.
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on December 15, 2021, 11:20:04 am
As mentioned, I successfully edited fprsrc source files. I successfully the relevant fpcsrc recompiled them (by manually deleting the old compiled files first)

So as such it would seem I solved those parts. (Or do you disagree? I would have considered this part fully solved otherwise)

At least I have freshly edited fpcsrc source files (where Lazarus editor can navigate around and fine declarations) and freshly compiled fprsrc files (since I had deleted them before the make/install)

...

So I *think* the permission issue got fully solved by that.

Why it is still not working is beyond me.

just thought I could scratch off "permission" issue :)
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: trev on December 15, 2021, 11:56:28 am
If there are no more permission errors emitted when you recompile, then yes, that is solved. Sorry, it wasn't clear to me from your post that those issues had been resolved.
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on December 16, 2021, 11:38:07 am
Quick note: I believe I solved them specifically for the WKWebView related files by deleting the compiled files. (i.e. by deleting the old compiled files and running new make/install, I saw new compiled files being ... compiled/made ... hence I know they got successfully recompiled. I hope that makes sense. If my logic is wrong and I am missing something with the behavior of make please let me know.)

Anyway, still won't won't in Lazarus so success is minimal at best. Anyhow, I kinda expected to run into all sorts of trouble. I always do on my Mac :D
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on December 18, 2021, 01:19:08 am
Anyway going further in experiment. Maybe helpful for other using FPCDeluxe needing to recompile FPC source:


1)
In finder I select "Get info" for "packages folder" and I see "staff" user does not have read + write ... 

I decide to fix this for the entire "LazarusCocoa64" directory because it is a problem *ALLOVER* that "staff" is write protected

And I recall from earlier ls -l that "staff" was mentioned (I am not into Mac intrincsic)

I do this like
https://support.apple.com/guide/mac-help/change-permissions-for-files-folders-or-disks-mchlp1203/mac
"Apply permissions to all items in a folder or a disk"


2)
I go into
/Users/%name%/LazarusCocoa64/fpcsrc/packages/cocoaint/units/x86_64-darwin
and make sure all is deleted so *new* files can be generated

3)
make clean all FPC=/Users/%name%/LazarusCocoa64/fpc/lib/fpc/3.3.1 OS_TARGET=darwin CPU_TARGET=x86_64 OPT="-XR/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/"
(now gives drastically fewer permission errors, but they are not all solved oddly. But the errors not related to the files in "cocoaint")

4)
we check and this folder is empty
/Users/%name%/LazarusCocoa64/fpcsrc/packages/cocoaint/units/x86_64-darwin


5)
For testing everything is getting compiled correctly inside *ifdef*, we introduce *temporary* compile time bugs in:
/Users/%name%/LazarusCocoa64/fpcsrc/packages/cocoaint/src/webkit/WKNavigationDelegate.pas
followed by running
sudo make install FPC=$PWD/compiler/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64
so we are 100% sure everything gets compiled correctly.


6)
When ready having tested evertyhing above carefully we run final:
sudo make install FPC=$PWD/compiler/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64

7)
we check and see new files have been successfully created in
/Users/%name%/LazarusCocoa64/fpcsrc/packages/cocoaint/units/x86_64-darwin


Thus we can completely entirely positively state new compiled units have been created

...

That Lazarus somehow still broken / out of sync I do not understand how can be.

Inside Lazarus I can now navigate to  *WKNavigationDelegateProtocol* declaration (CTRL + mouse click on the identifier in my own source) and I am taken to WKNavigationDelegate.inc

But I still get compiler error "Identifier not found "WKNavigationDelegateProtocol" 

I have tried in Lazarus "Clean and Build all" + manually delete "Lib" folders anywhere related to my own code.



Conclusion sofar: Lazarus broken deep within.
Probability of being correct 10%

Please if anyone has ideas let me know.


Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: trev on December 23, 2021, 12:43:52 pm
If you attach what you're trying to compile, I'll give it a whirl with a patched FPC. Let me know which FPC version you would like me to use.

(Note: My attempt may be delayed by Christmas festivities,  my tomorrow being Christmas Eve.)
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 07, 2022, 01:45:17 am
@trev @Zoë

I can see you both redeclare some delegate methods (Zoë in her code and Trev elsewhere) that use OpaqueCBlock

e.g.

webView_decidePolicyForNavigationAction_decisionHandler

Do I need to rewrite/fix WKNavigationProtocol to replace:

Code: Pascal  [Select][+][-]
  1. procedure webView_decidePolicyForNavigationAction_decisionHandler(webView: WKWebView; navigationAction: WKNavigationAction; decisionHandler: OpaqueCBlock); message 'webview:decidePolicyForNavigationAction:decisionHandler:')
  2.  

with this

Code: Pascal  [Select][+][-]
  1. procedure webView_decidePolicyForNavigationAction_decisionHandler(webView: WKWebView; navigationAction: WKNavigationAction; decisionHandler: WKNavigationDelegateProtocol_actionPolicy_decisionHandler); message 'webview:decidePolicyForNavigationAction:decisionHandler:')
  2.  


I think Trev does this. (In other thread where he helps med with CBLOCK documentation) https://forum.lazarus.freepascal.org/index.php/topic,57724.0.html

But in Zoe code the delegate implementor simply defines the implemention like this

Code: Pascal  [Select][+][-]
  1. procedure webView_decidePolicyForNaviagtaionAction_decisionHandler(webView: WKWebView; navigationAction: WKNavigationAction; decisionHandler: WKNavigationDelegateProtocol_actionPolicy_decisionHandler);



Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 07, 2022, 02:26:41 am
Another problem Zoe probably fixed in FPC source is WKNavigationDelegateProtocol_actionPolicy_decisionHandler is not defined anywhere I can find. Hmmm.

I guess * OpaqueCBlock* is and can somehow be used as a filler when something is not yet implemented in FPC
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: trev on January 07, 2022, 06:10:43 am
You can see my OpaqueCBlock approach in this Wiki example (https://wiki.freepascal.org/macOS_NSAlert#Modal_error_sheet_with_three_buttons) which at first glance seems different to Zoe's approach.
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: Zoë on January 07, 2022, 11:30:51 am
Ah yeah, I must have either missed that or fixed it after I submitted the patch.  Here's the relevant lines from WKNavigationDelegate.inc:

Code: Pascal  [Select][+][-]
  1. type
  2.   WKNavigationDelegateProtocol_actionPolicy_decisionHandler =
  3.     reference to procedure(policy: WKNavigationActionPolicy); cdecl; cblock;
  4.  
  5. type
  6.   WKNavigationDelegateProtocol = objcprotocol external name 'WKNavigationDelegate' (NSObjectProtocol)
  7.   optional
  8.     procedure webView_decidePolicyForNavigationAction_decisionHandler (webView: WKWebView; navigationAction: WKNavigationAction; decisionHandler: WKNavigationDelegateProtocol_actionPolicy_decisionHandler); message 'webView:decidePolicyForNavigationAction:decisionHandler:';
  9.     procedure webView_decidePolicyForNavigationResponse_decisionHandler (webView: WKWebView; navigationResponse: WKNavigationResponse; decisionHandler: OpaqueCBlock); message 'webView:decidePolicyForNavigationResponse:decisionHandler:';
  10.     procedure webView_didStartProvisionalNavigation (webView: WKWebView; navigation: WKNavigation); message 'webView:didStartProvisionalNavigation:';
  11.     procedure webView_didReceiveServerRedirectForProvisionalNavigation (webView: WKWebView; navigation: WKNavigation); message 'webView:didReceiveServerRedirectForProvisionalNavigation:';
  12.     procedure webView_didFailProvisionalNavigation_withError (webView: WKWebView; navigation: WKNavigation; error: NSError); message 'webView:didFailProvisionalNavigation:withError:';
  13.     procedure webView_didCommitNavigation (webView: WKWebView; navigation: WKNavigation); message 'webView:didCommitNavigation:';
  14.     procedure webView_didFinishNavigation (webView: WKWebView; navigation: WKNavigation); message 'webView:didFinishNavigation:';
  15.     procedure webView_didFailNavigation_withError (webView: WKWebView; navigation: WKNavigation; error: NSError); message 'webView:didFailNavigation:withError:';
  16.     procedure webView_didReceiveAuthenticationChallenge_completionHandler (webView: WKWebView; challenge: NSURLAuthenticationChallenge; completionHandler: OpaqueCBlock); message 'webView:didReceiveAuthenticationChallenge:completionHandler:';
  17.   end;
  18.  

OpaqueCBlock is the way cblock callbacks were declared in the headers before the compiler supported them, and is basically just a plain pointer.  You can still use them with the existing headers, but you need to declare the callback elsewhere and do casts as appropriate.
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 08, 2022, 10:25:43 am
Thank you Zoë and Trev :)
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 08, 2022, 09:37:38 pm
What is left is:

FWebView_CocoaWKWebView.customUserAgent
is not defined (but I think I can do this myself if neccessary by moving the entire declaration into the unit?)

I need to get
evaluateJavaScript_completionHandler('document.documentElement.outerHTML', ...OpaqueCBlock....)
working so I can retrieve the HTML of the document (probably hardest... anyway to cast this otherwise? Anyway this is by far most important since you can then get content*HTML *after* e.g. AJAX)

I need to get content filter working... Still need to research. But it is not always I want to download images, videos etc. Usuaully I only want HTML/AJAX





Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 09, 2022, 03:42:22 pm
@Zoe


Just to understand you correctly concerning CBlock and casting

So I have this
Code: Pascal  [Select][+][-]
  1. myWKWebView.evaluateJavaScript_completionHandler('document.documentElement.outerHTML', ...OpaqueCBlock....)

In Lazarus WEKWebView.inc defined as
Code: Pascal  [Select][+][-]
  1. procedure evaluateJavaScript_completionHandler(javaScriptString: NSString; completionHandler: OpaqueCBlock)

In Apple help defined as this:
Code: Pascal  [Select][+][-]
  1. func evaluateJavaScript(_ javaScriptString: String, completionHandler: ((Any?, Error?) -> Void)? = nil)

I would need to translate this part completionHandler: ((Any?, Error?) -> Void) to Lazarus.

And my new code would then be (using casting)
Code: Pascal  [Select][+][-]
  1. myWKWebView.evaluateJavaScript_completionHandler('document.documentElement.outerHTML', OpaqueCBlock(PtrFuncToCompletionHandlingMatchingTranslatedDefinition))

And ]myWKWebView.evaluateJavaScript_completionHandler would call into my completetion handly asynchroneously



.... Kinda a shame WKWebview does not yet contain properly translate the calls suing CBlock

And also not synchroneous versions of calls, e.g.
func evaluateJavaScript(_ javaScriptString: String) async throws -> Any

(Since I run WKWebView for AJAX crawling it is already in its own thread)



Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 10, 2022, 11:05:08 am
If anyone has any idea on how to get evaluateJavascript to work (necessary to grab content and many other things) let me know

I am not sure what is easier, implementing the sync or async version. But the async version has at least been defined in WK in Lazarus

Code: Pascal  [Select][+][-]
  1. procedure evaluateJavaScript_completionHandler(javaScriptString: NSString; completionHandler: OpaqueCBlock)
  2.  
  3. func evaluateJavaScript(_ javaScriptString: String, completionHandler: ((Any?, Error?) -> Void)? = nil)
  4.  

So we have this code

Code: Pascal  [Select][+][-]
  1.       FWebBrowser.FWebView_CocoaWKWebView.evaluateJavaScript_completionHandler(
  2.         'document.documentElement.outerHTML',
  3.         nil // need to pass in a completionhandler here that will process output and then through a mechanishm get that returned to our code
  4.       );
  5.  

Now, I am not too much into Apple API but I guess a try at CBlock callback would be

Code: Pascal  [Select][+][-]
  1.   reference to procedure(AAnyPtr: idPtr; AErrorPtr: NSErrorPtr); cdecl; cblock;
  2.  

But that is for sure wrong... :)

Ideally it would be great if the completionHandler code could be closure like... Or a sub procecedure? But I do not think CBlock allows for this?

But then to actually use with the non-fixed FPC source casting would be necessary?

Code: Pascal  [Select][+][-]
  1. evaluateJavaScript_completionHandler('document.documentElement.outerHTML', OpaqueCBlock(PtrFuncToCompletionHandlingMatchingTranslatedDefinition))
  2.  
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: Zoë on January 10, 2022, 07:06:41 pm
https://github.com/genericptr/MacOS_11_0/tree/master/webkit

Ryan updated his parser and posted macOS 11 headers, but they haven't been merged yet.  Looks like they're declaring cblock callbacks now, so you can grab the relevant definitions from there.

Quote
Now, I am not too much into Apple API but I guess a try at CBlock callback would be

That looks correct to me, but definitely double check it with the headers above.

Quote
Ideally it would be great if the completionHandler code could be closure like... Or a sub procecedure? But I do not think CBlock allows for this?

Unfortunately, no, you have to use an object's method.  Hopefully the cblock/closure code can be unified in the future, but the contractor we have working on adding anonymous methods doesn't have a Mac, so it'll have to wait until it's merged and someone else can take a crack at it.

Quote
But then to actually use with the non-fixed FPC source casting would be necessary?

The way I've done it in the past was to assign the method to a local variable that has the correct cblock declaration, and then pass that variable in with an OpaqueCBlock cast.
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 11, 2022, 01:20:52 pm
Hi Zoë

Thank you very much.

Following your link
https://github.com/genericptr/MacOS_11_0/tree/master/webkit

I am now using:
Code: Pascal  [Select][+][-]
  1. type
  2.   WKWebViewEvaluateJavascriptCallback = reference to procedure(param1: id; error: NSError); cblock; cdecl;
  3.  

In my class I defined *methods*:
 
Code: Pascal  [Select][+][-]
  1.  // bla bla bla
  2.   public
  3.     function GetDocumentAsStr: string;
  4.     procedure GetDocumentAsStr_JavascriptCallback(param1: id; error: NSError); cblock; cdecl;
  5.   end;
  6.  


In GetDocumentAsStr I have (simplified):
Code: Pascal  [Select][+][-]
  1. function TmsdvViewerCocoaWKWebView.GetDocumentAsStr: string;
  2. var
  3.   TmpJavaScriptCodeNSStr: NSString;
  4.   TmpFuncCallbackRefVar: WKWebViewEvaluateJavascriptCallback;
  5. begin
  6.       TmpJavaScriptCodeNSStr := msMac_StrToNSStr('document.documentElement.outerHTML');
  7.       TmpFuncCallbackRefVar := @GetDocumentAsStr_JavascriptCallback;
  8.       FWebBrowser.FWebView_CocoaWKWebView.evaluateJavaScript_completionHandler(
  9.         TmpJavaScriptCodeNSStr,
  10.         OpaqueCBlock(TmpFuncCallbackRefVar)
  11.       );
  12.  

However I am getting errors for:
Code: Pascal  [Select][+][-]
  1. procedure TmsdvViewerCocoaWKWebView.GetDocumentAsStr_JavascriptCallback(param1: id; error: NSError); cblock; cdecl;
Code: Pascal  [Select][+][-]
  1. procedure TmsdvViewerCocoaWKWebView.GetDocumentAsStr_JavascriptCallback(param1: id; error: NSError); cdecl;
  2.  
=
Quote
Error: Function header doesn't match the previous declaration "GetDocumentAsStr_JavascriptCallback(id;NSError) is block; CDecl;"

while
Code: Pascal  [Select][+][-]
  1. procedure TmsdvViewerCocoaWKWebView.GetDocumentAsStr_JavascriptCallback(param1: id; error: NSError);
  2.  
=
Quote
Error: Calling convention doesn't match forward

If anyone has any ideas what to try next... Or if I am doing something wrong :)
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: Zoë on January 11, 2022, 09:10:04 pm
Quote
However I am getting errors for:
Code: Pascal  [Select][+][-]
  1. procedure TmsdvViewerCocoaWKWebView.GetDocumentAsStr_JavascriptCallback(param1: id; error: NSError); cblock; cdecl;

Remove the 'cblock' from here.  The cblock is part of the variable/argument declaration, not something you need to flag your own methods with.
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 12, 2022, 12:08:42 am
Hi Zoë

Already tried.

Code: Pascal  [Select][+][-]
  1. procedure TmsdvViewerCocoaWKWebView.GetDocumentAsStr_JavascriptCallback(param1: id; error: NSError); cdecl;

gives error

Quote
Error: Function header doesn't match the previous declaration "GetDocumentAsStr_JavascriptCallback(id;NSError) is block; CDecl;"
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: Zoë on January 12, 2022, 12:40:22 am
You need to remove 'cblock' from everywhere in your code except the variable declaration:

Code: [Select]
type
  WKWebViewEvaluateJavascriptCallback = reference to procedure(param1: id; error: NSError); cblock; cdecl; // <<< SHOULD BE HERE
 
type
  TmsdvViewerCocoaWKWebView = ...
  public
    function GetDocumentAsStr: string;
    procedure GetDocumentAsStr_JavascriptCallback(param1: id; error: NSError); cdecl; // << SHOULD _NOT_ BE HERE
  end;
 
function TmsdvViewerCocoaWKWebView.GetDocumentAsStr: string;
var
  TmpJavaScriptCodeNSStr: NSString;
  TmpFuncCallbackRefVar: WKWebViewEvaluateJavascriptCallback;
begin
  TmpJavaScriptCodeNSStr := msMac_StrToNSStr('document.documentElement.outerHTML');
  TmpFuncCallbackRefVar := @GetDocumentAsStr_JavascriptCallback;
  FWebBrowser.FWebView_CocoaWKWebView.evaluateJavaScript_completionHandler(
    TmpJavaScriptCodeNSStr,
    OpaqueCBlock(TmpFuncCallbackRefVar)
    );
 end;

procedure TmsdvViewerCocoaWKWebView.GetDocumentAsStr_JavascriptCallback(param1: id; error: NSError); // << SHOULD NOT BE HERE
begin
  //
end

For the last one, 'cdecl' shouldn't be necessary either since the compiler should grab it from the class declaration, though I generally use {$MODE DELPHI} so I'm not positive on that for other modes.
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 12, 2022, 11:58:56 am
Thank you. Compilation works now. I will try out later if code crashes :D

One more question...

From
https://github.com/genericptr/MacOS_11_0/blob/master/webkit/WKWebView.inc

I see:
Code: Pascal  [Select][+][-]
  1. procedure setCustomUserAgent(newValue: NSString); message 'setCustomUserAgent:'; { available in macos 10.11, ios 9.0 }
  2. function customUserAgent: NSString; message 'customUserAgent'; { available in macos 10.11, ios 9.0 }

Does anyone know how API binding works on Mac?

Like if I add the above to my own WKWebView descendant... And user runs it on Mac OS 10.10 ... Will the executable not start?

Or is it sufficient that I check MacOS version before calling setCustomUserAgent?
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: Zoë on January 12, 2022, 09:46:02 pm
I think that standalone functions you need to load dynamically, but methods of Cocoa objects will be fine as long as you check the OS version before calling them.  Though macOS 10.11 is a reasonable lower bound nowadays anyway.  That's what we use for our app and we don't get any pushback about it (though we do have an older version that supports back to 10.6 available).
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: trev on January 13, 2022, 01:16:01 am
Quote
Or is it sufficient that I check macOS version before calling setCustomUserAgent?

You could do something like this to avoid undesired outcomes:

Code: Pascal  [Select][+][-]
  1. procedure TForm1.Button1Click(Sender: TObject);
  2. var
  3.   aSEL : SEL;
  4. begin
  5.     // Check whether OS version responds to this selector
  6.     aSEL := objcselector('operatingSystemVersion');
  7.     if NSProcessInfo.processInfo.respondsToSelector(aSEL) then
  8.       ProcessInfo
  9.     // Otherwise fallback to the deprecated Gestalt Manager
  10.     else
  11.       GestaltInfo;
  12. end;
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 13, 2022, 01:13:39 pm
Quick update: Javascript callback works.

New problem. I am pulling in all headers more or less because I need to do stuff.

However, I am encountering a circular referencing problem.

Declaration for

WKUserContentController references in its protocol declaration WKScriptMessageHandlerProtocol
and
WKScriptMessageHandlerProtocol references in its protocol declaration WKUserContentController

Not sure how to handle that.

Man... if those headers were implemented in FPC/Lazarus getting WKWebView to fully work would take estimated 1/20 of the time :D

Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: trev on January 13, 2022, 10:48:00 pm
Man... if those headers were implemented in FPC/Lazarus getting WKWebView to fully work would take estimated 1/20 of the time :D

Have you considered Ryan's conversion of the Cocoa headers for the macOS 11 SDK (https://github.com/genericptr/MacOS_11_0)?
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 13, 2022, 11:33:10 pm
I am manually copying in parts. Do you suggest I download the files and put them in a shared code library and try get Lazarus to use them? (Could not recompile FPC source)
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: trev on January 13, 2022, 11:55:28 pm
In the past I've simply copied Cocoa headers into my applications when I've needed to change/omit/add to the existing Cocoa headers (and removed the framework link directives).
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 14, 2022, 10:43:07 am
Maybe that had been better. But well, seems like no matter the solution one uses something trippy happens. But seems like a good idea, but not sure I want to to change now unless strictly necessary. It works OK copying in all headers. And then some day FPC team wants to integrate new headers I can comment it out.

But still... the problem is confusing:


Code: Pascal  [Select][+][-]
  1. //--
  2. // WKUserContentController.inc
  3. //--
  4. type
  5.   WKUserContentController = objcclass external (NSObject, NSSecureCodingProtocol)
  6.   public
  7.     function userScripts: NSArray; message 'userScripts';
  8.     procedure addUserScript (userScript: WKUserScript); message 'addUserScript:';
  9.     procedure removeAllUserScripts; message 'removeAllUserScripts';
  10.     procedure addScriptMessageHandler_contentWorld_name (scriptMessageHandler: WKScriptMessageHandlerProtocol; world: WKContentWorld; name: NSString); message 'addScriptMessageHandler:contentWorld:name:'; { available in macos 11.0, ios 14.0 }
  11.     procedure addScriptMessageHandlerWithReply_contentWorld_name (scriptMessageHandlerWithReply: WKScriptMessageHandlerWithReplyProtocol; contentWorld: WKContentWorld; name: NSString); message 'addScriptMessageHandlerWithReply:contentWorld:name:'; { available in macos 11.0, ios 14.0 }
  12.     procedure addScriptMessageHandler_name (scriptMessageHandler: WKScriptMessageHandlerProtocol; name: NSString); message 'addScriptMessageHandler:name:';
  13.     procedure removeScriptMessageHandlerForName_contentWorld (name: NSString; contentWorld: WKContentWorld); message 'removeScriptMessageHandlerForName:contentWorld:'; { available in macos 11.0, ios 14.0 }
  14.     procedure removeScriptMessageHandlerForName (name: NSString); message 'removeScriptMessageHandlerForName:';
  15.     procedure removeAllScriptMessageHandlersFromContentWorld (contentWorld: WKContentWorld); message 'removeAllScriptMessageHandlersFromContentWorld:'; { available in macos 11.0, ios 14.0 }
  16.     procedure removeAllScriptMessageHandlers; message 'removeAllScriptMessageHandlers'; { available in macos 11.0, ios 14.0 }
  17.     procedure addContentRuleList (contentRuleList: WKContentRuleList); message 'addContentRuleList:'; { available in macos 10.13, ios 11.0 }
  18.     procedure removeContentRuleList (contentRuleList: WKContentRuleList); message 'removeContentRuleList:'; { available in macos 10.13, ios 11.0 }
  19.     procedure removeAllContentRuleLists; message 'removeAllContentRuleLists'; { available in macos 10.13, ios 11.0 }
  20.     { Adopted protocols }
  21.     procedure encodeWithCoder (coder: NSCoder); message 'encodeWithCoder:';
  22.     function initWithCoder (coder: NSCoder): id; message 'initWithCoder:';
  23.     class function supportsSecureCoding: objcbool; message 'supportsSecureCoding';
  24.   end;
  25. type
  26.   WKUserContentControllerPtr = ^WKUserContentController;
  27. //--
  28. // WKScriptMessageHandler.inc
  29. //--
  30. type
  31.   WKScriptMessageHandlerProtocol = objcprotocol external name 'WKScriptMessageHandler' (NSObjectProtocol)
  32.   required
  33.     procedure userContentController_didReceiveScriptMessage (userContentController: WKUserContentController; message_: WKScriptMessage); message 'userContentController:didReceiveScriptMessage:';
  34.   end;
  35.  

Can't solve the circular reference between WKUserContentController and and WKScriptMessageHandlerProtocol



One additional oddness I have found is that copy from the updated headers I see code like this

Code: Pascal  [Select][+][-]
  1. type
  2.   WKScriptMessageHandlerProtocolPtr = ^WKScriptMessageHandlerProtocol;
  3.   WKScriptMessageHandlerProtocol = objcprotocol external name 'WKScriptMessageHandler' (NSObjectProtocol)
  4.   ...
  5.  

But when I compile Lazarus/FPC will not accept that and forces me to reverse order

Code: Pascal  [Select][+][-]
  1. type
  2.   WKScriptMessageHandlerProtocol = objcprotocol external name 'WKScriptMessageHandler' (NSObjectProtocol)
  3.   ...
  4.   WKScriptMessageHandlerProtocolPtr = ^WKScriptMessageHandlerProtocol;
  5.  

Not sure if the problem is related with some kind of forwards
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 14, 2022, 10:49:28 am
Found what I THOUGHT was solution in

https://github.com/genericptr/MacOS_11_0/blob/557d8f835b5591b8c43b820a8554185c0e402f2e/DefinedClassesWebKit.pas

DefinedClasses.inc


So examples
Code: Pascal  [Select][+][-]
  1.   WKScriptMessageHandlerProtocol = objcprotocol external name 'WKScriptMessageHandler';
  2.   // above forward for: WKScriptMessageHandlerProtocol = objcprotocol external name 'WKScriptMessageHandler' (NSObjectProtocol)
  3.  
  4.   WKUserContentController = objcclass external;
  5.   // above forward for: WKUserContentController = objcclass external (NSObject, NSSecureCodingProtocol)
  6.  


I am flipping inside right now. Why the **** does this work for the headers, but if predefine/forward declarations like above I get

Quote
Error: Duplicate identifier "xxxx"
Hint: Identifier already defined in UmsXXX.pas at line xxx

I actually think getting WKWebView fully working with all features would take like 1/50 of the time without all these problems  :o
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 15, 2022, 11:20:35 am
I am going to solve this "broken forwards of all kinds not working in my Lazarus" + "circular referencing" problems by...

Simply leaving out those declarations. I think that will work as long as I do not need to call them. At least I can compile then. Will need to see if causes problems runtime.

Do you agree this most likely will work? (i.e. I can only test on my own Mac, so if you have experience with it then do please let me know)

It will do as a temporary solution, so I can continue work and possibly also release.
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: trev on January 15, 2022, 10:22:46 pm
I am going to solve this "broken forwards of all kinds not working in my Lazarus" + "circular referencing" problems by...

Simply leaving out those declarations. I think that will work as long as I do not need to call them. At least I can compile then. Will need to see if causes problems runtime.

I've done this for other reasons and there've been no obvious issues. Nothing ventured, nothing gained :)
Title: Re: Minimum code for implementing WebView (deprecated) or WKWebView
Post by: MISV on January 17, 2022, 01:22:59 pm
Thank you :)


As everyone probably realizes, I am trying to hack and slash my way forward through the problems.


Seems Lazarus does not like this construct:


Code: Pascal  [Select][+][-]
  1.   TmsWKWebViewCore = objcclass external(WKWebView)
  2.   public
  3.     { available in macos 10.11, ios 9.0 }
  4.     procedure setCustomUserAgent(newValue: NSString); message 'setCustomUserAgent:';
  5.     function customUserAgent: NSString; message 'customUserAgent';
  6.   end;
  7.   TmsWKWebView = objcclass(TmsWKWebViewCore, WKScriptMessageHandlerProtocol)
  8.   public
  9.     procedure userContentController_didReceiveScriptMessage(userContentController: WKUserContentController; message_: WKScriptMessage);
  10.   end;
  11.  

(gives a bunch of error linker errors objc_class)


However using


Code: Pascal  [Select][+][-]
  1.  
  2. // while we use setNavigationDelegate, that solution is not possible with *WKScriptMessageHandlerProtocol* and need to implemented in main class
  3. TmsWKWebView = objcclass(TmsWKWebViewCore, WKScriptMessageHandlerProtocol)
  4.   public
  5.     { available in macos 10.11, ios 9.0 }
  6.     procedure setCustomUserAgent(newValue: NSString); message 'setCustomUserAgent:';
  7.     function customUserAgent: NSString; message 'customUserAgent';
  8.   public
  9.     procedure userContentController_didReceiveScriptMessage(userContentController: WKUserContentController; message_: WKScriptMessage);
  10.   end;
  11.  


also causes problems since compiler then expects the UserAgent functions to be implemented and not externally bound.

TinyPortal © 2005-2018