Change the chromium header from ewk_chromium.h to EWebKit.h/Ewebkit_internal.h
[platform/framework/web/crosswalk-tizen.git] / runtime / browser / web_application.cc
1 /*
2  * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16
17 #include "runtime/browser/web_application.h"
18
19 #include <app.h>
20 #include <Ecore.h>
21 #include <aul.h>
22
23 #include <algorithm>
24 #include <map>
25 #include <memory>
26 #include <sstream>
27 #include <vector>
28
29 #include "common/application_data.h"
30 #include "common/app_db.h"
31 #include "common/app_control.h"
32 #include "common/command_line.h"
33 #include "common/locale_manager.h"
34 #include "common/logger.h"
35 #include "common/profiler.h"
36 #include "common/resource_manager.h"
37 #include "common/string_utils.h"
38 #include "runtime/browser/native_window.h"
39 #include "runtime/browser/notification_manager.h"
40 #include "runtime/browser/popup.h"
41 #include "runtime/browser/popup_string.h"
42 #include "runtime/browser/vibration_manager.h"
43 #include "runtime/browser/web_view.h"
44 #include "runtime/browser/splash_screen.h"
45 #include "extensions/common/xwalk_extension_server.h"
46
47 #ifndef INJECTED_BUNDLE_PATH
48 #error INJECTED_BUNDLE_PATH is not set.
49 #endif
50
51 namespace runtime {
52
53 namespace {
54 const char* kKeyNameBack = "back";
55 const char* kKeyNameMenu = "menu";
56
57 const char* kConsoleLogEnableKey = "WRT_CONSOLE_LOG_ENABLE";
58 const char* kConsoleMessageLogTag = "ConsoleMessage";
59
60 const char* kVerboseKey = "verbose";
61 const char* kPortKey = "port";
62
63 const char* kAppControlEventScript =
64     "(function(){"
65     "var __event = document.createEvent(\"CustomEvent\");\n"
66     "__event.initCustomEvent(\"appcontrol\", true, true, null);\n"
67     "document.dispatchEvent(__event);\n"
68     "\n"
69     "for (var i=0; i < window.frames.length; i++)\n"
70     "{ window.frames[i].document.dispatchEvent(__event); }"
71     "})()";
72 const char* kBackKeyEventScript =
73     "(function(){"
74     "var __event = document.createEvent(\"CustomEvent\");\n"
75     "__event.initCustomEvent(\"tizenhwkey\", true, true, null);\n"
76     "__event.keyName = \"back\";\n"
77     "document.dispatchEvent(__event);\n"
78     "\n"
79     "for (var i=0; i < window.frames.length; i++)\n"
80     "{ window.frames[i].document.dispatchEvent(__event); }"
81     "})()";
82 const char* kMenuKeyEventScript =
83     "(function(){"
84     "var __event = document.createEvent(\"CustomEvent\");\n"
85     "__event.initCustomEvent(\"tizenhwkey\", true, true, null);\n"
86     "__event.keyName = \"menu\";\n"
87     "document.dispatchEvent(__event);\n"
88     "\n"
89     "for (var i=0; i < window.frames.length; i++)\n"
90     "{ window.frames[i].document.dispatchEvent(__event); }"
91     "})()";
92 const char* kAmbientTickEventScript =
93     "(function(){"
94     "var __event = document.createEvent(\"CustomEvent\");\n"
95     "__event.initCustomEvent(\"timetick\", true, true);\n"
96     "document.dispatchEvent(__event);\n"
97     "\n"
98     "for (var i=0; i < window.frames.length; i++)\n"
99     "{ window.frames[i].document.dispatchEvent(__event); }"
100     "})()";
101 const char* kFullscreenPrivilege = "http://tizen.org/privilege/fullscreen";
102 const char* kFullscreenFeature = "fullscreen";
103 const char* kNotificationPrivilege = "http://tizen.org/privilege/notification";
104 const char* kLocationPrivilege = "http://tizen.org/privilege/location";
105 const char* kStoragePrivilege = "http://tizen.org/privilege/unlimitedstorage";
106 const char* kUsermediaPrivilege = "http://tizen.org/privilege/mediacapture";
107 const char* kNotiIconFile = "noti_icon.png";
108 const char* kFileScheme = "file://";
109
110 const char* kVisibilitySuspendFeature = "visibility,suspend";
111 const char* kMediastreamRecordFeature = "mediastream,record";
112 const char* kEncryptedDatabaseFeature = "encrypted,database";
113 const char* kRotationLockFeature = "rotation,lock";
114 const char* kBackgroundMusicFeature = "background,music";
115 const char* kSoundModeFeature = "sound,mode";
116 const char* kBackgroundVibrationFeature = "background,vibration";
117 const char* kCSPFeature = "csp";
118
119 const char* kGeolocationPermissionPrefix = "__WRT_GEOPERM_";
120 const char* kNotificationPermissionPrefix = "__WRT_NOTIPERM_";
121 const char* kQuotaPermissionPrefix = "__WRT_QUOTAPERM_";
122 const char* kCertificateAllowPrefix = "__WRT_CERTIPERM_";
123 const char* kUsermediaPermissionPrefix = "__WRT_USERMEDIAPERM_";
124 const char* kDBPrivateSection = "private";
125
126 const char* kDefaultCSPRule =
127     "default-src *; script-src 'self'; style-src 'self'; object-src 'none';";
128 const char* kResWgtPath = "res/wgt/";
129 const char* kAppControlMain = "http://tizen.org/appcontrol/operation/main";
130
131 bool FindPrivilege(common::ApplicationData* app_data,
132                    const std::string& privilege) {
133   if (app_data->permissions_info().get() == NULL) return false;
134   auto it = app_data->permissions_info()->GetAPIPermissions().begin();
135   auto end = app_data->permissions_info()->GetAPIPermissions().end();
136   for (; it != end; ++it) {
137     if (*it == privilege) return true;
138   }
139   return false;
140 }
141
142 static void SendDownloadRequest(const std::string& url) {
143   common::AppControl request;
144   request.set_operation(APP_CONTROL_OPERATION_DOWNLOAD);
145   request.set_uri(url);
146   request.LaunchRequest();
147 }
148
149 static void InitializeNotificationCallback(Ewk_Context* ewk_context,
150                                            WebApplication* app) {
151   auto show = [](Ewk_Context*, Ewk_Notification* noti, void* user_data) {
152     WebApplication* self = static_cast<WebApplication*>(user_data);
153     if (self == NULL) return;
154     uint64_t id = ewk_notification_id_get(noti);
155     std::string title(ewk_notification_title_get(noti)
156                           ? ewk_notification_title_get(noti)
157                           : "");
158     std::string body(
159         ewk_notification_body_get(noti) ? ewk_notification_body_get(noti) : "");
160     std::string icon_path = self->data_path() + "/" + kNotiIconFile;
161     if (!ewk_notification_icon_save_as_png(noti, icon_path.c_str())) {
162       icon_path = "";
163     }
164     if (NotificationManager::GetInstance()->Show(id, title, body, icon_path))
165       ewk_notification_showed(id);
166   };
167   auto hide = [](Ewk_Context*, uint64_t noti_id, void*) {
168     NotificationManager::GetInstance()->Hide(noti_id);
169     ewk_notification_closed(noti_id, EINA_FALSE);
170   };
171   ewk_context_notification_callbacks_set(ewk_context, show, hide, app);
172 }
173
174 static Eina_Bool ExitAppIdlerCallback(void* data) {
175   WebApplication* app = static_cast<WebApplication*>(data);
176   if (app)
177     app->Terminate();
178   return ECORE_CALLBACK_CANCEL;
179 }
180
181 static bool ClearCookie(Ewk_Context* ewk_context) {
182   Ewk_Cookie_Manager* cookie_manager =
183       ewk_context_cookie_manager_get(ewk_context);
184   if (!cookie_manager) {
185     LOGGER(ERROR) << "Fail to get cookie manager";
186     return false;
187   }
188   ewk_cookie_manager_cookies_clear(cookie_manager);
189   return true;
190 }
191
192 static bool ProcessWellKnownScheme(const std::string& url) {
193   if (common::utils::StartsWith(url, "file:") ||
194       common::utils::StartsWith(url, "app:") ||
195       common::utils::StartsWith(url, "data:") ||
196       common::utils::StartsWith(url, "http:") ||
197       common::utils::StartsWith(url, "https:") ||
198       common::utils::StartsWith(url, "widget:") ||
199       common::utils::StartsWith(url, "about:") ||
200       common::utils::StartsWith(url, "blob:")) {
201     return false;
202   }
203
204   std::unique_ptr<common::AppControl> request(
205       common::AppControl::MakeAppcontrolFromURL(url));
206   if (request.get() == NULL || !request->LaunchRequest()) {
207     LOGGER(ERROR) << "Fail to send appcontrol request";
208     SLoggerE("Fail to send appcontrol request [%s]", url.c_str());
209   }
210
211   // Should return true, to stop the WebEngine progress step about this URL
212   return true;
213 }
214
215 }  // namespace
216
217 WebApplication::WebApplication(
218     NativeWindow* window,
219     common::ApplicationData* app_data)
220     : launched_(false),
221       debug_mode_(false),
222       verbose_mode_(false),
223       ewk_context_(
224           ewk_context_new_with_injected_bundle_path(INJECTED_BUNDLE_PATH)),
225       has_ownership_of_ewk_context_(true),
226       window_(window),
227       appid_(app_data->app_id()),
228       app_data_(app_data),
229       locale_manager_(new common::LocaleManager()),
230       terminator_(NULL) {
231   Initialize();
232 }
233
234 WebApplication::WebApplication(
235     NativeWindow* window,
236     common::ApplicationData* app_data,
237     Ewk_Context* context)
238     : launched_(false),
239       debug_mode_(false),
240       verbose_mode_(false),
241       ewk_context_(context),
242       has_ownership_of_ewk_context_(false),
243       window_(window),
244       appid_(app_data->app_id()),
245       app_data_(app_data),
246       locale_manager_(new common::LocaleManager()),
247       terminator_(NULL) {
248   Initialize();
249 }
250
251 WebApplication::~WebApplication() {
252   window_->SetContent(NULL);
253   auto it = view_stack_.begin();
254   for (; it != view_stack_.end(); ++it) {
255     delete *it;
256   }
257   view_stack_.clear();
258   if (ewk_context_ && has_ownership_of_ewk_context_)
259     ewk_context_delete(ewk_context_);
260 }
261
262 bool WebApplication::Initialize() {
263   SCOPE_PROFILE();
264   std::unique_ptr<char, decltype(std::free)*> path{app_get_data_path(),
265                                                    std::free};
266   app_data_path_ = path.get();
267
268   if (app_data_->setting_info() != NULL &&
269       app_data_->setting_info()->screen_orientation() ==
270           wgt::parse::SettingInfo::ScreenOrientation::AUTO) {
271     ewk_context_tizen_extensible_api_string_set(ewk_context_,
272                                                 kRotationLockFeature, true);
273     window_->SetAutoRotation();
274   } else if (app_data_->setting_info() != NULL &&
275              app_data_->setting_info()->screen_orientation() ==
276                  wgt::parse::SettingInfo::ScreenOrientation::PORTRAIT) {
277     window_->SetRotationLock(NativeWindow::ScreenOrientation::PORTRAIT_PRIMARY);
278   } else if (app_data_->setting_info() != NULL &&
279              app_data_->setting_info()->screen_orientation() ==
280                  wgt::parse::SettingInfo::ScreenOrientation::LANDSCAPE) {
281     window_->SetRotationLock(
282         NativeWindow::ScreenOrientation::LANDSCAPE_PRIMARY);
283   }
284
285   splash_screen_.reset(new SplashScreen(
286       window_, app_data_->splash_screen_info(), app_data_->application_path()));
287   resource_manager_.reset(
288       new common::ResourceManager(app_data_, locale_manager_.get()));
289   resource_manager_->set_base_resource_path(app_data_->application_path());
290
291   auto extension_server = extensions::XWalkExtensionServer::GetInstance();
292   extension_server->SetupIPC(ewk_context_);
293
294   // ewk setting
295   ewk_context_cache_model_set(ewk_context_, EWK_CACHE_MODEL_DOCUMENT_BROWSER);
296
297   // cookie
298   auto cookie_manager = ewk_context_cookie_manager_get(ewk_context_);
299   ewk_cookie_manager_accept_policy_set(cookie_manager,
300                                        EWK_COOKIE_ACCEPT_POLICY_ALWAYS);
301
302   // set persistent storage path
303   std::string cookie_path = data_path() + ".cookie";
304   ewk_cookie_manager_persistent_storage_set(
305       cookie_manager, cookie_path.c_str(),
306       EWK_COOKIE_PERSISTENT_STORAGE_SQLITE);
307
308   // vibration callback
309   auto vibration_start_callback = [](uint64_t ms, void*) {
310     platform::VibrationManager::GetInstance()->Start(static_cast<int>(ms));
311   };
312   auto vibration_stop_callback = [](void* /*user_data*/) {
313     platform::VibrationManager::GetInstance()->Stop();
314   };
315   ewk_context_vibration_client_callbacks_set(
316       ewk_context_, vibration_start_callback, vibration_stop_callback, NULL);
317
318   auto download_callback = [](const char* downloadUrl, void* /*data*/) {
319     SendDownloadRequest(downloadUrl);
320   };
321   ewk_context_did_start_download_callback_set(ewk_context_, download_callback,
322                                               this);
323   InitializeNotificationCallback(ewk_context_, this);
324
325   if (FindPrivilege(app_data_, kFullscreenPrivilege)) {
326     ewk_context_tizen_extensible_api_string_set(ewk_context_,
327                                                 kFullscreenFeature, true);
328   }
329
330   if (app_data_->setting_info() != NULL &&
331       app_data_->setting_info()->background_support_enabled()) {
332     ewk_context_tizen_extensible_api_string_set(
333                                 ewk_context_, kVisibilitySuspendFeature, true);
334     ewk_context_tizen_extensible_api_string_set(ewk_context_,
335                                                 kBackgroundMusicFeature, true);
336   } else {
337     ewk_context_tizen_extensible_api_string_set(
338                                ewk_context_, kVisibilitySuspendFeature, false);
339     ewk_context_tizen_extensible_api_string_set(ewk_context_,
340                                                kBackgroundMusicFeature, false);
341   }
342   ewk_context_tizen_extensible_api_string_set(ewk_context_,
343                                               kMediastreamRecordFeature, true);
344   ewk_context_tizen_extensible_api_string_set(ewk_context_,
345                                               kEncryptedDatabaseFeature, true);
346
347   if (app_data_->setting_info() != NULL &&
348       app_data_->setting_info()->sound_mode() ==
349           wgt::parse::SettingInfo::SoundMode::EXCLUSIVE) {
350     ewk_context_tizen_extensible_api_string_set(ewk_context_, kSoundModeFeature,
351                                                 true);
352   }
353
354   if (app_data_->setting_info() != NULL &&
355       app_data_->setting_info()->background_vibration()) {
356     ewk_context_tizen_extensible_api_string_set(
357         ewk_context_, kBackgroundVibrationFeature, true);
358   }
359
360   if (app_data_->widget_info() != NULL &&
361       !app_data_->widget_info()->default_locale().empty()) {
362     locale_manager_->SetDefaultLocale(
363         app_data_->widget_info()->default_locale());
364   }
365
366   if (app_data_->csp_info() != NULL || app_data_->csp_report_info() != NULL ||
367       app_data_->allowed_navigation_info() != NULL) {
368     security_model_version_ = 2;
369     if (app_data_->csp_info() == NULL ||
370         app_data_->csp_info()->security_rules().empty()) {
371       csp_rule_ = kDefaultCSPRule;
372     } else {
373       csp_rule_ = app_data_->csp_info()->security_rules();
374     }
375     if (app_data_->csp_report_info() != NULL &&
376         !app_data_->csp_report_info()->security_rules().empty()) {
377       csp_report_rule_ = app_data_->csp_report_info()->security_rules();
378     }
379     ewk_context_tizen_extensible_api_string_set(ewk_context_, kCSPFeature,
380                                                 EINA_TRUE);
381   } else {
382     security_model_version_ = 1;
383   }
384
385 #ifdef MANUAL_ROTATE_FEATURE_SUPPORT
386   // Set manual rotation
387   window_->EnableManualRotation(true);
388 #endif  // MANUAL_ROTATE_FEATURE_SUPPORT
389
390   return true;
391 }
392
393 void WebApplication::Launch(std::unique_ptr<common::AppControl> appcontrol) {
394   // send widget info to injected bundle
395   ewk_context_tizen_app_id_set(ewk_context_, appid_.c_str());
396
397   // Setup View
398   WebView* view = new WebView(window_, ewk_context_);
399   SetupWebView(view);
400
401   std::unique_ptr<common::ResourceManager::Resource> res =
402       resource_manager_->GetStartResource(appcontrol.get());
403   view->SetDefaultEncoding(res->encoding());
404
405   STEP_PROFILE_END("OnCreate -> URL Set");
406   STEP_PROFILE_START("URL Set -> Rendered");
407
408   window_->SetContent(view->evas_object());
409
410   // rotate and resize window forcibily for landscape mode.
411   // window rotate event is generated after window show. so
412   // when app get width and height from viewport, wrong value can be returned.
413   if (app_data_->setting_info()->screen_orientation() ==
414              wgt::parse::SettingInfo::ScreenOrientation::LANDSCAPE) {
415     LOGGER(DEBUG) << "rotate and resize window for landscape mode";
416     elm_win_rotation_with_resize_set(window_->evas_object(), 270);
417     evas_norender(evas_object_evas_get(window_->evas_object()));
418   }
419
420   view->LoadUrl(res->uri(), res->mime());
421   view_stack_.push_front(view);
422
423 #ifdef PROFILE_WEARABLE
424   // ewk_view_bg_color_set is not working at webview initialization.
425   if (app_data_->app_type() == common::ApplicationData::WATCH) {
426     view->SetBGColor(0, 0, 0, 255);
427   }
428 #endif  // PROFILE_WEARABLE
429
430   if (appcontrol->data(AUL_K_DEBUG) == "1") {
431     debug_mode_ = true;
432     LaunchInspector(appcontrol.get());
433   }
434   if (appcontrol->data(kVerboseKey) == "true") {
435     verbose_mode_ = true;
436   }
437
438   launched_ = true;
439 }
440
441 void WebApplication::AppControl(
442     std::unique_ptr<common::AppControl> appcontrol) {
443   std::unique_ptr<common::ResourceManager::Resource> res =
444       resource_manager_->GetStartResource(appcontrol.get());
445
446   bool do_reset = res->should_reset();
447
448   if (!do_reset) {
449     std::string current_page = view_stack_.front()->GetUrl();
450     std::string localized_page =
451         resource_manager_->GetLocalizedPath(res->uri());
452     if (current_page != localized_page) {
453       do_reset = true;
454     } else {
455       SendAppControlEvent();
456     }
457   }
458
459   // handle http://tizen.org/appcontrol/operation/main operation specially.
460   // only menu-screen app can send launch request with main operation.
461   // in this case, web app should have to resume web app not reset.
462   if (do_reset && (appcontrol->operation() == kAppControlMain)){
463     LOGGER(DEBUG) << "resume app for main operation";
464     do_reset = false;
465     SendAppControlEvent();
466   }
467
468   if (do_reset) {
469     // Reset to context
470     ClearViewStack();
471     WebView* view = view_stack_.front();
472     SetupWebView(view);
473     view->SetDefaultEncoding(res->encoding());
474     view->LoadUrl(res->uri(), res->mime());
475     window_->SetContent(view->evas_object());
476   }
477
478   if (!debug_mode_ && appcontrol->data(AUL_K_DEBUG) == "1") {
479     debug_mode_ = true;
480     LaunchInspector(appcontrol.get());
481   }
482   if (!verbose_mode_ && appcontrol->data(kVerboseKey) == "true") {
483     verbose_mode_ = true;
484   }
485   window_->Active();
486 }
487
488 void WebApplication::SendAppControlEvent() {
489   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
490     view_stack_.front()->EvalJavascript(kAppControlEventScript);
491 }
492
493 void WebApplication::ClearViewStack() {
494   window_->SetContent(NULL);
495   WebView* front = view_stack_.front();
496   auto it = view_stack_.begin();
497   for (; it != view_stack_.end(); ++it) {
498     if (*it != front) {
499       (*it)->Suspend();
500       delete *it;
501     }
502   }
503   view_stack_.clear();
504   view_stack_.push_front(front);
505 }
506
507 void WebApplication::Resume() {
508   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
509     view_stack_.front()->SetVisibility(true);
510
511   if (app_data_->setting_info() != NULL &&
512       app_data_->setting_info()->background_support_enabled()) {
513     return;
514   }
515
516   auto it = view_stack_.begin();
517   for (; it != view_stack_.end(); ++it) {
518     (*it)->Resume();
519   }
520 }
521
522 void WebApplication::Suspend() {
523   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
524     view_stack_.front()->SetVisibility(false);
525
526   if (app_data_->setting_info() != NULL &&
527       app_data_->setting_info()->background_support_enabled()) {
528     LOGGER(DEBUG) << "gone background (backgroud support enabed)";
529     return;
530   }
531
532   auto it = view_stack_.begin();
533   for (; it != view_stack_.end(); ++it) {
534     (*it)->Suspend();
535   }
536 }
537
538 void WebApplication::Terminate() {
539   if (terminator_) {
540     terminator_();
541   } else {
542     elm_exit();
543   }
544   auto extension_server = extensions::XWalkExtensionServer::GetInstance();
545   extension_server->Shutdown();
546 }
547
548 void WebApplication::OnCreatedNewWebView(WebView* /*view*/, WebView* new_view) {
549   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
550     view_stack_.front()->SetVisibility(false);
551
552   SetupWebView(new_view);
553   view_stack_.push_front(new_view);
554   window_->SetContent(new_view->evas_object());
555 }
556
557 void WebApplication::RemoveWebViewFromStack(WebView* view) {
558   if (view_stack_.size() == 0) return;
559
560   WebView* current = view_stack_.front();
561   if (current == view) {
562     view_stack_.pop_front();
563   } else {
564     auto found = std::find(view_stack_.begin(), view_stack_.end(), view);
565     if (found != view_stack_.end()) {
566       view_stack_.erase(found);
567     }
568   }
569
570   if (view_stack_.size() == 0) {
571     Terminate();
572   } else if (current != view_stack_.front()) {
573     view_stack_.front()->SetVisibility(true);
574     window_->SetContent(view_stack_.front()->evas_object());
575   }
576
577   // Delete after the callback context(for ewk view) was not used
578   ecore_idler_add([](void* view) {
579                     WebView* obj = static_cast<WebView*>(view);
580                     delete obj;
581                     return EINA_FALSE;
582                   },
583                   view);
584 }
585
586 void WebApplication::OnClosedWebView(WebView* view) {
587     RemoveWebViewFromStack(view);
588 }
589
590 void WebApplication::OnReceivedWrtMessage(WebView* /*view*/,
591                                           Ewk_IPC_Wrt_Message_Data* msg) {
592   Eina_Stringshare* msg_type = ewk_ipc_wrt_message_data_type_get(msg);
593
594 #define TYPE_BEGIN(x) (!strncmp(msg_type, x, strlen(x)))
595 #define TYPE_IS(x) (!strcmp(msg_type, x))
596
597   if (TYPE_BEGIN("xwalk://")) {
598     auto extension_server = extensions::XWalkExtensionServer::GetInstance();
599     extension_server->HandleIPCMessage(msg);
600   } else {
601     Eina_Stringshare* msg_id = ewk_ipc_wrt_message_data_id_get(msg);
602     Eina_Stringshare* msg_ref_id =
603         ewk_ipc_wrt_message_data_reference_id_get(msg);
604     Eina_Stringshare* msg_value = ewk_ipc_wrt_message_data_value_get(msg);
605
606     if (TYPE_IS("tizen://hide")) {
607       // One Way Message
608       window_->InActive();
609     } else if (TYPE_IS("tizen://exit")) {
610       // One Way Message
611       ecore_idler_add(ExitAppIdlerCallback, this);
612     } else if (TYPE_IS("tizen://changeUA")) {
613       // Async Message
614       // Change UserAgent of current WebView
615       bool ret = false;
616       if (view_stack_.size() > 0 && view_stack_.front() != NULL) {
617         ret = view_stack_.front()->SetUserAgent(std::string(msg_value));
618       }
619       // Send response
620       Ewk_IPC_Wrt_Message_Data* ans = ewk_ipc_wrt_message_data_new();
621       ewk_ipc_wrt_message_data_type_set(ans, msg_type);
622       ewk_ipc_wrt_message_data_reference_id_set(ans, msg_id);
623       if (ret)
624         ewk_ipc_wrt_message_data_value_set(ans, "success");
625       else
626         ewk_ipc_wrt_message_data_value_set(ans, "failed");
627       if (!ewk_ipc_wrt_message_send(ewk_context_, ans)) {
628         LOGGER(ERROR) << "Failed to send response";
629       }
630       ewk_ipc_wrt_message_data_del(ans);
631     } else if (TYPE_IS("tizen://deleteAllCookies")) {
632       Ewk_IPC_Wrt_Message_Data* ans = ewk_ipc_wrt_message_data_new();
633       ewk_ipc_wrt_message_data_type_set(ans, msg_type);
634       ewk_ipc_wrt_message_data_reference_id_set(ans, msg_id);
635       if (ClearCookie(ewk_context_))
636         ewk_ipc_wrt_message_data_value_set(ans, "success");
637       else
638         ewk_ipc_wrt_message_data_value_set(ans, "failed");
639       if (!ewk_ipc_wrt_message_send(ewk_context_, ans)) {
640         LOGGER(ERROR) << "Failed to send response";
641       }
642       ewk_ipc_wrt_message_data_del(ans);
643     } else if (TYPE_IS("tizen://hide_splash_screen")) {
644       splash_screen_->HideSplashScreen(SplashScreen::HideReason::CUSTOM);
645     }
646
647     eina_stringshare_del(msg_ref_id);
648     eina_stringshare_del(msg_id);
649     eina_stringshare_del(msg_value);
650   }
651
652 #undef TYPE_IS
653 #undef TYPE_BEGIN
654
655   eina_stringshare_del(msg_type);
656 }
657
658 void WebApplication::OnOrientationLock(
659     WebView* view, bool lock,
660     NativeWindow::ScreenOrientation preferred_rotation) {
661   if (view_stack_.size() == 0) return;
662
663   // Only top-most view can set the orientation relate operation
664   if (view_stack_.front() != view) return;
665
666   auto orientaion_setting =
667       app_data_->setting_info() != NULL
668           ? app_data_->setting_info()->screen_orientation()
669           :
670           wgt::parse::SettingInfo::ScreenOrientation::AUTO;
671   if (orientaion_setting != wgt::parse::SettingInfo::ScreenOrientation::AUTO) {
672     return;
673   }
674
675   if (lock) {
676     window_->SetRotationLock(preferred_rotation);
677   } else {
678     window_->SetAutoRotation();
679   }
680 }
681
682 void WebApplication::OnHardwareKey(WebView* view, const std::string& keyname) {
683   // NOTE: This code is added to enable back-key on remote URL
684   if (!common::utils::StartsWith(view->GetUrl(), kFileScheme)) {
685     if (kKeyNameBack == keyname) {
686       LOGGER(DEBUG) << "Back to previous page for remote URL";
687       if (!view->Backward()) {
688         RemoveWebViewFromStack(view_stack_.front());
689       }
690     }
691     return;
692   }
693
694   bool enabled = app_data_->setting_info() != NULL
695                      ? app_data_->setting_info()->hwkey_enabled()
696                      : true;
697   if (enabled && kKeyNameBack == keyname) {
698     view->EvalJavascript(kBackKeyEventScript);
699     // NOTE: This code is added for backward compatibility.
700     // If the 'backbutton_presence' is true, WebView should be navigated back.
701     if (app_data_->setting_info() &&
702         app_data_->setting_info()->backbutton_presence()) {
703       if (!view->Backward()) {
704         RemoveWebViewFromStack(view_stack_.front());
705       }
706     }
707   } else if (enabled && kKeyNameMenu == keyname) {
708     view->EvalJavascript(kMenuKeyEventScript);
709   }
710 }
711
712 void WebApplication::OnLanguageChanged() {
713   locale_manager_->UpdateSystemLocale();
714   ewk_context_cache_clear(ewk_context_);
715   auto it = view_stack_.begin();
716   for (; it != view_stack_.end(); ++it) {
717     (*it)->Reload();
718   }
719 }
720
721 void WebApplication::OnConsoleMessage(const std::string& msg, int level) {
722   static bool enabled = (getenv(kConsoleLogEnableKey) != NULL);
723   enabled = true;
724
725   std::string split_msg = msg;
726   std::size_t pos = msg.find(kResWgtPath);
727   if (pos != std::string::npos) {
728     split_msg = msg.substr(pos + strlen(kResWgtPath));
729   }
730
731   if (debug_mode_ || verbose_mode_ || enabled) {
732     int dlog_level = DLOG_DEBUG;
733     switch (level) {
734       case EWK_CONSOLE_MESSAGE_LEVEL_WARNING:
735         dlog_level = DLOG_WARN;
736         break;
737       case EWK_CONSOLE_MESSAGE_LEVEL_ERROR:
738         dlog_level = DLOG_ERROR;
739         break;
740       default:
741         dlog_level = DLOG_DEBUG;
742         break;
743     }
744     LOGGER_RAW(dlog_level, kConsoleMessageLogTag)
745       << "[" << app_data_->pkg_id() << "] " << split_msg;
746   }
747 }
748
749 void WebApplication::OnLowMemory() {
750   ewk_context_cache_clear(ewk_context_);
751   ewk_context_notify_low_memory(ewk_context_);
752 }
753
754 void WebApplication::OnSoftKeyboardChangeEvent(WebView* /*view*/,
755                                SoftKeyboardChangeEventValue softkeyboard_value) {
756   LOGGER(DEBUG) << "OnSoftKeyboardChangeEvent";
757   std::stringstream script;
758   script
759     << "(function(){"
760     << "var __event = document.createEvent(\"CustomEvent\");\n"
761     << "var __detail = {};\n"
762     << "__event.initCustomEvent(\"softkeyboardchange\",true,true,__detail);\n"
763     << "__event.state = \"" << softkeyboard_value.state << "\";\n"
764     << "__event.width = " << softkeyboard_value.width << ";\n"
765     << "__event.height = " << softkeyboard_value.height << ";\n"
766     << "document.dispatchEvent(__event);\n"
767     << "\n"
768     << "for (var i=0; i < window.frames.length; i++)\n"
769     << "{ window.frames[i].document.dispatchEvent(__event); }"
770     << "})()";
771   std::string kSoftKeyboardScript = script.str();
772   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
773     view_stack_.front()->EvalJavascript(kSoftKeyboardScript.c_str());
774 }
775
776 #ifdef ROTARY_EVENT_FEATURE_SUPPORT
777 void WebApplication::OnRotaryEvent(WebView* /*view*/,
778                                    RotaryEventType type) {
779   LOGGER(DEBUG) << "OnRotaryEvent";
780   std::stringstream script;
781   script
782     << "(function(){"
783     << "var __event = document.createEvent(\"CustomEvent\");\n"
784     << "var __detail = {};\n"
785     << "__event.initCustomEvent(\"rotarydetent\", true, true, __detail);\n"
786     << "__event.detail.direction = \""
787     << (type == RotaryEventType::CLOCKWISE ? "CW" : "CCW")
788     << "\";\n"
789     << "document.dispatchEvent(__event);\n"
790     << "\n"
791     << "for (var i=0; i < window.frames.length; i++)\n"
792     << "{ window.frames[i].document.dispatchEvent(__event); }"
793     << "})()";
794   std::string kRotaryEventScript = script.str();
795   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
796     view_stack_.front()->EvalJavascript(kRotaryEventScript.c_str());
797 }
798 #endif  // ROTARY_EVENT_FEATURE_SUPPORT
799
800 void WebApplication::OnTimeTick(long time) {
801 #if 0
802   LOGGER(DEBUG) << "TimeTick";
803   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
804     view_stack_.front()->EvalJavascript(kAmbientTickEventScript);
805 #endif
806 }
807
808 void WebApplication::OnAmbientTick(long time) {
809   LOGGER(DEBUG) << "AmbientTick";
810   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
811     view_stack_.front()->EvalJavascript(kAmbientTickEventScript);
812 }
813
814 void WebApplication::OnAmbientChanged(bool ambient_mode) {
815   LOGGER(DEBUG) << "AmbientChanged";
816   std::stringstream script;
817   script
818     << "(function(){"
819     << "var __event = document.createEvent(\"CustomEvent\");\n"
820     << "var __detail = {};\n"
821     << "__event.initCustomEvent(\"ambientmodechanged\",true,true,__detail);\n"
822     << "__event.detail.ambientMode = "
823     << (ambient_mode ? "true" : "false") << ";\n"
824     << "document.dispatchEvent(__event);\n"
825     << "\n"
826     << "for (var i=0; i < window.frames.length; i++)\n"
827     << "{ window.frames[i].document.dispatchEvent(__event); }"
828     << "})()";
829   std::string kAmbientChangedEventScript = script.str();
830   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
831     view_stack_.front()->EvalJavascript(kAmbientChangedEventScript.c_str());
832 }
833
834 bool WebApplication::OnContextMenuDisabled(WebView* /*view*/) {
835   return !(app_data_->setting_info() != NULL
836                ? app_data_->setting_info()->context_menu_enabled()
837                : true);
838 }
839
840 void WebApplication::OnLoadStart(WebView* /*view*/) {
841   LOGGER(DEBUG) << "LoadStart";
842 }
843
844 void WebApplication::OnLoadFinished(WebView* /*view*/) {
845   LOGGER(DEBUG) << "LoadFinished";
846   splash_screen_->HideSplashScreen(SplashScreen::HideReason::LOADFINISHED);
847 }
848
849 void WebApplication::OnRendered(WebView* /*view*/) {
850   STEP_PROFILE_END("URL Set -> Rendered");
851   STEP_PROFILE_END("Start -> Launch Completed");
852   LOGGER(DEBUG) << "Rendered";
853   splash_screen_->HideSplashScreen(SplashScreen::HideReason::RENDERED);
854
855   // Show window after frame rendered.
856   window_->Show();
857   window_->Active();
858 }
859
860 #ifdef MANUAL_ROTATE_FEATURE_SUPPORT
861 void WebApplication::OnRotatePrepared(WebView* /*view*/) {
862   window_->ManualRotationDone();
863 }
864 #endif  // MANUAL_ROTATE_FEATURE_SUPPORT
865
866 void WebApplication::LaunchInspector(common::AppControl* appcontrol) {
867   unsigned int port = ewk_context_inspector_server_start(ewk_context_, 0);
868   std::stringstream ss;
869   ss << port;
870   std::map<std::string, std::vector<std::string>> data;
871   data[kPortKey] = {ss.str()};
872   appcontrol->Reply(data);
873 }
874
875 void WebApplication::SetupWebView(WebView* view) {
876   view->SetEventListener(this);
877
878   // Setup CSP Rule
879   if (security_model_version_ == 2) {
880     view->SetCSPRule(csp_rule_, false);
881     if (!csp_report_rule_.empty()) {
882       view->SetCSPRule(csp_report_rule_, true);
883     }
884   }
885 }
886
887 bool WebApplication::OnDidNavigation(WebView* /*view*/,
888                                      const std::string& url) {
889   // scheme handling
890   // except(file , http, https, app) pass to appcontrol and return false
891   if (ProcessWellKnownScheme(url)) {
892     return false;
893   }
894
895   // send launch request for blocked URL to guarrenty backward-compatibility.
896   if (resource_manager_->AllowNavigation(url)) {
897     return true;
898   } else {
899     LOGGER(DEBUG) << "URL is blocked. send launch request for URL : " << url;
900     std::unique_ptr<common::AppControl> request(
901       common::AppControl::MakeAppcontrolFromURL(url));
902     if (request.get() == NULL || !request->LaunchRequest()) {
903       LOGGER(ERROR) << "Fail to send appcontrol request";
904     }
905     return false;
906   }
907 }
908
909 void WebApplication::OnNotificationPermissionRequest(
910     WebView*, const std::string& url,
911     std::function<void(bool)> result_handler) {
912   auto db = common::AppDB::GetInstance();
913   std::string reminder =
914       db->Get(kDBPrivateSection, kNotificationPermissionPrefix + url);
915   if (reminder == "allowed") {
916     result_handler(true);
917     return;
918   } else if (reminder == "denied") {
919     result_handler(false);
920     return;
921   }
922
923   // Local Domain: Grant permission if defined, otherwise Popup user prompt.
924   // Remote Domain: Popup user prompt.
925   if (common::utils::StartsWith(url, "file://") &&
926       FindPrivilege(app_data_, kNotificationPrivilege)) {
927     result_handler(true);
928     return;
929   }
930
931   Popup* popup = Popup::CreatePopup(window_);
932   popup->SetButtonType(Popup::ButtonType::AllowDenyButton);
933   popup->SetTitle(popup_string::kPopupTitleWebNotification);
934   popup->SetBody(popup_string::kPopupBodyWebNotification);
935   popup->SetCheckBox(popup_string::kPopupCheckRememberPreference);
936   popup->SetResultHandler(
937       [db, result_handler, url](Popup* popup, void* /*user_data*/) {
938         bool result = popup->GetButtonResult();
939         bool remember = popup->GetCheckBoxResult();
940         if (remember) {
941           db->Set(kDBPrivateSection, kNotificationPermissionPrefix + url,
942                   result ? "allowed" : "denied");
943         }
944         result_handler(result);
945       },
946       this);
947   popup->Show();
948 }
949
950 void WebApplication::OnGeolocationPermissionRequest(
951     WebView*, const std::string& url,
952     std::function<void(bool)> result_handler) {
953   auto db = common::AppDB::GetInstance();
954   std::string reminder =
955       db->Get(kDBPrivateSection, kGeolocationPermissionPrefix + url);
956   if (reminder == "allowed") {
957     result_handler(true);
958     return;
959   } else if (reminder == "denied") {
960     result_handler(false);
961     return;
962   }
963
964   // Local Domain: Grant permission if defined, otherwise block execution.
965   // Remote Domain: Popup user prompt if defined, otherwise block execution.
966   if (!FindPrivilege(app_data_, kLocationPrivilege)) {
967     result_handler(false);
968     return;
969   }
970
971   if (common::utils::StartsWith(url, "file://")) {
972     result_handler(true);
973     return;
974   }
975
976   Popup* popup = Popup::CreatePopup(window_);
977   popup->SetButtonType(Popup::ButtonType::AllowDenyButton);
978   popup->SetTitle(popup_string::kPopupTitleGeoLocation);
979   popup->SetBody(popup_string::kPopupBodyGeoLocation);
980   popup->SetCheckBox(popup_string::kPopupCheckRememberPreference);
981   popup->SetResultHandler(
982       [db, result_handler, url](Popup* popup, void* /*user_data*/) {
983         bool result = popup->GetButtonResult();
984         bool remember = popup->GetCheckBoxResult();
985         if (remember) {
986           db->Set(kDBPrivateSection, kGeolocationPermissionPrefix + url,
987                   result ? "allowed" : "denied");
988         }
989         result_handler(result);
990       },
991       this);
992   popup->Show();
993 }
994
995 void WebApplication::OnQuotaExceed(WebView*, const std::string& url,
996                                    std::function<void(bool)> result_handler) {
997   auto db = common::AppDB::GetInstance();
998   std::string reminder =
999       db->Get(kDBPrivateSection, kQuotaPermissionPrefix + url);
1000   if (reminder == "allowed") {
1001     result_handler(true);
1002     return;
1003   } else if (reminder == "denied") {
1004     result_handler(false);
1005     return;
1006   }
1007
1008   // Local Domain: Grant permission if defined, otherwise Popup user prompt.
1009   // Remote Domain: Popup user prompt.
1010   if (common::utils::StartsWith(url, "file://") &&
1011       FindPrivilege(app_data_, kStoragePrivilege)) {
1012     result_handler(true);
1013     return;
1014   }
1015
1016   Popup* popup = Popup::CreatePopup(window_);
1017   popup->SetButtonType(Popup::ButtonType::AllowDenyButton);
1018   popup->SetTitle(popup_string::kPopupTitleWebStorage);
1019   popup->SetBody(popup_string::kPopupBodyWebStorage);
1020   popup->SetCheckBox(popup_string::kPopupCheckRememberPreference);
1021   popup->SetResultHandler(
1022       [db, result_handler, url](Popup* popup, void* /*user_data*/) {
1023         bool result = popup->GetButtonResult();
1024         bool remember = popup->GetCheckBoxResult();
1025         if (remember) {
1026           db->Set(kDBPrivateSection, kQuotaPermissionPrefix + url,
1027                   result ? "allowed" : "denied");
1028         }
1029         result_handler(result);
1030       },
1031       this);
1032   popup->Show();
1033 }
1034
1035 void WebApplication::OnAuthenticationRequest(
1036     WebView*, const std::string& /*url*/, const std::string& /*message*/,
1037     std::function<void(bool submit, const std::string& id,
1038                        const std::string& password)> result_handler) {
1039   Popup* popup = Popup::CreatePopup(window_);
1040   popup->SetButtonType(Popup::ButtonType::LoginCancelButton);
1041   popup->SetFirstEntry(popup_string::kPopupLabelAuthusername,
1042                        Popup::EntryType::Edit);
1043   popup->SetSecondEntry(popup_string::kPopupLabelPassword,
1044                         Popup::EntryType::PwEdit);
1045   popup->SetTitle(popup_string::kPopupTitleAuthRequest);
1046   popup->SetBody(popup_string::kPopupBodyAuthRequest);
1047   popup->SetResultHandler([result_handler](Popup* popup, void* /*user_data*/) {
1048                             bool result = popup->GetButtonResult();
1049                             std::string id = popup->GetFirstEntryResult();
1050                             std::string passwd = popup->GetSecondEntryResult();
1051                             result_handler(result, id, passwd);
1052                           },
1053                           this);
1054   popup->Show();
1055 }
1056
1057 void WebApplication::OnCertificateAllowRequest(
1058     WebView*, const std::string& url, const std::string& pem,
1059     std::function<void(bool allow)> result_handler) {
1060   auto db = common::AppDB::GetInstance();
1061   std::string reminder =
1062       db->Get(kDBPrivateSection, kCertificateAllowPrefix + pem);
1063   if (reminder == "allowed") {
1064     result_handler(true);
1065     return;
1066   } else if (reminder == "denied") {
1067     result_handler(false);
1068     return;
1069   }
1070
1071   Popup* popup = Popup::CreatePopup(window_);
1072   popup->SetButtonType(Popup::ButtonType::AllowDenyButton);
1073   popup->SetTitle(popup_string::kPopupTitleCert);
1074   popup->SetBody(popup_string::GetText(
1075                  popup_string::kPopupBodyCert) + "\n\n" + url);
1076   popup->SetCheckBox(popup_string::kPopupCheckRememberPreference);
1077   popup->SetResultHandler(
1078       [db, result_handler, pem](Popup* popup, void* /*user_data*/) {
1079         bool result = popup->GetButtonResult();
1080         bool remember = popup->GetCheckBoxResult();
1081         if (remember) {
1082           db->Set(kDBPrivateSection, kCertificateAllowPrefix + pem,
1083                   result ? "allowed" : "denied");
1084         }
1085         result_handler(result);
1086       },
1087       this);
1088   popup->Show();
1089 }
1090
1091 void WebApplication::OnUsermediaPermissionRequest(
1092     WebView*, const std::string& url,
1093     std::function<void(bool)> result_handler) {
1094   auto db = common::AppDB::GetInstance();
1095   std::string reminder =
1096       db->Get(kDBPrivateSection, kUsermediaPermissionPrefix + url);
1097   if (reminder == "allowed") {
1098     result_handler(true);
1099     return;
1100   } else if (reminder == "denied") {
1101     result_handler(false);
1102     return;
1103   }
1104
1105   // Local Domain: Grant permission if defined, otherwise block execution.
1106   // Remote Domain: Popup user prompt if defined, otherwise block execution.
1107   if (!FindPrivilege(app_data_, kUsermediaPrivilege)) {
1108     result_handler(false);
1109     return;
1110   }
1111
1112   if (common::utils::StartsWith(url, "file://")) {
1113     result_handler(true);
1114     return;
1115   }
1116
1117   Popup* popup = Popup::CreatePopup(window_);
1118   popup->SetButtonType(Popup::ButtonType::AllowDenyButton);
1119   popup->SetTitle(popup_string::kPopupTitleUserMedia);
1120   popup->SetBody(popup_string::kPopupBodyUserMedia);
1121   popup->SetCheckBox(popup_string::kPopupCheckRememberPreference);
1122   popup->SetResultHandler(
1123       [db, result_handler, url](Popup* popup, void* /*user_data*/) {
1124         bool result = popup->GetButtonResult();
1125         bool remember = popup->GetCheckBoxResult();
1126         if (remember) {
1127           db->Set(kDBPrivateSection, kUsermediaPermissionPrefix + url,
1128                   result ? "allowed" : "denied");
1129         }
1130         result_handler(result);
1131       },
1132       this);
1133   popup->Show();
1134 }
1135
1136 }  // namespace runtime