[Release] wrt_0.8.187
[platform/framework/web/wrt.git] / src / wrt-client / wrt-client.cpp
1 /*
2  * Copyright (c) 2011 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 #include "wrt-client.h"
17 #include <aul.h>
18 #include <sys/time.h>
19 #include <sys/resource.h>
20 #include <appcore-efl.h>
21 #include <appcore-common.h>
22 #include <cstdlib>
23 #include <cstdio>
24 #include <string>
25 #include <dpl/log/log.h>
26 #include <dpl/optional_typedefs.h>
27 #include <dpl/exception.h>
28 #include <common/application_data.h>
29 #include <core_module.h>
30 #include <localization_setting.h>
31 #include <widget_deserialize_model.h>
32 #include <EWebKit2.h>
33 #include <dpl/localization/w3c_file_localization.h>
34 #include <dpl/localization/LanguageTagsProvider.h>
35 #include "webkit/bundles/plugin_module_support.h"
36 #include <popup-runner/PopupInvoker.h>
37 #include <prepare_external_storage.h>
38 #include <vconf.h>
39
40 #include "process_pool.h"
41 #include "menu_db_util.h"
42 #include "launchpad_util.h"
43
44 //W3C PACKAGING enviroment variable name
45 #define W3C_DEBUG_ENV_VARIABLE "DEBUG_LOAD_FINISH"
46
47 // window signal callback
48 const char *EDJE_SHOW_BACKWARD_SIGNAL = "show,backward,signal";
49 const std::string VIEWMODE_TYPE_FULLSCREEN = "fullscreen";
50 const std::string VIEWMODE_TYPE_MAXIMIZED = "maximized";
51 char const* const ELM_SWALLOW_CONTENT = "elm.swallow.content";
52 const char* const BUNDLE_PATH = "/usr/lib/wrt-wk2-bundles/libwrt-wk2-bundle.so";
53 const char* const caCertPath = "/opt/usr/share/certs/ca-certificate.crt";
54
55 // process pool
56 const char* const DUMMY_PROCESS_PATH = "/usr/bin/wrt_launchpad_daemon_candidate";
57 static Ewk_Context* s_preparedEwkContext = NULL;
58 static WindowData*  s_preparedWindowData = NULL;
59 static int    app_argc = 0;
60 static char** app_argv = NULL;
61
62 // orientation
63 const int WIN_ORIENTATION_PORTRAIT_PRIMARY_ANGLE = 0;
64 const int WIN_ORIENTATION_LANDSCAPE_PRIMARY_ANGLE = 270;
65 const int W3C_ORIENTATION_PORTRAIT_PRIMARY_ANGLE = 0;
66 const int W3C_ORIENTATION_LANDSCAPE_PRIMARY_ANGLE = 90;
67
68 // env
69 const char* const HOME = "HOME";
70 const char* const APP_HOME_PATH = "/opt/home/app";
71
72 WrtClient::WrtClient(int argc, char **argv) :
73     Application(argc, argv, "wrt-client", false),
74     DPL::TaskDecl<WrtClient>(this),
75     m_appControlIndex(DPL::OptionalUInt()),
76     m_launched(false),
77     m_initializing(false),
78     m_initialized(false),
79     m_sdkLauncherPid(0),
80     m_debugMode(false),
81     m_debuggerPort(0),
82     m_returnStatus(ReturnStatus::Succeeded),
83     m_widgetState(WidgetState::WidgetState_Stopped)
84 {
85     Touch();
86     LogDebug("App Created");
87 }
88
89 WrtClient::~WrtClient()
90 {
91     LogDebug("App Finished");
92 }
93
94 WrtClient::ReturnStatus::Type WrtClient::getReturnStatus() const
95 {
96     return m_returnStatus;
97 }
98
99 void WrtClient::OnStop()
100 {
101     LogInfo("Stopping Dummy Client");
102 }
103
104 void WrtClient::OnCreate()
105 {
106     LogInfo("On Create");
107     ADD_PROFILING_POINT("OnCreate callback", "point");
108     ewk_init();
109 }
110
111 void WrtClient::OnResume()
112 {
113     if (m_widgetState != WidgetState_Suspended) {
114         LogWarning("Widget is not suspended, resuming was skipped");
115         return;
116     }
117     m_widget->Resume();
118     m_widgetState = WidgetState_Running;
119 }
120
121 void WrtClient::OnPause()
122 {
123     if (m_widgetState != WidgetState_Running) {
124         LogWarning("Widget is not running to be suspended");
125         return;
126     }
127     m_widget->Suspend();
128     m_widgetState = WidgetState_Suspended;
129 }
130
131 void WrtClient::OnReset(bundle *b)
132 {
133     LogDebug("OnReset");
134     // bundle argument is freed after OnReset() is returned
135     // So bundle duplication is needed
136     ApplicationDataSingleton::Instance().setBundle(bundle_dup(b));
137
138     if (true == m_initializing) {
139         LogDebug("can not handle reset event");
140         return;
141     }
142     if (true == m_launched) {
143         if (m_widgetState == WidgetState_Stopped) {
144             LogError("Widget is not running to be reset");
145             return;
146         }
147         m_widget->Reset();
148         m_windowData->emitSignalForUserLayout(EDJE_SHOW_BACKWARD_SIGNAL, "");
149         m_widgetState = WidgetState_Running;
150     } else {
151         if (true == checkArgument()) {
152             setStep();
153         } else {
154             showHelpAndQuit();
155         }
156     }
157
158     // low memory callback set
159     appcore_set_event_callback(
160             APPCORE_EVENT_LOW_MEMORY,
161             WrtClient::appcoreLowMemoryCallback,
162             this);
163 }
164
165 void WrtClient::OnTerminate()
166 {
167     LogDebug("Wrt Shutdown now");
168     shutdownStep();
169 }
170
171 void WrtClient::showHelpAndQuit()
172 {
173     printf("Usage: wrt-client [OPTION]... [WIDGET: ID]...\n"
174            "launch widgets.\n"
175            "Mandatory arguments to long options are mandatory for short "
176            "options too.\n"
177            "  -h,    --help                                 show this help\n"
178            "  -l,    --launch                               "
179            "launch widget with given tizen ID\n"
180            "  -t,    --tizen                                "
181            "launch widget with given tizen ID\n"
182            "\n");
183
184     Quit();
185 }
186
187 bool WrtClient::checkArgument()
188 {
189     std::string tizenId = getTizenIdFromArgument(m_argc, m_argv);
190
191     if (tizenId.empty()) {
192         // Just show help
193         return false;
194     } else {
195         std::size_t pos =
196             tizenId.find(WrtDB::AppControlPrefix::PROCESS_PREFIX);
197         if (pos != std::string::npos) {
198             std::string id = tizenId.substr(pos);
199             id.erase(strlen(WrtDB::AppControlPrefix::PROCESS_PREFIX));
200             std::stringstream s(id);
201             unsigned int appControlIndex;
202             s >> appControlIndex;
203             m_appControlIndex = appControlIndex;
204             tizenId.erase(pos);
205             LogDebug("app-control execute-index : " << appControlIndex);
206         }
207         m_tizenId = tizenId;
208         LogDebug("Tizen id: " << m_tizenId);
209         return true;
210     }
211 }
212
213 std::string WrtClient::getTizenIdFromArgument(int argc, char **argv)
214 {
215     LogInfo("checkArgument");
216     std::string arg = argv[0];
217
218     if (arg.empty()) {
219         return "";
220     }
221
222     if (arg.find("wrt-client") != std::string::npos) {
223         if (argc <= 1) {
224             return "";
225         }
226
227         arg = argv[1];
228
229         if (arg == "-h" || arg == "--help") {
230             return "";
231         } else if (arg == "-l" || arg == "--launch" ||
232                    arg == "-t" || arg == "--tizen")
233         {
234             if (argc != 3) {
235                 return "";
236             }
237             return argv[2];
238         } else {
239             return "";
240         }
241     } else {
242         // Launch widget based on application basename
243         size_t pos = arg.find_last_of('/');
244
245         if (pos != std::string::npos) {
246             arg = arg.erase(0, pos + 1);
247         }
248
249         return arg;
250     }
251 }
252
253 void WrtClient::setStep()
254 {
255     LogInfo("setStep");
256
257     AddStep(&WrtClient::initStep);
258
259     setSdkLauncherDebugData();
260
261     AddStep(&WrtClient::launchStep);
262     AddStep(&WrtClient::shutdownStep);
263
264     m_initializing = true;
265
266     DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(NextStepEvent());
267 }
268
269 void WrtClient::setSdkLauncherDebugData()
270 {
271     LogDebug("setSdkLauncherDebugData");
272
273     /* check bundle from sdk launcher */
274     bundle *bundleFromSdkLauncher;
275     bundleFromSdkLauncher = bundle_import_from_argv(m_argc, m_argv);
276     const char *bundle_debug = bundle_get_val(bundleFromSdkLauncher, "debug");
277     const char *bundle_pid = bundle_get_val(bundleFromSdkLauncher, "pid");
278     if (bundle_debug != NULL && bundle_pid != NULL) {
279         if (strcmp(bundle_debug, "true") == 0) {
280             m_debugMode = true;
281             m_sdkLauncherPid = atoi(bundle_pid);
282         } else {
283             m_debugMode = false;
284         }
285     }
286     bundle_free(bundleFromSdkLauncher);
287 }
288
289 bool WrtClient::checkDebugMode(SDKDebugData* debugData)
290 {
291     LogError("Checking for debug mode");
292     Assert(m_dao);
293
294     bool debugMode = debugData->debugMode;
295
296     LogInfo("[DEBUG_MODE] Widget is launched in " <<
297             (debugMode ? "DEBUG" : "RETAIL") <<
298             " mode.");
299
300     if (debugMode == true) {
301         // In WAC widget, only test widgets can use web inspector.
302         // In TIZEN widget,
303         // every launched widgets as debug mode can use it.
304         if (m_dao->getWidgetType().appType == WrtDB::APP_TYPE_WAC20) {
305             bool developerMode =
306                 WRT::CoreModuleSingleton::Instance().developerMode();
307             //This code will be activated
308             //after WAC test certificate is used by SDK
309             //bool isTestWidget = view->m_widgetModel->IsTestWidget.Get();
310             //if(!isTestWidget)
311             //{
312             //    LogInfo("This is not WAC Test Widget");
313             //    break;
314             //}
315             if (!developerMode) {
316                 LogInfo("This is not WAC Developer Mode");
317                 debugMode = false;
318             }
319         }
320     }
321     return debugMode;
322 }
323
324 void WrtClient::OnEventReceived(const NextStepEvent& /*event*/)
325 {
326     LogDebug("Executing next step");
327     NextStep();
328 }
329
330 void WrtClient::initStep()
331 {
332     LogDebug("");
333     if (WRT::CoreModuleSingleton::Instance().Init()) {
334         m_initialized = true;
335     } else {
336         m_returnStatus = ReturnStatus::Failed;
337         SwitchToStep(&WrtClient::shutdownStep);
338     }
339
340     // ecore_event_jobs are processed sequentially without concession to
341     // other type events. To give a chance of execute to other events,
342     // ecore_timer_add was used.
343     DPL::Event::ControllerEventHandler<NextStepEvent>::PostTimedEvent(
344         NextStepEvent(), 0.001);
345 }
346
347 bool WrtClient::checkWACTestCertififedWidget()
348 {
349     // WAC Waikiki Beta Release Core Specification: Widget Runtime
350     // 10 Dec 2010
351     //
352     // WR-4710 The WRT MUST enable debug functions only for WAC test widgets
353     // i.e. the functions must not be usable for normal WAC widgets, even when
354     // a WAC test widget is executing.
355     ADD_PROFILING_POINT("DeveloperModeCheck", "start");
356     Assert(!!m_dao);
357     // WAC test widget
358     // A widget signed with a WAC-issued test certificate as described in
359     // Developer Mode.
360
361     bool developerWidget = m_dao->isTestWidget();
362     bool developerMode = WRT::CoreModuleSingleton::Instance().developerMode();
363
364     LogDebug("Is WAC test widget: " << developerWidget);
365     LogDebug("Is developer Mode: " << developerMode);
366
367     if (developerWidget) {
368         if (!developerMode) {
369             LogError("WAC test certified developer widget is needed for " <<
370                      "developer mode");
371             return false;
372         } else {
373             //TODO: WR-4660 (show popup about developer widget
374             //      during launch
375             LogInfo("POPUP: THIS IS TEST WIDGET!");
376         }
377     }
378     ADD_PROFILING_POINT("DeveloperModeCheck", "stop");
379     return true;
380 }
381
382 void WrtClient::loadFinishCallback(Evas_Object* webview)
383 {
384     ADD_PROFILING_POINT("loadFinishCallback", "start");
385     SDKDebugData* debug = new SDKDebugData;
386     debug->debugMode = m_debugMode;
387     debug->pid = new unsigned long(getpid());
388
389     LogInfo("Post result of launch");
390
391     // Start inspector server, if current mode is debugger mode.
392     // In the WK2 case, ewk_view_inspector_server_start should
393     // be called after WebProcess is created.
394     if (checkDebugMode(debug)) {
395         debug->portnum =
396             ewk_view_inspector_server_start(m_widget->GetCurrentWebview(), 0);
397         if (debug->portnum == 0) {
398             LogWarning("Failed to get portnum");
399         } else {
400             LogInfo("Assigned port number for inspector : "
401                     << debug->portnum);
402         }
403     } else {
404         LogDebug("Debug mode is disabled");
405     }
406
407     //w3c packaging test debug (message on 4>)
408     const char * makeScreen = getenv(W3C_DEBUG_ENV_VARIABLE);
409     if (makeScreen != NULL && strcmp(makeScreen, "1") == 0) {
410         FILE* doutput = fdopen(4, "w");
411         fprintf(doutput, "didFinishLoadForFrameCallback: ready\n");
412         fclose(doutput);
413     }
414
415     if (webview) {
416         LogDebug("Launch succesfull");
417
418         m_launched = true;
419         m_initializing = false;
420         setlinebuf(stdout);
421         ADD_PROFILING_POINT("loadFinishCallback", "stop");
422         printf("launched\n");
423         fflush(stdout);
424     } else {
425         printf("failed\n");
426
427         m_returnStatus = ReturnStatus::Failed;
428         //shutdownStep
429         DPL::Event::ControllerEventHandler<NextStepEvent>::
430             PostEvent(NextStepEvent());
431     }
432
433     if (debug->debugMode) {
434         LogDebug("Send RT signal to wrt-launcher(pid: " << m_sdkLauncherPid);
435         union sigval sv;
436         /* send real time signal with result to wrt-launcher */
437         if (webview) {
438             LogDebug("userData->portnum : " << debug->portnum);
439             sv.sival_int = debug->portnum;
440         } else {
441             sv.sival_int = -1;
442         }
443         sigqueue(m_sdkLauncherPid, SIGRTMIN, sv);
444     }
445
446     ApplicationDataSingleton::Instance().freeBundle();
447
448     LogDebug("Cleaning wrtClient launch resources...");
449     delete debug->pid;
450     delete debug;
451 }
452
453 void WrtClient::progressFinishCallback()
454 {
455     m_splashScreen->stopSplashScreen();
456 }
457
458 void WrtClient::webkitExitCallback()
459 {
460     LogDebug("window close called, terminating app");
461     SwitchToStep(&WrtClient::shutdownStep);
462     DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
463         NextStepEvent());
464 }
465
466 void WrtClient::webCrashCallback()
467 {
468     LogError("webProcess crashed");
469     SwitchToStep(&WrtClient::shutdownStep);
470     DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
471         NextStepEvent());
472 }
473
474 void WrtClient::launchStep()
475 {
476     ADD_PROFILING_POINT("launchStep", "start");
477     LogDebug("Launching widget ...");
478
479     ADD_PROFILING_POINT("getRunnableWidgetObject", "start");
480     m_widget = WRT::CoreModuleSingleton::Instance()
481             .getRunnableWidgetObject(m_tizenId, m_appControlIndex);
482     ADD_PROFILING_POINT("getRunnableWidgetObject", "stop");
483
484     if (!m_widget) {
485         LogError("RunnableWidgetObject is NULL, stop launchStep");
486         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
487             NextStepEvent());
488         return;
489     }
490
491     if (m_widgetState == WidgetState_Running) {
492         LogWarning("Widget already running, stop launchStep");
493         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
494             NextStepEvent());
495         return;
496     }
497
498     if (m_widgetState == WidgetState_Authorizing) {
499         LogWarning("Widget already authorizing, stop launchStep");
500         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
501             NextStepEvent());
502         return;
503     }
504
505     m_dao.reset(new WrtDB::WidgetDAOReadOnly(DPL::FromASCIIString(m_tizenId)));
506     DPL::Optional<DPL::String> defloc = m_dao->getDefaultlocale();
507     if (!defloc.IsNull()) {
508         LanguageTagsProviderSingleton::Instance().addWidgetDefaultLocales(
509             *defloc);
510     }
511
512     PrepareExternalStorageSingleton::Instance().Initialize(m_dao->getTizenPkgId());
513
514     /* remove language change callback */
515     /*
516     LocalizationSetting::SetLanguageChangedCallback(
517             languageChangedCallback, this);
518     */
519
520     ADD_PROFILING_POINT("CreateWindow", "start");
521     if (s_preparedWindowData == NULL) {
522         m_windowData.reset(new WindowData(static_cast<unsigned long>(getpid()), true));
523     } else {
524         m_windowData.reset(s_preparedWindowData);
525         s_preparedWindowData = NULL;
526     }
527     ADD_PROFILING_POINT("CreateWindow", "stop");
528     evas_object_show(m_windowData->m_win);
529     // rotate window to initial value
530     setOrientationWindow();
531
532     WRT::UserDelegatesPtr cbs(new WRT::UserDelegates);
533     ADD_PROFILING_POINT("Create splash screen", "start");
534     m_splashScreen.reset(
535         new SplashScreenSupport(m_windowData->m_win));
536     if (m_splashScreen->createSplashScreen(m_dao->getSplashImgSrc())) {
537         m_splashScreen->startSplashScreen();
538         cbs->progressFinish = DPL::MakeDelegate(
539                 this,
540                 &WrtClient::
541                     progressFinishCallback);
542     }
543     ADD_PROFILING_POINT("Create splash screen", "stop");
544     DPL::OptionalString startUrl = W3CFileLocalization::getStartFile(m_dao);
545     if (!m_widget->PrepareView(DPL::ToUTF8String(*startUrl),
546             m_windowData->m_win, s_preparedEwkContext))
547     {
548         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
549             NextStepEvent());
550         return;
551     }
552     // send rotate information to ewk
553     setOrientationEwk();
554
555     //you can't show window with splash screen before PrepareView
556     //ewk_view_add_with_context() in viewLogic breaks window
557
558     m_windowData->init();
559
560     WrtDB::WidgetLocalizedInfo localizedInfo =
561         W3CFileLocalization::getLocalizedInfo(m_dao);
562     std::string name = "";
563     if (!(localizedInfo.name.IsNull())) {
564         name = DPL::ToUTF8String(*(localizedInfo.name));
565     }
566     elm_win_title_set(m_windowData->m_win, name.c_str());
567
568     initializeWindowModes();
569     connectElmCallback();
570
571     if (!checkWACTestCertififedWidget()) {
572         LogWarning("WAC Certificate failed, stop launchStep");
573         return;
574     }
575
576     m_widgetState = WidgetState_Authorizing;
577     if (!m_widget->CheckBeforeLaunch()) {
578         LogError("CheckBeforeLaunch failed, stop launchStep");
579         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
580             NextStepEvent());
581         return;
582     }
583     LogInfo("Widget launch accepted. Entering running state");
584     m_widgetState = WidgetState_Running;
585
586     cbs->loadFinish = DPL::MakeDelegate(this, &WrtClient::loadFinishCallback);
587     cbs->bufferSet = DPL::MakeDelegate(this, &WrtClient::setLayout);
588     cbs->bufferUnset = DPL::MakeDelegate(this, &WrtClient::unsetLayout);
589     cbs->webkitExit = DPL::MakeDelegate(this, &WrtClient::webkitExitCallback);
590     cbs->webCrash = DPL::MakeDelegate(this, &WrtClient::webCrashCallback);
591     cbs->toggleFullscreen = DPL::MakeDelegate(
592             m_windowData.get(), &WindowData::toggleFullscreen);
593
594     m_widget->SetUserDelegates(cbs);
595     m_widget->Show();
596
597     m_windowData->emitSignalForUserLayout(EDJE_SHOW_BACKWARD_SIGNAL, "");
598
599     ADD_PROFILING_POINT("launchStep", "stop");
600 }
601
602 void WrtClient::initializeWindowModes()
603 {
604     Assert(m_windowData);
605     Assert(m_dao);
606     auto windowModes = m_dao->getWindowModes();
607     bool fullscreen = false;
608     bool backbutton = false;
609     if (m_dao->getWidgetType().appType == WrtDB::APP_TYPE_TIZENWEBAPP) {
610         WrtDB::WidgetSettings widgetSettings;
611         m_dao->getWidgetSettings(widgetSettings);
612         WidgetSettingList settings(widgetSettings);
613         backbutton =
614             (settings.getBackButtonPresence() == BackButton_Enable);
615     }
616
617     FOREACH(it, windowModes)
618     {
619         std::string viewMode = DPL::ToUTF8String(*it);
620         if (viewMode == VIEWMODE_TYPE_FULLSCREEN) {
621             fullscreen = true;
622             break;
623         } else if (viewMode == VIEWMODE_TYPE_MAXIMIZED) {
624             break;
625         }
626     }
627
628     m_windowData->setViewMode(fullscreen,
629                               backbutton);
630 }
631
632 void WrtClient::backButtonCallback(void* data,
633                                    Evas_Object * /*obj*/,
634                                    void * /*event_info*/)
635 {
636     LogInfo("BackButtonCallback");
637     Assert(data);
638
639     WrtClient* This = static_cast<WrtClient*>(data);
640
641     This->m_widget->Backward();
642 }
643
644 int WrtClient::appcoreLowMemoryCallback(void* /*data*/)
645 {
646     LogInfo("appcoreLowMemoryCallback");
647     //WrtClient* This = static_cast<WrtClient*>(data);
648
649     // TODO call RunnableWidgetObject API regarding low memory
650     // The API should be implemented
651
652     return 0;
653 }
654
655 void WrtClient::setOrientationWindow(void)
656 {
657     Assert(m_windowData);
658     Assert(m_dao);
659
660     WrtDB::WidgetSettings widgetSettings;
661     m_dao->getWidgetSettings(widgetSettings);
662     WidgetSettingList settings(widgetSettings);
663     WidgetSettingScreenLock rotationValue = settings.getRotationValue();
664     if (rotationValue == Screen_Portrait) {
665         elm_win_wm_rotation_preferred_rotation_set(
666             m_windowData->m_win,
667             WIN_ORIENTATION_PORTRAIT_PRIMARY_ANGLE);
668     } else if (rotationValue == Screen_Landscape) {
669         elm_win_wm_rotation_preferred_rotation_set(
670             m_windowData->m_win,
671             WIN_ORIENTATION_LANDSCAPE_PRIMARY_ANGLE);
672     } else {
673         elm_win_wm_rotation_preferred_rotation_set(
674             m_windowData->m_win,
675             WIN_ORIENTATION_PORTRAIT_PRIMARY_ANGLE);
676     }
677 }
678
679 void WrtClient::setOrientationEwk(void)
680 {
681     Assert(m_widget);
682     Assert(m_dao);
683
684     WrtDB::WidgetSettings widgetSettings;
685     m_dao->getWidgetSettings(widgetSettings);
686     WidgetSettingList settings(widgetSettings);
687     WidgetSettingScreenLock rotationValue = settings.getRotationValue();
688     if (rotationValue == Screen_Portrait) {
689         ewk_view_orientation_send(
690             m_widget->GetCurrentWebview(),
691              W3C_ORIENTATION_PORTRAIT_PRIMARY_ANGLE);
692     } else if (rotationValue == Screen_Landscape) {
693         ewk_view_orientation_send(
694             m_widget->GetCurrentWebview(),
695             W3C_ORIENTATION_LANDSCAPE_PRIMARY_ANGLE);
696     } else {
697         ewk_view_orientation_send(
698             m_widget->GetCurrentWebview(),
699             W3C_ORIENTATION_PORTRAIT_PRIMARY_ANGLE);
700     }
701 }
702
703 void WrtClient::connectElmCallback()
704 {
705     Assert(m_windowData);
706     Assert(m_dao);
707     WrtDB::WidgetSettings widgetSettings;
708     m_dao->getWidgetSettings(widgetSettings);
709     WidgetSettingList settings(widgetSettings);
710     if (settings.getBackButtonPresence() == BackButton_Enable) {
711         m_windowData->addFloatBackButtonCallback(
712             "clicked",
713             &WrtClient::backButtonCallback,
714             this);
715     }
716 }
717
718 void WrtClient::setLayout(Evas_Object* newBuffer)
719 {
720     LogDebug("add new webkit buffer to window");
721     Assert(newBuffer);
722
723     elm_object_part_content_set(m_windowData->m_user_layout,
724                                 ELM_SWALLOW_CONTENT,
725                                 newBuffer);
726
727     evas_object_show(newBuffer);
728 }
729
730 void WrtClient::unsetLayout(Evas_Object* currentBuffer)
731 {
732     LogDebug("remove current webkit buffer from window");
733     Assert(currentBuffer);
734     evas_object_hide(currentBuffer);
735
736     elm_object_part_content_unset(m_windowData->m_user_layout,
737                                   ELM_SWALLOW_CONTENT);
738 }
739
740 void WrtClient::shutdownStep()
741 {
742     LogDebug("Closing Wrt connection ...");
743
744     if (m_widget && m_widgetState) {
745         m_widgetState = WidgetState_Stopped;
746         m_widget->Hide();
747         m_widget.reset();
748         ewk_context_delete(s_preparedEwkContext);
749         PrepareExternalStorageSingleton::Instance().Deinitialize();
750         WRT::CoreModuleSingleton::Instance().Terminate();
751     }
752     if (m_initialized) {
753         m_initialized = false;
754     }
755     m_windowData.reset();
756     Quit();
757 }
758
759 int WrtClient::languageChangedCallback(void *data)
760 {
761     LogDebug("Language Changed");
762     if (!data) {
763         return 0;
764     }
765     WrtClient* wrtClient = static_cast<WrtClient*>(data);
766     if (!(wrtClient->m_dao)) {
767         return 0;
768     }
769
770     // reset function fetches system locales and recreates language tags
771     LanguageTagsProviderSingleton::Instance().resetLanguageTags();
772     // widget default locales are added to language tags below
773     DPL::OptionalString defloc = wrtClient->m_dao->getDefaultlocale();
774     if (!defloc.IsNull()) {
775         LanguageTagsProviderSingleton::Instance().addWidgetDefaultLocales(
776             *defloc);
777     }
778
779     if (wrtClient->m_launched &&
780         wrtClient->m_widgetState != WidgetState_Stopped)
781     {
782         wrtClient->m_widget->ReloadStartPage();
783     }
784     return 0;
785 }
786
787 void WrtClient::Quit()
788 {
789     ewk_shutdown();
790     DPL::Application::Quit();
791 }
792
793 static Eina_Bool proces_pool_fd_handler(void* /*data*/, Ecore_Fd_Handler *handler)
794 {
795     int fd = ecore_main_fd_handler_fd_get(handler);
796
797     if (ecore_main_fd_handler_active_get(handler, ECORE_FD_ERROR))
798     {
799         LogDebug("ECORE_FD_ERROR");
800
801         if (fd != -1)
802         {
803             close(fd);
804         }
805
806         exit(-1);
807         return ECORE_CALLBACK_CANCEL;
808     }
809
810     if (ecore_main_fd_handler_active_get(handler, ECORE_FD_READ))
811     {
812         LogDebug("ECORE_FD_READ");
813         {
814             app_pkt_t* pkt = (app_pkt_t*) malloc(sizeof(char) * AUL_SOCK_MAXBUFF);
815             memset(pkt, 0, AUL_SOCK_MAXBUFF);
816
817             int recv_ret = recv(fd, pkt, AUL_SOCK_MAXBUFF, 0);
818
819             if (fd != -1)
820             {
821                 close(fd);
822             }
823
824             if (recv_ret == -1)
825             {
826                 LogDebug("recv error!");
827                 exit(-1);
828             }
829             LogDebug("recv_ret : " << recv_ret << ", pkt->len : " << pkt->len);
830
831             ecore_main_fd_handler_del(handler);
832
833             __wrt_launchpad_main_loop(pkt, app_argv[0], &app_argc, &app_argv);
834
835             free(pkt);
836         }
837
838         ecore_main_loop_quit();
839         return ECORE_CALLBACK_CANCEL;
840     }
841
842     return ECORE_CALLBACK_CANCEL;
843 }
844
845 static void vconf_changed_handler(keynode_t* /*key*/, void* /*data*/)
846 {
847     LogInfo("VCONFKEY_LANGSET vconf-key was changed!");
848
849     // When system language is changed, the candidate process will be created again.
850     exit(-1);
851 }
852
853 void set_env()
854 {
855     // set evas backend type
856     if (!getenv("ELM_ENGINE"))
857     {
858         if (!setenv("ELM_ENGINE", "gl", 1))
859         {
860             LogDebug("Enable backend");
861         }
862     }
863     else
864     {
865         LogDebug("ELM_ENGINE : " << getenv("ELM_ENGINE"));
866     }
867
868 #ifndef TIZEN_PUBLIC
869     setenv("COREGL_FASTPATH", "1", 1);
870 #endif
871     setenv("CAIRO_GL_COMPOSITOR", "msaa", 1);
872     setenv("CAIRO_GL_LAZY_FLUSHING", "yes", 1);
873     setenv("ELM_IMAGE_CACHE", "0", 1);
874 }
875
876 int main(int argc,
877          char *argv[])
878 {
879     // process pool - store arg's value
880     app_argc = argc;
881     app_argv = argv;
882
883     UNHANDLED_EXCEPTION_HANDLER_BEGIN
884     {
885         ADD_PROFILING_POINT("main-entered", "point");
886
887         // Set log tagging
888         DPL::Log::LogSystemSingleton::Instance().SetTag("WRT");
889
890         // Set environment variables
891         set_env();
892
893         if (argc > 1 && argv[1] != NULL && !strcmp(argv[1], "-d"))
894         {
895             LogInfo("Entered dummy process mode");
896             sprintf(argv[0], "%s                                              ",
897                     DUMMY_PROCESS_PATH);
898
899             LogInfo("Prepare ewk_context");
900             appcore_set_i18n("wrt-client", NULL);
901             ewk_set_arguments(argc, argv);
902             setenv("WRT_LAUNCHING_PERFORMANCE", "1", 1);
903             s_preparedEwkContext = ewk_context_new_with_injected_bundle_path(BUNDLE_PATH);
904
905             if (s_preparedEwkContext == NULL)
906             {
907                 LogInfo("Creating webkit context was failed!");
908                 exit(-1);
909             }
910
911             LogInfo("ewk_context_certificate_file_set()");
912             ewk_context_certificate_file_set(s_preparedEwkContext, caCertPath);
913
914             int client_fd = __connect_process_pool_server();
915
916             if (client_fd == -1)
917             {
918                 LogInfo("Connecting process_pool_server was failed!");
919                 exit(-1);
920             }
921
922             // register language changed callback
923             vconf_notify_key_changed(VCONFKEY_LANGSET, vconf_changed_handler, NULL);
924
925             LogInfo("Prepare window_data");
926             // Temporarily change HOME path to app
927             // This change is needed for getting elementary profile
928             // /opt/home/app/.elementary/config/mobile/base.cfg
929             const char* backupEnv = getenv(HOME);
930             setenv(HOME, APP_HOME_PATH, 1);
931             LogInfo("elm_init()");
932             elm_init(argc, argv);
933             setenv(HOME, backupEnv, 1);
934
935             LogInfo("WindowData()");
936             s_preparedWindowData = new WindowData(static_cast<unsigned long>(getpid()));
937
938             Ecore_Fd_Handler* fd_handler = ecore_main_fd_handler_add(client_fd,
939                                            (Ecore_Fd_Handler_Flags)(ECORE_FD_READ|ECORE_FD_ERROR),
940                                            proces_pool_fd_handler, NULL, NULL, NULL);
941
942             if (fd_handler == NULL)
943             {
944                 LogInfo("fd_handler is NULL");
945                 exit(-1);
946             }
947
948             setpriority(PRIO_PROCESS, 0, 0);
949
950             LogDebug("ecore_main_loop_begin()");
951             ecore_main_loop_begin();
952             LogDebug("ecore_main_loop_begin()_end");
953
954             // deregister language changed callback
955             vconf_ignore_key_changed(VCONFKEY_LANGSET, vconf_changed_handler);
956
957             std::string tizenId = WrtClient::getTizenIdFromArgument(argc, argv);
958             PluginModuleSupport::init(s_preparedEwkContext, tizenId);
959         }
960         else
961         {
962             // This code is to fork a web process without exec.
963             std::string tizenId = WrtClient::getTizenIdFromArgument(argc, argv);
964             if (!tizenId.empty()) {
965                 std::size_t pos =
966                     tizenId.find(WrtDB::AppControlPrefix::PROCESS_PREFIX);
967                 if (pos != std::string::npos) {
968                     tizenId.erase(pos);
969                 }
970
971                 LogDebug("Launching by fork mode");
972                 // Language env setup
973                 appcore_set_i18n("wrt-client", NULL);
974                 ewk_set_arguments(argc, argv);
975                 setenv("WRT_LAUNCHING_PERFORMANCE", "1", 1);
976                 s_preparedEwkContext = ewk_context_new_with_injected_bundle_path(
977                         BUNDLE_PATH);
978
979                 if (s_preparedEwkContext == NULL)
980                 {
981                     LogInfo("Creating webkit context was failed!");
982                     Wrt::Popup::PopupInvoker().showInfo("Error", "Creating webkit context was failed.", "OK");
983                     exit(-1);
984                 }
985
986                 // plugin init
987                 PluginModuleSupport::init(s_preparedEwkContext, tizenId);
988
989                 LogInfo("ewk_context_certificate_file_set()");
990                 ewk_context_certificate_file_set(s_preparedEwkContext, caCertPath);
991             }
992         }
993
994         // Output on stdout will be flushed after every newline character,
995         // even if it is redirected to a pipe. This is useful for running
996         // from a script and parsing output.
997         // (Standard behavior of stdlib is to use full buffering when
998         // redirected to a pipe, which means even after an end of line
999         // the output may not be flushed).
1000         setlinebuf(stdout);
1001
1002         WrtClient app(app_argc, app_argv);
1003
1004         ADD_PROFILING_POINT("Before appExec", "point");
1005         int ret = app.Exec();
1006         LogDebug("App returned: " << ret);
1007         ret = app.getReturnStatus();
1008         LogDebug("WrtClient returned: " << ret);
1009         return ret;
1010     }
1011     UNHANDLED_EXCEPTION_HANDLER_END
1012 }