modify to send the key to web app
[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       lang_changed_mode_(false),
224       ewk_context_(
225           ewk_context_new_with_injected_bundle_path(INJECTED_BUNDLE_PATH)),
226       has_ownership_of_ewk_context_(true),
227       window_(window),
228       appid_(app_data->app_id()),
229       app_data_(app_data),
230       locale_manager_(new common::LocaleManager()),
231       terminator_(NULL) {
232   Initialize();
233 }
234
235 WebApplication::WebApplication(
236     NativeWindow* window,
237     common::ApplicationData* app_data,
238     Ewk_Context* context)
239     : launched_(false),
240       debug_mode_(false),
241       verbose_mode_(false),
242       ewk_context_(context),
243       has_ownership_of_ewk_context_(false),
244       window_(window),
245       appid_(app_data->app_id()),
246       app_data_(app_data),
247       locale_manager_(new common::LocaleManager()),
248       terminator_(NULL) {
249   Initialize();
250 }
251
252 WebApplication::~WebApplication() {
253   window_->SetContent(NULL);
254   auto it = view_stack_.begin();
255   for (; it != view_stack_.end(); ++it) {
256     delete *it;
257   }
258   view_stack_.clear();
259   if (ewk_context_ && has_ownership_of_ewk_context_)
260     ewk_context_delete(ewk_context_);
261 }
262
263 bool WebApplication::Initialize() {
264   SCOPE_PROFILE();
265   std::unique_ptr<char, decltype(std::free)*> path{app_get_data_path(),
266                                                    std::free};
267   app_data_path_ = path.get();
268
269   if (app_data_->setting_info() != NULL &&
270       app_data_->setting_info()->screen_orientation() ==
271           wgt::parse::SettingInfo::ScreenOrientation::AUTO) {
272     ewk_context_tizen_extensible_api_string_set(ewk_context_,
273                                                 kRotationLockFeature, true);
274     window_->SetAutoRotation();
275   } else if (app_data_->setting_info() != NULL &&
276              app_data_->setting_info()->screen_orientation() ==
277                  wgt::parse::SettingInfo::ScreenOrientation::PORTRAIT) {
278     window_->SetRotationLock(NativeWindow::ScreenOrientation::PORTRAIT_PRIMARY);
279   } else if (app_data_->setting_info() != NULL &&
280              app_data_->setting_info()->screen_orientation() ==
281                  wgt::parse::SettingInfo::ScreenOrientation::LANDSCAPE) {
282     window_->SetRotationLock(
283         NativeWindow::ScreenOrientation::LANDSCAPE_PRIMARY);
284   }
285
286   splash_screen_.reset(new SplashScreen(
287       window_, app_data_->splash_screen_info(), app_data_->application_path()));
288   resource_manager_.reset(
289       new common::ResourceManager(app_data_, locale_manager_.get()));
290   resource_manager_->set_base_resource_path(app_data_->application_path());
291
292   auto extension_server = extensions::XWalkExtensionServer::GetInstance();
293   extension_server->SetupIPC(ewk_context_);
294
295   // ewk setting
296   ewk_context_cache_model_set(ewk_context_, EWK_CACHE_MODEL_DOCUMENT_BROWSER);
297
298   // cookie
299   auto cookie_manager = ewk_context_cookie_manager_get(ewk_context_);
300   ewk_cookie_manager_accept_policy_set(cookie_manager,
301                                        EWK_COOKIE_ACCEPT_POLICY_ALWAYS);
302
303   // set persistent storage path
304   std::string cookie_path = data_path() + ".cookie";
305   ewk_cookie_manager_persistent_storage_set(
306       cookie_manager, cookie_path.c_str(),
307       EWK_COOKIE_PERSISTENT_STORAGE_SQLITE);
308
309   // vibration callback
310   auto vibration_start_callback = [](uint64_t ms, void*) {
311     platform::VibrationManager::GetInstance()->Start(static_cast<int>(ms));
312   };
313   auto vibration_stop_callback = [](void* /*user_data*/) {
314     platform::VibrationManager::GetInstance()->Stop();
315   };
316   ewk_context_vibration_client_callbacks_set(
317       ewk_context_, vibration_start_callback, vibration_stop_callback, NULL);
318
319   auto download_callback = [](const char* downloadUrl, void* /*data*/) {
320     SendDownloadRequest(downloadUrl);
321   };
322   ewk_context_did_start_download_callback_set(ewk_context_, download_callback,
323                                               this);
324   InitializeNotificationCallback(ewk_context_, this);
325
326   if (FindPrivilege(app_data_, kFullscreenPrivilege)) {
327     ewk_context_tizen_extensible_api_string_set(ewk_context_,
328                                                 kFullscreenFeature, true);
329   }
330
331   if (app_data_->setting_info() != NULL &&
332       app_data_->setting_info()->background_support_enabled()) {
333     ewk_context_tizen_extensible_api_string_set(
334                                 ewk_context_, kVisibilitySuspendFeature, true);
335     ewk_context_tizen_extensible_api_string_set(ewk_context_,
336                                                 kBackgroundMusicFeature, true);
337   } else {
338     ewk_context_tizen_extensible_api_string_set(
339                                ewk_context_, kVisibilitySuspendFeature, false);
340     ewk_context_tizen_extensible_api_string_set(ewk_context_,
341                                                kBackgroundMusicFeature, false);
342   }
343   ewk_context_tizen_extensible_api_string_set(ewk_context_,
344                                               kMediastreamRecordFeature, true);
345   ewk_context_tizen_extensible_api_string_set(ewk_context_,
346                                               kEncryptedDatabaseFeature, true);
347
348   if (app_data_->setting_info() != NULL &&
349       app_data_->setting_info()->sound_mode() ==
350           wgt::parse::SettingInfo::SoundMode::EXCLUSIVE) {
351     ewk_context_tizen_extensible_api_string_set(ewk_context_, kSoundModeFeature,
352                                                 true);
353   }
354
355   if (app_data_->setting_info() != NULL &&
356       app_data_->setting_info()->background_vibration()) {
357     ewk_context_tizen_extensible_api_string_set(
358         ewk_context_, kBackgroundVibrationFeature, true);
359   }
360
361   if (app_data_->widget_info() != NULL &&
362       !app_data_->widget_info()->default_locale().empty()) {
363     locale_manager_->SetDefaultLocale(
364         app_data_->widget_info()->default_locale());
365   }
366
367   if (app_data_->csp_info() != NULL || app_data_->csp_report_info() != NULL ||
368       app_data_->allowed_navigation_info() != NULL) {
369     security_model_version_ = 2;
370     if (app_data_->csp_info() == NULL ||
371         app_data_->csp_info()->security_rules().empty()) {
372       csp_rule_ = kDefaultCSPRule;
373     } else {
374       csp_rule_ = app_data_->csp_info()->security_rules();
375     }
376     if (app_data_->csp_report_info() != NULL &&
377         !app_data_->csp_report_info()->security_rules().empty()) {
378       csp_report_rule_ = app_data_->csp_report_info()->security_rules();
379     }
380     ewk_context_tizen_extensible_api_string_set(ewk_context_, kCSPFeature,
381                                                 EINA_TRUE);
382   } else {
383     security_model_version_ = 1;
384   }
385
386 #ifdef MANUAL_ROTATE_FEATURE_SUPPORT
387   // Set manual rotation
388   window_->EnableManualRotation(true);
389 #endif  // MANUAL_ROTATE_FEATURE_SUPPORT
390
391   return true;
392 }
393
394 void WebApplication::Launch(std::unique_ptr<common::AppControl> appcontrol) {
395   // send widget info to injected bundle
396   ewk_context_tizen_app_id_set(ewk_context_, appid_.c_str());
397
398   // Setup View
399   WebView* view = new WebView(window_, ewk_context_);
400   SetupWebView(view);
401
402   std::unique_ptr<common::ResourceManager::Resource> res =
403       resource_manager_->GetStartResource(appcontrol.get());
404   view->SetDefaultEncoding(res->encoding());
405
406   STEP_PROFILE_END("OnCreate -> URL Set");
407   STEP_PROFILE_START("URL Set -> Rendered");
408
409   window_->SetContent(view->evas_object());
410
411 #ifdef PROFILE_MOBILE
412   // rotate and resize window forcibily for landscape mode.
413   // window rotate event is generated after window show. so
414   // when app get width and height from viewport, wrong value can be returned.
415   if (app_data_->setting_info()->screen_orientation() ==
416              wgt::parse::SettingInfo::ScreenOrientation::LANDSCAPE) {
417     LOGGER(DEBUG) << "rotate and resize window for landscape mode";
418     elm_win_rotation_with_resize_set(window_->evas_object(), 270);
419     evas_norender(evas_object_evas_get(window_->evas_object()));
420   }
421 #endif  // PROFILE_MOBILE
422
423   view->LoadUrl(res->uri(), res->mime());
424   view_stack_.push_front(view);
425
426 #ifdef PROFILE_WEARABLE
427   // ewk_view_bg_color_set is not working at webview initialization.
428   if (app_data_->app_type() == common::ApplicationData::WATCH) {
429     view->SetBGColor(0, 0, 0, 255);
430   }
431 #endif  // PROFILE_WEARABLE
432
433   if (appcontrol->data(AUL_K_DEBUG) == "1") {
434     debug_mode_ = true;
435     LaunchInspector(appcontrol.get());
436   }
437   if (appcontrol->data(kVerboseKey) == "true") {
438     verbose_mode_ = true;
439   }
440
441   launched_ = true;
442 }
443
444 void WebApplication::AppControl(
445     std::unique_ptr<common::AppControl> appcontrol) {
446   std::unique_ptr<common::ResourceManager::Resource> res =
447       resource_manager_->GetStartResource(appcontrol.get());
448
449   bool do_reset = res->should_reset();
450
451   if (!do_reset) {
452     std::string current_page = view_stack_.front()->GetUrl();
453     std::string localized_page = res->uri();
454
455     if (current_page != localized_page) {
456       do_reset = true;
457     } else {
458       SendAppControlEvent();
459     }
460   }
461
462   // handle http://tizen.org/appcontrol/operation/main operation specially.
463   // only menu-screen app can send launch request with main operation.
464   // in this case, web app should have to resume web app not reset.
465   if (do_reset && (appcontrol->operation() == kAppControlMain)){
466     LOGGER(DEBUG) << "resume app for main operation";
467     do_reset = false;
468     SendAppControlEvent();
469   }
470
471   if (do_reset) {
472     // Reset to context
473     ClearViewStack();
474     WebView* view = view_stack_.front();
475     SetupWebView(view);
476     view->SetDefaultEncoding(res->encoding());
477     view->LoadUrl(res->uri(), res->mime());
478     window_->SetContent(view->evas_object());
479   }
480
481   if (!debug_mode_ && appcontrol->data(AUL_K_DEBUG) == "1") {
482     debug_mode_ = true;
483     LaunchInspector(appcontrol.get());
484   }
485   if (!verbose_mode_ && appcontrol->data(kVerboseKey) == "true") {
486     verbose_mode_ = true;
487   }
488   window_->Active();
489 }
490
491 void WebApplication::SendAppControlEvent() {
492   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
493     view_stack_.front()->EvalJavascript(kAppControlEventScript);
494 }
495
496 void WebApplication::ClearViewStack() {
497   window_->SetContent(NULL);
498   WebView* front = view_stack_.front();
499   auto it = view_stack_.begin();
500   for (; it != view_stack_.end(); ++it) {
501     if (*it != front) {
502       (*it)->Suspend();
503       delete *it;
504     }
505   }
506   view_stack_.clear();
507   view_stack_.push_front(front);
508 }
509
510 void WebApplication::Resume() {
511   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
512     view_stack_.front()->SetVisibility(true);
513
514   if (app_data_->setting_info() != NULL &&
515       app_data_->setting_info()->background_support_enabled()) {
516     return;
517   }
518
519   auto it = view_stack_.begin();
520   for (; it != view_stack_.end(); ++it) {
521     (*it)->Resume();
522   }
523 }
524
525 void WebApplication::Suspend() {
526   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
527     view_stack_.front()->SetVisibility(false);
528
529   if (app_data_->setting_info() != NULL &&
530       app_data_->setting_info()->background_support_enabled()) {
531     LOGGER(DEBUG) << "gone background (backgroud support enabed)";
532     return;
533   }
534
535   auto it = view_stack_.begin();
536   for (; it != view_stack_.end(); ++it) {
537     (*it)->Suspend();
538   }
539 }
540
541 void WebApplication::Terminate() {
542   if (terminator_) {
543     terminator_();
544   } else {
545     elm_exit();
546   }
547   auto extension_server = extensions::XWalkExtensionServer::GetInstance();
548   extension_server->Shutdown();
549 }
550
551 void WebApplication::OnCreatedNewWebView(WebView* /*view*/, WebView* new_view) {
552   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
553     view_stack_.front()->SetVisibility(false);
554
555   SetupWebView(new_view);
556   view_stack_.push_front(new_view);
557   window_->SetContent(new_view->evas_object());
558 }
559
560 void WebApplication::RemoveWebViewFromStack(WebView* view) {
561   if (view_stack_.size() == 0) return;
562
563   WebView* current = view_stack_.front();
564   if (current == view) {
565     view_stack_.pop_front();
566   } else {
567     auto found = std::find(view_stack_.begin(), view_stack_.end(), view);
568     if (found != view_stack_.end()) {
569       view_stack_.erase(found);
570     }
571   }
572
573   if (view_stack_.size() == 0) {
574     Terminate();
575   } else if (current != view_stack_.front()) {
576     view_stack_.front()->SetVisibility(true);
577     window_->SetContent(view_stack_.front()->evas_object());
578   }
579
580   // Delete after the callback context(for ewk view) was not used
581   ecore_idler_add([](void* view) {
582                     WebView* obj = static_cast<WebView*>(view);
583                     delete obj;
584                     return EINA_FALSE;
585                   },
586                   view);
587 }
588
589 void WebApplication::OnClosedWebView(WebView* view) {
590     RemoveWebViewFromStack(view);
591 }
592
593 void WebApplication::OnReceivedWrtMessage(WebView* /*view*/,
594                                           Ewk_IPC_Wrt_Message_Data* msg) {
595   Eina_Stringshare* msg_type = ewk_ipc_wrt_message_data_type_get(msg);
596
597 #define TYPE_BEGIN(x) (!strncmp(msg_type, x, strlen(x)))
598 #define TYPE_IS(x) (!strcmp(msg_type, x))
599
600   if (TYPE_BEGIN("xwalk://")) {
601     auto extension_server = extensions::XWalkExtensionServer::GetInstance();
602     extension_server->HandleIPCMessage(msg);
603   } else {
604     Eina_Stringshare* msg_id = ewk_ipc_wrt_message_data_id_get(msg);
605     Eina_Stringshare* msg_ref_id =
606         ewk_ipc_wrt_message_data_reference_id_get(msg);
607     Eina_Stringshare* msg_value = ewk_ipc_wrt_message_data_value_get(msg);
608
609     if (TYPE_IS("tizen://hide")) {
610       // One Way Message
611       window_->InActive();
612     } else if (TYPE_IS("tizen://exit")) {
613       // One Way Message
614       ecore_idler_add(ExitAppIdlerCallback, this);
615     } else if (TYPE_IS("tizen://changeUA")) {
616       // Async Message
617       // Change UserAgent of current WebView
618       bool ret = false;
619       if (view_stack_.size() > 0 && view_stack_.front() != NULL) {
620         ret = view_stack_.front()->SetUserAgent(std::string(msg_value));
621       }
622       // Send response
623       Ewk_IPC_Wrt_Message_Data* ans = ewk_ipc_wrt_message_data_new();
624       ewk_ipc_wrt_message_data_type_set(ans, msg_type);
625       ewk_ipc_wrt_message_data_reference_id_set(ans, msg_id);
626       if (ret)
627         ewk_ipc_wrt_message_data_value_set(ans, "success");
628       else
629         ewk_ipc_wrt_message_data_value_set(ans, "failed");
630       if (!ewk_ipc_wrt_message_send(ewk_context_, ans)) {
631         LOGGER(ERROR) << "Failed to send response";
632       }
633       ewk_ipc_wrt_message_data_del(ans);
634     } else if (TYPE_IS("tizen://deleteAllCookies")) {
635       Ewk_IPC_Wrt_Message_Data* ans = ewk_ipc_wrt_message_data_new();
636       ewk_ipc_wrt_message_data_type_set(ans, msg_type);
637       ewk_ipc_wrt_message_data_reference_id_set(ans, msg_id);
638       if (ClearCookie(ewk_context_))
639         ewk_ipc_wrt_message_data_value_set(ans, "success");
640       else
641         ewk_ipc_wrt_message_data_value_set(ans, "failed");
642       if (!ewk_ipc_wrt_message_send(ewk_context_, ans)) {
643         LOGGER(ERROR) << "Failed to send response";
644       }
645       ewk_ipc_wrt_message_data_del(ans);
646     } else if (TYPE_IS("tizen://hide_splash_screen")) {
647       splash_screen_->HideSplashScreen(SplashScreen::HideReason::CUSTOM);
648     }
649
650     eina_stringshare_del(msg_ref_id);
651     eina_stringshare_del(msg_id);
652     eina_stringshare_del(msg_value);
653   }
654
655 #undef TYPE_IS
656 #undef TYPE_BEGIN
657
658   eina_stringshare_del(msg_type);
659 }
660
661 void WebApplication::OnOrientationLock(
662     WebView* view, bool lock,
663     NativeWindow::ScreenOrientation preferred_rotation) {
664   if (view_stack_.size() == 0) return;
665
666   // Only top-most view can set the orientation relate operation
667   if (view_stack_.front() != view) return;
668
669   auto orientaion_setting =
670       app_data_->setting_info() != NULL
671           ? app_data_->setting_info()->screen_orientation()
672           :
673           wgt::parse::SettingInfo::ScreenOrientation::AUTO;
674   if (orientaion_setting != wgt::parse::SettingInfo::ScreenOrientation::AUTO) {
675     return;
676   }
677
678   if (lock) {
679     window_->SetRotationLock(preferred_rotation);
680   } else {
681     window_->SetAutoRotation();
682   }
683 }
684
685 void WebApplication::OnHardwareKey(WebView* view, const std::string& keyname) {
686   // NOTE: This code is added to enable back-key on remote URL
687   bool enabled = app_data_->setting_info() != NULL
688                      ? app_data_->setting_info()->hwkey_enabled()
689                      : true;
690
691   if (!common::utils::StartsWith(view->GetUrl(), kFileScheme)) {
692     if (kKeyNameBack == keyname) {
693       LOGGER(DEBUG) << "Back to previous page for remote URL";
694       if (!view->Backward()) {
695         if(enabled)
696           view->EvalJavascript(kBackKeyEventScript);
697         RemoveWebViewFromStack(view_stack_.front());
698       }
699     }
700     return;
701   }
702
703   if (enabled && kKeyNameBack == keyname) {
704     view->EvalJavascript(kBackKeyEventScript);
705     // NOTE: This code is added for backward compatibility.
706     // If the 'backbutton_presence' is true, WebView should be navigated back.
707     if (app_data_->setting_info() &&
708         app_data_->setting_info()->backbutton_presence()) {
709       if (!view->Backward()) {
710         RemoveWebViewFromStack(view_stack_.front());
711       }
712     }
713   } else if (enabled && kKeyNameMenu == keyname) {
714     view->EvalJavascript(kMenuKeyEventScript);
715   }
716 }
717
718 void WebApplication::OnLanguageChanged() {
719   lang_changed_mode_ = true;
720   locale_manager_->UpdateSystemLocale();
721   ewk_context_cache_clear(ewk_context_);
722   auto it = view_stack_.begin();
723   for (; it != view_stack_.end(); ++it) {
724     (*it)->Reload();
725   }
726 }
727
728 void WebApplication::OnConsoleMessage(const std::string& msg, int level) {
729   static bool enabled = (getenv(kConsoleLogEnableKey) != NULL);
730   enabled = true;
731
732   std::string split_msg = msg;
733   std::size_t pos = msg.find(kResWgtPath);
734   if (pos != std::string::npos) {
735     split_msg = msg.substr(pos + strlen(kResWgtPath));
736   }
737
738   if (debug_mode_ || verbose_mode_ || enabled) {
739     int dlog_level = DLOG_DEBUG;
740     switch (level) {
741       case EWK_CONSOLE_MESSAGE_LEVEL_WARNING:
742         dlog_level = DLOG_WARN;
743         break;
744       case EWK_CONSOLE_MESSAGE_LEVEL_ERROR:
745         dlog_level = DLOG_ERROR;
746         break;
747       default:
748         dlog_level = DLOG_DEBUG;
749         break;
750     }
751     LOGGER_RAW(dlog_level, kConsoleMessageLogTag)
752       << "[" << app_data_->pkg_id() << "] " << split_msg;
753   }
754 }
755
756 void WebApplication::OnLowMemory() {
757   ewk_context_cache_clear(ewk_context_);
758   ewk_context_notify_low_memory(ewk_context_);
759 }
760
761 void WebApplication::OnSoftKeyboardChangeEvent(WebView* /*view*/,
762                                SoftKeyboardChangeEventValue softkeyboard_value) {
763   LOGGER(DEBUG) << "OnSoftKeyboardChangeEvent";
764   std::stringstream script;
765   script
766     << "(function(){"
767     << "var __event = document.createEvent(\"CustomEvent\");\n"
768     << "var __detail = {};\n"
769     << "__event.initCustomEvent(\"softkeyboardchange\",true,true,__detail);\n"
770     << "__event.state = \"" << softkeyboard_value.state << "\";\n"
771     << "__event.width = " << softkeyboard_value.width << ";\n"
772     << "__event.height = " << softkeyboard_value.height << ";\n"
773     << "document.dispatchEvent(__event);\n"
774     << "\n"
775     << "for (var i=0; i < window.frames.length; i++)\n"
776     << "{ window.frames[i].document.dispatchEvent(__event); }"
777     << "})()";
778   std::string kSoftKeyboardScript = script.str();
779   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
780     view_stack_.front()->EvalJavascript(kSoftKeyboardScript.c_str());
781 }
782
783 #ifdef ROTARY_EVENT_FEATURE_SUPPORT
784 void WebApplication::OnRotaryEvent(WebView* /*view*/,
785                                    RotaryEventType type) {
786   LOGGER(DEBUG) << "OnRotaryEvent";
787   std::stringstream script;
788   script
789     << "(function(){"
790     << "var __event = document.createEvent(\"CustomEvent\");\n"
791     << "var __detail = {};\n"
792     << "__event.initCustomEvent(\"rotarydetent\", true, true, __detail);\n"
793     << "__event.detail.direction = \""
794     << (type == RotaryEventType::CLOCKWISE ? "CW" : "CCW")
795     << "\";\n"
796     << "document.dispatchEvent(__event);\n"
797     << "\n"
798     << "for (var i=0; i < window.frames.length; i++)\n"
799     << "{ window.frames[i].document.dispatchEvent(__event); }"
800     << "})()";
801   std::string kRotaryEventScript = script.str();
802   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
803     view_stack_.front()->EvalJavascript(kRotaryEventScript.c_str());
804 }
805 #endif  // ROTARY_EVENT_FEATURE_SUPPORT
806
807 void WebApplication::OnTimeTick(long time) {
808 #if 0
809   LOGGER(DEBUG) << "TimeTick";
810   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
811     view_stack_.front()->EvalJavascript(kAmbientTickEventScript);
812 #endif
813 }
814
815 void WebApplication::OnAmbientTick(long time) {
816   LOGGER(DEBUG) << "AmbientTick";
817   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
818     view_stack_.front()->EvalJavascript(kAmbientTickEventScript);
819 }
820
821 void WebApplication::OnAmbientChanged(bool ambient_mode) {
822   LOGGER(DEBUG) << "AmbientChanged";
823   std::stringstream script;
824   script
825     << "(function(){"
826     << "var __event = document.createEvent(\"CustomEvent\");\n"
827     << "var __detail = {};\n"
828     << "__event.initCustomEvent(\"ambientmodechanged\",true,true,__detail);\n"
829     << "__event.detail.ambientMode = "
830     << (ambient_mode ? "true" : "false") << ";\n"
831     << "document.dispatchEvent(__event);\n"
832     << "\n"
833     << "for (var i=0; i < window.frames.length; i++)\n"
834     << "{ window.frames[i].document.dispatchEvent(__event); }"
835     << "})()";
836   std::string kAmbientChangedEventScript = script.str();
837   if (view_stack_.size() > 0 && view_stack_.front() != NULL)
838     view_stack_.front()->EvalJavascript(kAmbientChangedEventScript.c_str());
839 }
840
841 bool WebApplication::OnContextMenuDisabled(WebView* /*view*/) {
842   return !(app_data_->setting_info() != NULL
843                ? app_data_->setting_info()->context_menu_enabled()
844                : true);
845 }
846
847 void WebApplication::OnLoadStart(WebView* /*view*/) {
848   LOGGER(DEBUG) << "LoadStart";
849 }
850
851 void WebApplication::OnLoadFinished(WebView* /*view*/) {
852   LOGGER(DEBUG) << "LoadFinished";
853   splash_screen_->HideSplashScreen(SplashScreen::HideReason::LOADFINISHED);
854 }
855
856 void WebApplication::OnRendered(WebView* /*view*/) {
857   STEP_PROFILE_END("URL Set -> Rendered");
858   STEP_PROFILE_END("Start -> Launch Completed");
859   LOGGER(DEBUG) << "Rendered";
860   splash_screen_->HideSplashScreen(SplashScreen::HideReason::RENDERED);
861
862   // Do not show(), active() for language change
863   if(lang_changed_mode_ == false){
864       // Show window after frame rendered.
865       window_->Show();
866       window_->Active();
867   }
868   else{
869       lang_changed_mode_ = false;
870   }
871 }
872
873 #ifdef MANUAL_ROTATE_FEATURE_SUPPORT
874 void WebApplication::OnRotatePrepared(WebView* /*view*/) {
875   window_->ManualRotationDone();
876 }
877 #endif  // MANUAL_ROTATE_FEATURE_SUPPORT
878
879 void WebApplication::LaunchInspector(common::AppControl* appcontrol) {
880   unsigned int port = ewk_context_inspector_server_start(ewk_context_, 0);
881   std::stringstream ss;
882   ss << port;
883   std::map<std::string, std::vector<std::string>> data;
884   data[kPortKey] = {ss.str()};
885   appcontrol->Reply(data);
886 }
887
888 void WebApplication::SetupWebView(WebView* view) {
889   view->SetEventListener(this);
890
891   // Setup CSP Rule
892   if (security_model_version_ == 2) {
893     view->SetCSPRule(csp_rule_, false);
894     if (!csp_report_rule_.empty()) {
895       view->SetCSPRule(csp_report_rule_, true);
896     }
897   }
898 }
899
900 bool WebApplication::OnDidNavigation(WebView* /*view*/,
901                                      const std::string& url) {
902   // scheme handling
903   // except(file , http, https, app) pass to appcontrol and return false
904   if (ProcessWellKnownScheme(url)) {
905     return false;
906   }
907
908   // send launch request for blocked URL to guarrenty backward-compatibility.
909   if (resource_manager_->AllowNavigation(url)) {
910     return true;
911   } else {
912     LOGGER(DEBUG) << "URL is blocked. send launch request for URL : " << url;
913     std::unique_ptr<common::AppControl> request(
914       common::AppControl::MakeAppcontrolFromURL(url));
915     if (request.get() == NULL || !request->LaunchRequest()) {
916       LOGGER(ERROR) << "Fail to send appcontrol request";
917     }
918     return false;
919   }
920 }
921
922 void WebApplication::OnNotificationPermissionRequest(
923     WebView*, const std::string& url,
924     std::function<void(bool)> result_handler) {
925   auto db = common::AppDB::GetInstance();
926   std::string reminder =
927       db->Get(kDBPrivateSection, kNotificationPermissionPrefix + url);
928   if (reminder == "allowed") {
929     result_handler(true);
930     return;
931   } else if (reminder == "denied") {
932     result_handler(false);
933     return;
934   }
935
936   // Local Domain: Grant permission if defined, otherwise Popup user prompt.
937   // Remote Domain: Popup user prompt.
938   if (common::utils::StartsWith(url, "file://") &&
939       FindPrivilege(app_data_, kNotificationPrivilege)) {
940     result_handler(true);
941     return;
942   }
943
944   Popup* popup = Popup::CreatePopup(window_);
945   popup->SetButtonType(Popup::ButtonType::AllowDenyButton);
946   popup->SetTitle(popup_string::kPopupTitleWebNotification);
947   popup->SetBody(popup_string::kPopupBodyWebNotification);
948   popup->SetCheckBox(popup_string::kPopupCheckRememberPreference);
949   popup->SetResultHandler(
950       [db, result_handler, url](Popup* popup, void* /*user_data*/) {
951         bool result = popup->GetButtonResult();
952         bool remember = popup->GetCheckBoxResult();
953         if (remember) {
954           db->Set(kDBPrivateSection, kNotificationPermissionPrefix + url,
955                   result ? "allowed" : "denied");
956         }
957         result_handler(result);
958       },
959       this);
960   popup->Show();
961 }
962
963 void WebApplication::OnGeolocationPermissionRequest(
964     WebView*, const std::string& url,
965     std::function<void(bool)> result_handler) {
966   auto db = common::AppDB::GetInstance();
967   std::string reminder =
968       db->Get(kDBPrivateSection, kGeolocationPermissionPrefix + url);
969   if (reminder == "allowed") {
970     result_handler(true);
971     return;
972   } else if (reminder == "denied") {
973     result_handler(false);
974     return;
975   }
976
977   // Local Domain: Grant permission if defined, otherwise block execution.
978   // Remote Domain: Popup user prompt if defined, otherwise block execution.
979   if (!FindPrivilege(app_data_, kLocationPrivilege)) {
980     result_handler(false);
981     return;
982   }
983
984   if (common::utils::StartsWith(url, "file://")) {
985     result_handler(true);
986     return;
987   }
988
989   Popup* popup = Popup::CreatePopup(window_);
990   popup->SetButtonType(Popup::ButtonType::AllowDenyButton);
991   popup->SetTitle(popup_string::kPopupTitleGeoLocation);
992   popup->SetBody(popup_string::kPopupBodyGeoLocation);
993   popup->SetCheckBox(popup_string::kPopupCheckRememberPreference);
994   popup->SetResultHandler(
995       [db, result_handler, url](Popup* popup, void* /*user_data*/) {
996         bool result = popup->GetButtonResult();
997         bool remember = popup->GetCheckBoxResult();
998         if (remember) {
999           db->Set(kDBPrivateSection, kGeolocationPermissionPrefix + url,
1000                   result ? "allowed" : "denied");
1001         }
1002         result_handler(result);
1003       },
1004       this);
1005   popup->Show();
1006 }
1007
1008 void WebApplication::OnQuotaExceed(WebView*, const std::string& url,
1009                                    std::function<void(bool)> result_handler) {
1010   auto db = common::AppDB::GetInstance();
1011   std::string reminder =
1012       db->Get(kDBPrivateSection, kQuotaPermissionPrefix + url);
1013   if (reminder == "allowed") {
1014     result_handler(true);
1015     return;
1016   } else if (reminder == "denied") {
1017     result_handler(false);
1018     return;
1019   }
1020
1021   // Local Domain: Grant permission if defined, otherwise Popup user prompt.
1022   // Remote Domain: Popup user prompt.
1023   if (common::utils::StartsWith(url, "file://") &&
1024       FindPrivilege(app_data_, kStoragePrivilege)) {
1025     result_handler(true);
1026     return;
1027   }
1028
1029   Popup* popup = Popup::CreatePopup(window_);
1030   popup->SetButtonType(Popup::ButtonType::AllowDenyButton);
1031   popup->SetTitle(popup_string::kPopupTitleWebStorage);
1032   popup->SetBody(popup_string::kPopupBodyWebStorage);
1033   popup->SetCheckBox(popup_string::kPopupCheckRememberPreference);
1034   popup->SetResultHandler(
1035       [db, result_handler, url](Popup* popup, void* /*user_data*/) {
1036         bool result = popup->GetButtonResult();
1037         bool remember = popup->GetCheckBoxResult();
1038         if (remember) {
1039           db->Set(kDBPrivateSection, kQuotaPermissionPrefix + url,
1040                   result ? "allowed" : "denied");
1041         }
1042         result_handler(result);
1043       },
1044       this);
1045   popup->Show();
1046 }
1047
1048 void WebApplication::OnAuthenticationRequest(
1049     WebView*, const std::string& /*url*/, const std::string& /*message*/,
1050     std::function<void(bool submit, const std::string& id,
1051                        const std::string& password)> result_handler) {
1052   Popup* popup = Popup::CreatePopup(window_);
1053   popup->SetButtonType(Popup::ButtonType::LoginCancelButton);
1054   popup->SetFirstEntry(popup_string::kPopupLabelAuthusername,
1055                        Popup::EntryType::Edit);
1056   popup->SetSecondEntry(popup_string::kPopupLabelPassword,
1057                         Popup::EntryType::PwEdit);
1058   popup->SetTitle(popup_string::kPopupTitleAuthRequest);
1059   popup->SetBody(popup_string::kPopupBodyAuthRequest);
1060   popup->SetResultHandler([result_handler](Popup* popup, void* /*user_data*/) {
1061                             bool result = popup->GetButtonResult();
1062                             std::string id = popup->GetFirstEntryResult();
1063                             std::string passwd = popup->GetSecondEntryResult();
1064                             result_handler(result, id, passwd);
1065                           },
1066                           this);
1067   popup->Show();
1068 }
1069
1070 void WebApplication::OnCertificateAllowRequest(
1071     WebView*, const std::string& url, const std::string& pem,
1072     std::function<void(bool allow)> result_handler) {
1073   auto db = common::AppDB::GetInstance();
1074   std::string reminder =
1075       db->Get(kDBPrivateSection, kCertificateAllowPrefix + pem);
1076   if (reminder == "allowed") {
1077     result_handler(true);
1078     return;
1079   } else if (reminder == "denied") {
1080     result_handler(false);
1081     return;
1082   }
1083
1084   Popup* popup = Popup::CreatePopup(window_);
1085   popup->SetButtonType(Popup::ButtonType::AllowDenyButton);
1086   popup->SetTitle(popup_string::kPopupTitleCert);
1087   popup->SetBody(popup_string::GetText(
1088                  popup_string::kPopupBodyCert) + "\n\n" + url);
1089   popup->SetCheckBox(popup_string::kPopupCheckRememberPreference);
1090   popup->SetResultHandler(
1091       [db, result_handler, pem](Popup* popup, void* /*user_data*/) {
1092         bool result = popup->GetButtonResult();
1093         bool remember = popup->GetCheckBoxResult();
1094         if (remember) {
1095           db->Set(kDBPrivateSection, kCertificateAllowPrefix + pem,
1096                   result ? "allowed" : "denied");
1097         }
1098         result_handler(result);
1099       },
1100       this);
1101   popup->Show();
1102 }
1103
1104 void WebApplication::OnUsermediaPermissionRequest(
1105     WebView*, const std::string& url,
1106     std::function<void(bool)> result_handler) {
1107   auto db = common::AppDB::GetInstance();
1108   std::string reminder =
1109       db->Get(kDBPrivateSection, kUsermediaPermissionPrefix + url);
1110   if (reminder == "allowed") {
1111     result_handler(true);
1112     return;
1113   } else if (reminder == "denied") {
1114     result_handler(false);
1115     return;
1116   }
1117
1118   // Local Domain: Grant permission if defined, otherwise block execution.
1119   // Remote Domain: Popup user prompt if defined, otherwise block execution.
1120   if (!FindPrivilege(app_data_, kUsermediaPrivilege)) {
1121     result_handler(false);
1122     return;
1123   }
1124
1125   if (common::utils::StartsWith(url, "file://")) {
1126     result_handler(true);
1127     return;
1128   }
1129
1130   Popup* popup = Popup::CreatePopup(window_);
1131   popup->SetButtonType(Popup::ButtonType::AllowDenyButton);
1132   popup->SetTitle(popup_string::kPopupTitleUserMedia);
1133   popup->SetBody(popup_string::kPopupBodyUserMedia);
1134   popup->SetCheckBox(popup_string::kPopupCheckRememberPreference);
1135   popup->SetResultHandler(
1136       [db, result_handler, url](Popup* popup, void* /*user_data*/) {
1137         bool result = popup->GetButtonResult();
1138         bool remember = popup->GetCheckBoxResult();
1139         if (remember) {
1140           db->Set(kDBPrivateSection, kUsermediaPermissionPrefix + url,
1141                   result ? "allowed" : "denied");
1142         }
1143         result_handler(result);
1144       },
1145       this);
1146   popup->Show();
1147 }
1148
1149 }  // namespace runtime