Add APIs for intercepting http request in web view.
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / devel-api / controls / web-view / web-view.h
1 #ifndef DALI_TOOLKIT_WEB_VIEW_H
2 #define DALI_TOOLKIT_WEB_VIEW_H
3
4 /*
5  * Copyright (c) 2021 Samsung Electronics Co., Ltd.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  */
20
21 // EXTERNAL INCLUDES
22 #include <functional>
23 #include <memory>
24
25 // INTERNAL INCLUDES
26 #include <dali-toolkit/public-api/controls/control.h>
27 #include <dali/devel-api/adaptor-framework/web-engine-plugin.h>
28
29 namespace Dali
30 {
31 namespace Toolkit
32 {
33 class ImageView;
34 class WebBackForwardList;
35 class WebContext;
36 class WebCookieManager;
37 class WebFormRepostDecision;
38 class WebSettings;
39
40 namespace Internal DALI_INTERNAL
41 {
42 class WebView;
43 } // namespace DALI_INTERNAL
44
45 /**
46  * @addtogroup dali_toolkit_controls_web_view
47  * @{
48  */
49
50 /**
51  * @brief WebView is a control for displaying web content.
52  *
53  * This enables embedding web pages in the application.
54  *
55  * For working WebView, a web engine plugin for a platform should be provided.
56  *
57  */
58 class DALI_TOOLKIT_API WebView : public Control
59 {
60 public:
61   /**
62    * @brief Enumeration for the start and end property ranges for this control.
63    */
64   enum PropertyRange
65   {
66     PROPERTY_START_INDEX = Control::CONTROL_PROPERTY_END_INDEX + 1,
67     PROPERTY_END_INDEX   = PROPERTY_START_INDEX + 1000,
68   };
69
70   /**
71    * @brief Enumeration for the instance of properties belonging to the WebView class.
72    */
73   struct Property
74   {
75     enum
76     {
77       /**
78        * @brief The url to load.
79        * @details name "url", type Property::STRING.
80        */
81       URL = PROPERTY_START_INDEX,
82
83       /**
84        * @brief The user agent string.
85        * @details name "userAgent", type Property::STRING.
86        */
87       USER_AGENT,
88
89       /**
90        * @brief The current position of scroll.
91        * @details name "scrollPosition", type Property::VECTOR2.
92        */
93       SCROLL_POSITION,
94
95       /**
96        * @brief The current size of scroll.
97        * @details name "scrollSize", type Property::VECTOR2.
98        * @note The value is read-only.
99        */
100       SCROLL_SIZE,
101
102       /**
103        * @brief The current size of content.
104        * @details name "contentSize", type Property::VECTOR2.
105        * @note The value is read-only.
106        */
107       CONTENT_SIZE,
108
109       /**
110        * @brief The title of web page.
111        * @details name "title", type Property::STRING.
112        * @note The value is read-only.
113        */
114       TITLE,
115
116       /**
117        * @brief Whether video hole is enabled or not.
118        * @details name "videoHoleEnabled", type Property::BOOLEAN.
119        * @note The value is read-only.
120        */
121       VIDEO_HOLE_ENABLED,
122
123       /**
124        * @brief Whether mouse event is enabled.
125        * @details name "mouseEventsEnabled", type Property::BOOLEAN.
126        * @note Default is true.
127        */
128       MOUSE_EVENTS_ENABLED,
129
130       /**
131        * @brief Whether key event is enabled.
132        * @details name "keyEventsEnabled", type Property::BOOLEAN.
133        * @note Default is true.
134        */
135       KEY_EVENTS_ENABLED,
136
137       /**
138        * @brief The background color of web page.
139        * @details name "documentBackgroundColor", type Property::VECTOR4.
140        */
141       DOCUMENT_BACKGROUND_COLOR,
142
143       /**
144        * @brief Whether tiles can be cleared or not when hidden.
145        * @details name "tilesClearedWhenHidden", type BOOLEAN.
146        */
147       TILES_CLEARED_WHEN_HIDDEN,
148
149       /**
150        * @brief The multiplier of cover area of tile when rendering web page.
151        * @details name "tileCoverAreaMultiplier", type FLOAT.
152        */
153       TILE_COVER_AREA_MULTIPLIER,
154
155       /**
156        * @brief Whether cursor is enabled or not by client.
157        * @details name "cursorEnabledByClient", type BOOLEAN.
158        */
159       CURSOR_ENABLED_BY_CLIENT,
160
161       /**
162        * @brief The selected text of web page.
163        * @details name "selectedText", type Property::STRING.
164        * @note The value is read-only.
165        */
166       SELECTED_TEXT,
167
168       /**
169        * @brief Zoom factor of web page.
170        * @details name "pageZoomFactor", type Property::FLOAT.
171        */
172       PAGE_ZOOM_FACTOR,
173
174       /**
175        * @brief Zoom factor of text.
176        * @details name "textZoomFactor", type Property::FLOAT.
177        */
178       TEXT_ZOOM_FACTOR,
179
180       /**
181        * @brief progress percentage of loading a web page.
182        * @details name "loadProgressPercentage", type Property::FLOAT.
183        * @note The value is read-only.
184        */
185       LOAD_PROGRESS_PERCENTAGE,
186     };
187   };
188
189   /**
190    * @brief Enumeration for indicating error code of page loading.
191    */
192   enum class LoadErrorCode
193   {
194     UNKNOWN = 0,           ///< Unknown.
195     CANCELED,              ///< User canceled.
196     CANT_SUPPORT_MIMETYPE, ///< Can't show the page for this MIME type.
197     FAILED_FILE_IO,        ///< File IO error.
198     CANT_CONNECT,          ///< Cannot connect to the network.
199     CANT_LOOKUP_HOST,      ///< Fail to look up host from the DNS.
200     FAILED_TLS_HANDSHAKE,  ///< Fail to SSL/TLS handshake.
201     INVALID_CERTIFICATE,   ///< Received certificate is invalid.
202     REQUEST_TIMEOUT,       ///< Connection timeout.
203     TOO_MANY_REDIRECTS,    ///< Too many redirects.
204     TOO_MANY_REQUESTS,     ///< Too many requests during this load.
205     BAD_URL,               ///< Malformed URL.
206     UNSUPPORTED_SCHEME,    ///< Unsupported scheme.
207     AUTHENTICATION,        ///< User authentication failed on the server.
208     INTERNAL_SERVER        ///< Web server has an internal server error.
209   };
210
211   /**
212    * @brief WebView callback related with screen-shot captured.
213    */
214   using WebViewScreenshotCapturedCallback = std::function<void(Dali::Toolkit::ImageView)>;
215
216   /**
217    * @brief WebView signal type related with page loading.
218    */
219   using WebViewPageLoadSignalType = Signal<void(WebView, const std::string&)>;
220
221   /**
222    * @brief WebView signal type related with page loading error.
223    */
224   using WebViewPageLoadErrorSignalType = Signal<void(WebView, const std::string&, LoadErrorCode)>;
225
226   /**
227    * @brief WebView signal type related with scroll edge reached.
228    */
229   using WebViewScrollEdgeReachedSignalType = Signal<void(WebView, Dali::WebEnginePlugin::ScrollEdge)>;
230
231   /**
232    * @brief WebView signal type related with url changed.
233    */
234   using WebViewUrlChangedSignalType = Signal<void(WebView, const std::string&)>;
235
236   /**
237    * @brief WebView signal type related with form repost decision.
238    */
239   using WebViewFormRepostDecisionSignalType = Signal<void(WebView, std::shared_ptr<Dali::Toolkit::WebFormRepostDecision>)>;
240
241   /**
242    * @brief WebView signal type related with frame rendered.
243    */
244   using WebViewFrameRenderedSignalType = Signal<void(WebView)>;
245
246   /**
247    * @brief WebView signal type related with http request interceptor.
248    */
249   using WebViewRequestInterceptorSignalType = Signal<void(WebView, std::shared_ptr<Dali::WebEngineRequestInterceptor>)>;
250
251 public:
252   /**
253    * @brief Creates an initialized WebView.
254    * @return A handle to a newly allocated Dali WebView
255    *
256    * @note WebView will not display anything
257    */
258   static WebView New();
259
260   /**
261    * @brief Creates an initialized WebView.
262    *
263    * @param [in] locale The locale of Web
264    * @param [in] timezoneId The timezoneId of Web
265    */
266   static WebView New(const std::string& locale, const std::string& timezoneId);
267
268   /**
269    * @brief Creates an initialized WebView.
270    *
271    * @param [in] argc The count of arguments of Applications
272    * @param [in] argv The string array of arguments of Applications
273    */
274   static WebView New(int argc, char** argv);
275
276   /**
277    * @brief Creates an uninitialized WebView.
278    */
279   WebView();
280
281   /**
282    * @brief Destructor.
283    *
284    * This is non-virtual since derived Handel types must not contain data or virtual methods.
285    */
286   ~WebView();
287
288   /*
289    * @brief Copy constructor.
290    *
291    * @param[in] WebView WebView to copy. The copied WebView will point at the same implementation
292    */
293   WebView(const WebView& WebView);
294
295   /**
296    * @brief Assignment operator.
297    *
298    * @param[in] WebView The WebView to assign from
299    * @return The updated WebView
300    */
301   WebView& operator=(const WebView& WebView);
302
303   /**
304    * @brief Downcasts a handle to WebView handle.
305    *
306    * If handle points to a WebView, the downcast produces valid handle.
307    * If not, the returned handle is left uninitialized.
308    *
309    * @param[in] handle Handle to an object
310    * @return Handle to a WebView or an uninitialized handle
311    */
312   static WebView DownCast(BaseHandle handle);
313
314   /**
315    * @brief Get WebSettings of WebEngine.
316    */
317   Dali::Toolkit::WebSettings* GetSettings() const;
318
319   /**
320    * @brief Get WebContext of WebEngine.
321    */
322   Dali::Toolkit::WebContext* GetContext() const;
323
324   /**
325    * @brief Get CookieManager of WebEngine.
326    */
327   Dali::Toolkit::WebCookieManager* GetCookieManager() const;
328
329   /**
330    * @brief Get WebBackForwardList of WebEngine.
331    */
332   Dali::Toolkit::WebBackForwardList* GetBackForwardList() const;
333
334   /**
335    * @brief Get Favicon of web page.
336    *
337    * @return Handle to a fav icon
338    */
339   Dali::Toolkit::ImageView& GetFavicon();
340
341   /**
342    * @brief Loads a web page based on a given URL.
343    *
344    * @param [in] url The URL of the resource to load
345    */
346   void LoadUrl(const std::string& url);
347
348   /**
349    * @brief Loads a given string as web contents.
350    *
351    * @param [in] htmlString The string to use as the contents of the web page
352    */
353   void LoadHtmlString(const std::string& htmlString);
354
355   /**
356    * @brief Load the specified html string as the content of the view overriding current history entry
357    *
358    * @param[in] html HTML data to load
359    * @param[in] basicUri Base URL used for relative paths to external objects
360    * @param[in] unreachableUrl URL that could not be reached
361    *
362    * @return true if successfully loaded, false otherwise
363    */
364   bool LoadHtmlStringOverrideCurrentEntry(const std::string& html, const std::string& basicUri, const std::string& unreachableUrl);
365
366   /**
367    * @brief Requests loading the given contents by MIME type into the view object
368    *
369    * @param[in] contents The content to load
370    * @param[in] contentSize The size of contents (in bytes)
371    * @param[in] mimeType The type of contents, if 0 is given "text/html" is assumed
372    * @param[in] encoding The encoding for contents, if 0 is given "UTF-8" is assumed
373    * @param[in] baseUri The base URI to use for relative resources
374    *
375    * @return true if successfully request, false otherwise
376    */
377   bool LoadContents(const std::string& contents, uint32_t contentSize, const std::string& mimeType, const std::string& encoding, const std::string& baseUri);
378
379   /**
380    * @brief Reloads the Web.
381    */
382   void Reload();
383
384   /**
385    * @brief Reloads the current page's document without cache
386    */
387   bool ReloadWithoutCache();
388
389   /**
390    * @brief Stops loading web contents on the current page.
391    */
392   void StopLoading();
393
394   /**
395    * @brief Suspends the operation associated with the view.
396    */
397   void Suspend();
398
399   /**
400    * @brief Resumes the operation associated with the view object after calling Suspend().
401    */
402   void Resume();
403
404   /**
405    * @brief To suspend all url loading
406    */
407   void SuspendNetworkLoading();
408
409   /**
410    * @brief To resume new url network loading
411    */
412   void ResumeNetworkLoading();
413
414   /**
415    * @brief Add custom header
416    *
417    * @param[in] name custom header name to add the custom header
418    * @param[in] value custom header value to add the custom header
419    *
420    * @return true if succeeded, false otherwise
421    */
422   bool AddCustomHeader(const std::string& name, const std::string& value);
423
424   /**
425    * @brief Remove custom header
426    *
427    * @param[in] name custom header name to remove the custom header
428    *
429    * @return true if succeeded, false otherwise
430    */
431   bool RemoveCustomHeader(const std::string& name);
432
433   /**
434    * @brief Start the inspector server
435    *
436    * @param[in] port port number
437    *
438    * @return the port number
439    */
440   uint32_t StartInspectorServer(uint32_t port);
441
442   /**
443    * @brief Stop the inspector server
444    *
445    * @return true if succeeded, false otherwise
446    */
447   bool StopInspectorServer();
448
449   /**
450    * @brief Scrolls web page of view by deltaX and deltaY.
451    * @param[in] deltaX The delta x of scroll
452    * @param[in] deltaY The delta y of scroll
453    */
454   void ScrollBy(int deltaX, int deltaY);
455
456   /**
457    * @brief Scrolls edge of view by deltaX and deltaY.
458    *
459    * @param[in] deltaX horizontal offset to scroll
460    * @param[in] deltaY vertical offset to scroll
461    *
462    * @return true if succeeded, false otherwise
463    */
464   bool ScrollEdgeBy(int deltaX, int deltaY);
465
466   /**
467    * @brief Returns whether forward is possible.
468    *
469    * @return True if forward is possible, false otherwise
470    */
471   bool CanGoForward();
472
473   /**
474    * @brief Goes forward in the navigation history.
475    */
476   void GoForward();
477
478   /**
479    * @brief Returns whether backward is possible.
480    *
481    * @return True if backward is possible, false otherwise
482    */
483   bool CanGoBack();
484
485   /**
486    * @brief Goes back in the navigation history.
487    */
488   void GoBack();
489
490   /**
491    * @brief Evaluates JavaScript code represented as a string.
492    *
493    * @param[in] script The JavaScript code
494    * @param[in] resultHandler The callback function to be called by the JavaScript runtime. This carries evaluation result
495    */
496   void EvaluateJavaScript(const std::string& script, std::function<void(const std::string&)> resultHandler);
497
498   /**
499    * @brief Evaluates JavaScript code represented as a string.
500    *
501    * @param[in] script The JavaScript code
502    */
503   void EvaluateJavaScript(const std::string& script);
504
505   /**
506    * @brief Inject a JavaScript object with a message handler into the WebView.
507    *
508    * @note The injected object will appear in the JavaScript context to be loaded next.
509    *
510    * Example:
511    *
512    * 1. Native
513    *
514    *     webview.AddJavaScriptMessageHandler( "myObject", []( const std::string& message ) {
515    *         printf( "Received a message from JS: %s", message.c_str() );
516    *     });
517    *
518    *     // Start WebView by loading URL
519    *     webview.LoadUrl( url );
520    *
521    * 2. JavaScript
522    *
523    *     myObject.postMessage( "Hello World!" ); // "Received a message from JS: Hello World!"
524    *
525    *
526    * @param[in] exposedObjectName The name of exposed object
527    * @param[in] handler The callback function
528    */
529   void AddJavaScriptMessageHandler(const std::string& exposedObjectName, std::function<void(const std::string&)> handler);
530
531   /**
532    * @brief Register alert callback for javascript.
533    *
534    * @param[in] callback The callback function to be called by the JavaScript runtime.
535    */
536   void RegisterJavaScriptAlertCallback(Dali::WebEnginePlugin::JavaScriptAlertCallback callback);
537
538   /**
539    * @brief Reply for JavaScript alert.
540    */
541   void JavaScriptAlertReply();
542
543   /**
544    * @brief Register confirm callback for javascript.
545    *
546    * @param[in] callback The callback function to be called by the JavaScript runtime.
547    */
548   void RegisterJavaScriptConfirmCallback(Dali::WebEnginePlugin::JavaScriptConfirmCallback callback);
549
550   /**
551    * @brief Reply for JavaScript confirm.
552    * @param[in] confirmed True if confirmed, false otherwise
553    */
554   void JavaScriptConfirmReply(bool confirmed);
555
556   /**
557    * @brief Register prompt callback for javascript.
558    *
559    * @param[in] callback The callback function to be called by the JavaScript runtime.
560    */
561   void RegisterJavaScriptPromptCallback(Dali::WebEnginePlugin::JavaScriptPromptCallback callback);
562
563   /**
564    * @brief Reply for JavaScript prompt.
565    * @param[in] result The result from input-field of prompt popup.
566    */
567   void JavaScriptPromptReply(const std::string& result);
568
569   /**
570    * @brief Clears the history of Web.
571    */
572   void ClearHistory();
573
574   /**
575    * @brief Clears all tiles resources of Web.
576    */
577   void ClearAllTilesResources();
578
579   /**
580    * @brief Scales the current page, centered at the given point.
581    * @param[in] scaleFactor a new factor to be scaled.
582    * @param[in] point a center coordinate.
583    */
584   void SetScaleFactor(float scaleFactor, Dali::Vector2 point);
585
586   /**
587    * @brief Gets the current scale factor of the page.
588    * @return The current scale factor.
589    */
590   float GetScaleFactor() const;
591
592   /**
593    * @brief Request to activate/deactivate the accessibility usage set by web app.
594    * @param[in] activated Activate accessibility or not.
595    */
596   void ActivateAccessibility(bool activated);
597
598   /**
599    * @brief Searches and highlights the given string in the document.
600    * @param[in] text The text to find
601    * @param[in] options The options to find
602    * @param[in] maxMatchCount The maximum match count to find
603    *
604    * @return true if found & highlighted, false otherwise
605    */
606   bool HighlightText(const std::string& text, Dali::WebEnginePlugin::FindOption options, uint32_t maxMatchCount);
607
608   /**
609    * @brief Add dynamic certificate path.
610    * @param[in] host host that required client authentication
611    * @param[in] certPath the file path stored certificate
612    */
613   void AddDynamicCertificatePath(const std::string& host, const std::string& certPath);
614
615   /**
616    * @brief Get snapshot of the specified viewArea of page.
617    *
618    * @param[in] viewArea The rectangle of screen shot
619    * @param[in] scaleFactor The scale factor
620    *
621    * @return image view of screen shot
622    */
623   Dali::Toolkit::ImageView GetScreenshot(Dali::Rect<int> viewArea, float scaleFactor);
624
625   /**
626    * @brief Request to get snapshot of the specified viewArea of page asynchronously.
627    *
628    * @param[in] viewArea The rectangle of screen shot
629    * @param[in] scaleFactor The scale factor
630    * @param[in] callback The callback for screen shot
631    *
632    * @return true if requested successfully, false otherwise
633    */
634   bool GetScreenshotAsynchronously(Dali::Rect<int> viewArea, float scaleFactor, WebViewScreenshotCapturedCallback callback);
635
636   /**
637    * @brief Asynchronous request to check if there is a video playing in the given view.
638    *
639    * @param[in] callback The callback called after checking if video is playing or not
640    *
641    * @return true if requested successfully, false otherwise
642    */
643   bool CheckVideoPlayingAsynchronously(Dali::WebEnginePlugin::VideoPlayingCallback callback);
644
645   /**
646    * @brief Sets callback which will be called upon geolocation permission request.
647    *
648    * @param[in] callback The callback for requesting geolocation permission
649    */
650   void RegisterGeolocationPermissionCallback(Dali::WebEnginePlugin::GeolocationPermissionCallback callback);
651
652   /**
653    * @brief Connects to this signal to be notified when page loading is started.
654    *
655    * @return A signal object to connect with
656    */
657   WebViewPageLoadSignalType& PageLoadStartedSignal();
658
659   /**
660    * @brief Connects to this signal to be notified when page loading is in progress.
661    *
662    * @return A signal object to connect with
663    */
664   WebViewPageLoadSignalType& PageLoadInProgressSignal();
665
666   /**
667    * @brief Connects to this signal to be notified when page loading is finished.
668    *
669    * @return A signal object to connect with
670    */
671   WebViewPageLoadSignalType& PageLoadFinishedSignal();
672
673   /**
674    * @brief Connects to this signal to be notified when an error occurs in page loading.
675    *
676    * @return A signal object to connect with
677    */
678   WebViewPageLoadErrorSignalType& PageLoadErrorSignal();
679
680   /**
681    * @brief Connects to this signal to be notified when scroll edge is reached.
682    *
683    * @return A signal object to connect with
684    */
685   WebViewScrollEdgeReachedSignalType& ScrollEdgeReachedSignal();
686
687   /**
688    * @brief Connects to this signal to be notified when url is changed.
689    *
690    * @return A signal object to connect with
691    */
692   WebViewUrlChangedSignalType& UrlChangedSignal();
693
694   /**
695    * @brief Connects to this signal to be notified when form repost decision is requested.
696    *
697    * @return A signal object to connect with.
698    */
699   WebViewFormRepostDecisionSignalType& FormRepostDecisionSignal();
700
701   /**
702    * @brief Connects to this signal to be notified when frame is rendered.
703    *
704    * @return A signal object to connect with.
705    */
706   WebViewFrameRenderedSignalType& FrameRenderedSignal();
707
708   /**
709    * @brief Connects to this signal to be notified when http request need be intercepted.
710    *
711    * @return A signal object to connect with.
712    */
713   WebViewRequestInterceptorSignalType& RequestInterceptorSignal();
714
715 public: // Not intended for application developers
716   /// @cond internal
717   /**
718    * @brief Creates a handle using the Toolkit::Internal implementation.
719    *
720    * @param[in] implementation The WebView implementation
721    */
722   DALI_INTERNAL WebView(Internal::WebView& implementation);
723
724   /**
725    * @brief Allows the creation of this WebView from an Internal::CustomActor pointer.
726    *
727    * @param[in] internal A pointer to the internal CustomActor
728    */
729   explicit DALI_INTERNAL WebView(Dali::Internal::CustomActor* internal);
730   /// @endcond
731 };
732
733 /**
734  * @}
735  */
736
737 } // namespace Toolkit
738
739 } // namespace Dali
740
741 #endif // DALI_TOOLKIT_WEB_VIEW_H