[Release] wrt_0.8.180
[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
39 #include "process_pool.h"
40 #include "menu_db_util.h"
41 #include "launchpad_util.h"
42
43 //W3C PACKAGING enviroment variable name
44 #define W3C_DEBUG_ENV_VARIABLE "DEBUG_LOAD_FINISH"
45
46 // window signal callback
47 const char *EDJE_SHOW_BACKWARD_SIGNAL = "show,backward,signal";
48 const std::string VIEWMODE_TYPE_FULLSCREEN = "fullscreen";
49 const std::string VIEWMODE_TYPE_MAXIMIZED = "maximized";
50 char const* const ELM_SWALLOW_CONTENT = "elm.swallow.content";
51 const char* const BUNDLE_PATH = "/usr/lib/wrt-wk2-bundles/libwrt-wk2-bundle.so";
52 const char* const caCertPath = "/opt/usr/share/certs/ca-certificate.crt";
53
54 // process pool
55 const char* const DUMMY_PROCESS_PATH = "/usr/bin/wrt_launchpad_daemon_candidate";
56 static Ewk_Context* s_preparedEwkContext = NULL;
57 static WindowData*  s_preparedWindowData = NULL;
58 static int    app_argc = 0;
59 static char** app_argv = NULL;
60
61 // orientation
62 const int WIN_ORIENTATION_PORTRAIT_PRIMARY_ANGLE = 0;
63 const int WIN_ORIENTATION_LANDSCAPE_PRIMARY_ANGLE = 270;
64 const int W3C_ORIENTATION_PORTRAIT_PRIMARY_ANGLE = 0;
65 const int W3C_ORIENTATION_LANDSCAPE_PRIMARY_ANGLE = 90;
66
67 // env
68 const char* const HOME = "HOME";
69 const char* const APP_HOME_PATH = "/opt/home/app";
70
71 WrtClient::WrtClient(int argc, char **argv) :
72     Application(argc, argv, "wrt-client", false),
73     DPL::TaskDecl<WrtClient>(this),
74     m_launched(false),
75     m_initializing(false),
76     m_initialized(false),
77     m_sdkLauncherPid(0),
78     m_debugMode(false),
79     m_debuggerPort(0),
80     m_returnStatus(ReturnStatus::Succeeded),
81     m_widgetState(WidgetState::WidgetState_Stopped)
82 {
83     Touch();
84     LogDebug("App Created");
85 }
86
87 WrtClient::~WrtClient()
88 {
89     LogDebug("App Finished");
90 }
91
92 WrtClient::ReturnStatus::Type WrtClient::getReturnStatus() const
93 {
94     return m_returnStatus;
95 }
96
97 void WrtClient::OnStop()
98 {
99     LogInfo("Stopping Dummy Client");
100 }
101
102 void WrtClient::OnCreate()
103 {
104     LogInfo("On Create");
105     ADD_PROFILING_POINT("OnCreate callback", "point");
106     ewk_init();
107 }
108
109 void WrtClient::OnResume()
110 {
111     if (m_widgetState != WidgetState_Suspended) {
112         LogWarning("Widget is not suspended, resuming was skipped");
113         return;
114     }
115     m_widget->Resume();
116     m_widgetState = WidgetState_Running;
117 }
118
119 void WrtClient::OnPause()
120 {
121     if (m_widgetState != WidgetState_Running) {
122         LogWarning("Widget is not running to be suspended");
123         return;
124     }
125     m_widget->Suspend();
126     m_widgetState = WidgetState_Suspended;
127 }
128
129 void WrtClient::OnReset(bundle *b)
130 {
131     LogDebug("OnReset");
132     // bundle argument is freed after OnReset() is returned
133     // So bundle duplication is needed
134     ApplicationDataSingleton::Instance().setBundle(bundle_dup(b));
135
136     if (true == m_initializing) {
137         LogDebug("can not handle reset event");
138         return;
139     }
140     if (true == m_launched) {
141         if (m_widgetState == WidgetState_Stopped) {
142             LogError("Widget is not running to be reset");
143             return;
144         }
145         m_widget->Reset();
146         m_windowData->emitSignalForUserLayout(EDJE_SHOW_BACKWARD_SIGNAL, "");
147         m_widgetState = WidgetState_Running;
148     } else {
149         if (true == checkArgument()) {
150             setStep();
151         } else {
152             showHelpAndQuit();
153         }
154     }
155
156     // low memory callback set
157     appcore_set_event_callback(
158             APPCORE_EVENT_LOW_MEMORY,
159             WrtClient::appcoreLowMemoryCallback,
160             this);
161 }
162
163 void WrtClient::OnTerminate()
164 {
165     LogDebug("Wrt Shutdown now");
166     shutdownStep();
167 }
168
169 void WrtClient::showHelpAndQuit()
170 {
171     printf("Usage: wrt-client [OPTION]... [WIDGET: ID]...\n"
172            "launch widgets.\n"
173            "Mandatory arguments to long options are mandatory for short "
174            "options too.\n"
175            "  -h,    --help                                 show this help\n"
176            "  -l,    --launch                               "
177            "launch widget with given tizen ID\n"
178            "  -t,    --tizen                                "
179            "launch widget with given tizen ID\n"
180            "\n");
181
182     Quit();
183 }
184
185 bool WrtClient::checkArgument()
186 {
187     std::string tizenId = getTizenIdFromArgument(m_argc, m_argv);
188
189     if (tizenId.empty()) {
190         // Just show help
191         return false;
192     } else {
193 #ifdef MULTIPROCESS_SERVICE_SUPPORT
194         const char * SERVICE_POSTFIX = "-__SERVICE_PROCESS__";
195         std::size_t pos = tizenId.find(SERVICE_POSTFIX);
196         if (pos != std::string::npos) {
197             std::string id = tizenId.substr(pos);
198             id.erase(strlen(SERVICE_POSTFIX));
199             std::stringstream s(id);
200             unsigned serviceIndex;
201             s >> serviceIndex;
202             m_serviceIndex = serviceIndex;
203             tizenId.erase(pos);
204             LogDebug("service index " << serviceIndex);
205         }
206 #endif
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_serviceIndex);
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         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     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     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     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
846 void set_env()
847 {
848     // set evas backend type
849     if (!getenv("ELM_ENGINE"))
850     {
851         if (!setenv("ELM_ENGINE", "gl", 1))
852         {
853             LogDebug("Enable backend");
854         }
855     }
856     else
857     {
858         LogDebug("ELM_ENGINE : " << getenv("ELM_ENGINE"));
859     }
860
861 #ifndef TIZEN_PUBLIC
862     setenv("COREGL_FASTPATH", "1", 1);
863 #endif
864     setenv("CAIRO_GL_COMPOSITOR", "msaa", 1);
865     setenv("CAIRO_GL_LAZY_FLUSHING", "yes", 1);
866     setenv("ELM_IMAGE_CACHE", "0", 1);
867 }
868
869
870 int main(int argc,
871          char *argv[])
872 {
873     // process pool - store arg's value
874     app_argc = argc;
875     app_argv = argv;
876
877     UNHANDLED_EXCEPTION_HANDLER_BEGIN
878     {
879         ADD_PROFILING_POINT("main-entered", "point");
880
881         // Set log tagging
882         DPL::Log::LogSystemSingleton::Instance().SetTag("WRT");
883
884         // Set environment variables
885         set_env();
886
887         if (argc > 1 && argv[1] != NULL && !strcmp(argv[1], "-d"))
888         {
889             LogInfo("Entered dummy process mode");
890             sprintf(argv[0], "%s                                              ",
891                     DUMMY_PROCESS_PATH);
892
893             LogInfo("Prepare ewk_context");
894             appcore_set_i18n("wrt-client", NULL);
895             ewk_set_arguments(argc, argv);
896             setenv("WRT_LAUNCHING_PERFORMANCE", "1", 1);
897             s_preparedEwkContext = ewk_context_new_with_injected_bundle_path(BUNDLE_PATH);
898
899             if (s_preparedEwkContext == NULL)
900             {
901                 LogInfo("Creating webkit context was failed!");
902                 exit(-1);
903             }
904
905             LogInfo("ewk_context_certificate_file_set()");
906             ewk_context_certificate_file_set(s_preparedEwkContext, caCertPath);
907
908             int client_fd = __connect_process_pool_server();
909
910             if (client_fd == -1)
911             {
912                 LogInfo("Connecting process_pool_server was failed!");
913                 exit(-1);
914             }
915
916             LogInfo("Prepare window_data");
917             // Temporarily change HOME path to app
918             // This change is needed for getting elementary profile
919             // /opt/home/app/.elementary/config/mobile/base.cfg
920             const char* backupEnv = getenv(HOME);
921             setenv(HOME, APP_HOME_PATH, 1);
922             LogInfo("elm_init()");
923             elm_init(argc, argv);
924             setenv(HOME, backupEnv, 1);
925
926             LogInfo("WindowData()");
927             s_preparedWindowData = new WindowData(static_cast<unsigned long>(getpid()));
928
929             Ecore_Fd_Handler* fd_handler = ecore_main_fd_handler_add(client_fd,
930                                            (Ecore_Fd_Handler_Flags)(ECORE_FD_READ|ECORE_FD_ERROR),
931                                            proces_pool_fd_handler, NULL, NULL, NULL);
932
933             if (fd_handler == NULL)
934             {
935                 LogInfo("fd_handler is NULL");
936                 exit(-1);
937             }
938
939             setpriority(PRIO_PROCESS, 0, 0);
940
941             LogDebug("ecore_main_loop_begin()");
942             ecore_main_loop_begin();
943             LogDebug("ecore_main_loop_begin()_end");
944
945             std::string tizenId = WrtClient::getTizenIdFromArgument(argc, argv);
946             PluginModuleSupport::init(s_preparedEwkContext, tizenId);
947
948         }
949         else
950         {
951             // This code is to fork a web process without exec.
952             std::string tizenId = WrtClient::getTizenIdFromArgument(argc, argv);
953
954             if (!tizenId.empty())
955             {
956 #ifdef MULTIPROCESS_SERVICE_SUPPORT
957                 std::size_t pos = tizenId.find("-__SERVICE_PROCESS__");
958                 if (pos != std::string::npos) {
959                     tizenId.erase(pos);
960                 }
961 #endif
962                 LogDebug("Launching by fork mode");
963                 // Language env setup
964                 appcore_set_i18n("wrt-client", NULL);
965                 ewk_set_arguments(argc, argv);
966                 setenv("WRT_LAUNCHING_PERFORMANCE", "1", 1);
967                 s_preparedEwkContext = ewk_context_new_with_injected_bundle_path(
968                         BUNDLE_PATH);
969
970                 if (s_preparedEwkContext == NULL)
971                 {
972                     LogInfo("Creating webkit context was failed!");
973                     Wrt::Popup::PopupInvoker().showInfo("Error", "Creating webkit context was failed.", "OK");
974                     exit(-1);
975                 }
976
977                 // plugin init
978                 PluginModuleSupport::init(s_preparedEwkContext, tizenId);
979
980                 LogInfo("ewk_context_certificate_file_set()");
981                 ewk_context_certificate_file_set(s_preparedEwkContext, caCertPath);
982             }
983         }
984
985         // Output on stdout will be flushed after every newline character,
986         // even if it is redirected to a pipe. This is useful for running
987         // from a script and parsing output.
988         // (Standard behavior of stdlib is to use full buffering when
989         // redirected to a pipe, which means even after an end of line
990         // the output may not be flushed).
991         setlinebuf(stdout);
992
993         WrtClient app(app_argc, app_argv);
994
995         ADD_PROFILING_POINT("Before appExec", "point");
996         int ret = app.Exec();
997         LogDebug("App returned: " << ret);
998         ret = app.getReturnStatus();
999         LogDebug("WrtClient returned: " << ret);
1000         return ret;
1001     }
1002     UNHANDLED_EXCEPTION_HANDLER_END
1003 }