[Release] wrt_0.8.181
[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 #ifdef MULTIPROCESS_SERVICE_SUPPORT
481     m_widget = WRT::CoreModuleSingleton::Instance()
482             .getRunnableWidgetObject(m_tizenId, m_serviceIndex);
483 #else
484 m_widget = WRT::CoreModuleSingleton::Instance()
485         .getRunnableWidgetObject(m_tizenId);
486 #endif
487     ADD_PROFILING_POINT("getRunnableWidgetObject", "stop");
488
489     if (!m_widget) {
490         LogError("RunnableWidgetObject is NULL, stop launchStep");
491         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
492             NextStepEvent());
493         return;
494     }
495
496     if (m_widgetState == WidgetState_Running) {
497         LogWarning("Widget already running, stop launchStep");
498         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
499             NextStepEvent());
500         return;
501     }
502
503     if (m_widgetState == WidgetState_Authorizing) {
504         LogWarning("Widget already authorizing, stop launchStep");
505         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
506             NextStepEvent());
507         return;
508     }
509
510     m_dao.reset(new WrtDB::WidgetDAOReadOnly(DPL::FromASCIIString(m_tizenId)));
511     DPL::Optional<DPL::String> defloc = m_dao->getDefaultlocale();
512     if (!defloc.IsNull()) {
513         LanguageTagsProviderSingleton::Instance().addWidgetDefaultLocales(
514             *defloc);
515     }
516
517     PrepareExternalStorageSingleton::Instance().Initialize(m_dao->getTizenPkgId());
518
519     /* remove language change callback */
520     /*
521     LocalizationSetting::SetLanguageChangedCallback(
522             languageChangedCallback, this);
523     */
524
525     ADD_PROFILING_POINT("CreateWindow", "start");
526     if (s_preparedWindowData == NULL) {
527         m_windowData.reset(new WindowData(static_cast<unsigned long>(getpid()), true));
528     } else {
529         m_windowData.reset(s_preparedWindowData);
530         s_preparedWindowData = NULL;
531     }
532     ADD_PROFILING_POINT("CreateWindow", "stop");
533     evas_object_show(m_windowData->m_win);
534     // rotate window to initial value
535     setOrientationWindow();
536
537     WRT::UserDelegatesPtr cbs(new WRT::UserDelegates);
538     ADD_PROFILING_POINT("Create splash screen", "start");
539     m_splashScreen.reset(
540         new SplashScreenSupport(m_windowData->m_win));
541     if (m_splashScreen->createSplashScreen(m_dao->getSplashImgSrc())) {
542         m_splashScreen->startSplashScreen();
543         cbs->progressFinish = DPL::MakeDelegate(
544                 this,
545                 &WrtClient::
546                     progressFinishCallback);
547     }
548     ADD_PROFILING_POINT("Create splash screen", "stop");
549     DPL::OptionalString startUrl = W3CFileLocalization::getStartFile(m_dao);
550     if (!m_widget->PrepareView(DPL::ToUTF8String(*startUrl),
551             m_windowData->m_win, s_preparedEwkContext))
552     {
553         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
554             NextStepEvent());
555         return;
556     }
557     // send rotate information to ewk
558     setOrientationEwk();
559
560     //you can't show window with splash screen before PrepareView
561     //ewk_view_add_with_context() in viewLogic breaks window
562
563     m_windowData->init();
564
565     WrtDB::WidgetLocalizedInfo localizedInfo =
566         W3CFileLocalization::getLocalizedInfo(m_dao);
567     std::string name = "";
568     if (!(localizedInfo.name.IsNull())) {
569         name = DPL::ToUTF8String(*(localizedInfo.name));
570     }
571     elm_win_title_set(m_windowData->m_win, name.c_str());
572
573     initializeWindowModes();
574     connectElmCallback();
575
576     if (!checkWACTestCertififedWidget()) {
577         LogWarning("WAC Certificate failed, stop launchStep");
578         return;
579     }
580
581     m_widgetState = WidgetState_Authorizing;
582     if (!m_widget->CheckBeforeLaunch()) {
583         LogError("CheckBeforeLaunch failed, stop launchStep");
584         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
585             NextStepEvent());
586         return;
587     }
588     LogInfo("Widget launch accepted. Entering running state");
589     m_widgetState = WidgetState_Running;
590
591     cbs->loadFinish = DPL::MakeDelegate(this, &WrtClient::loadFinishCallback);
592     cbs->bufferSet = DPL::MakeDelegate(this, &WrtClient::setLayout);
593     cbs->bufferUnset = DPL::MakeDelegate(this, &WrtClient::unsetLayout);
594     cbs->webkitExit = DPL::MakeDelegate(this, &WrtClient::webkitExitCallback);
595     cbs->webCrash = DPL::MakeDelegate(this, &WrtClient::webCrashCallback);
596     cbs->toggleFullscreen = DPL::MakeDelegate(
597             m_windowData.get(), &WindowData::toggleFullscreen);
598
599     m_widget->SetUserDelegates(cbs);
600     m_widget->Show();
601
602     m_windowData->emitSignalForUserLayout(EDJE_SHOW_BACKWARD_SIGNAL, "");
603
604     ADD_PROFILING_POINT("launchStep", "stop");
605 }
606
607 void WrtClient::initializeWindowModes()
608 {
609     Assert(m_windowData);
610     Assert(m_dao);
611     auto windowModes = m_dao->getWindowModes();
612     bool fullscreen = false;
613     bool backbutton = false;
614     if (m_dao->getWidgetType().appType == WrtDB::APP_TYPE_TIZENWEBAPP) {
615         WidgetSettings widgetSettings;
616         m_dao->getWidgetSettings(widgetSettings);
617         WidgetSettingList settings(widgetSettings);
618         backbutton =
619             (settings.getBackButtonPresence() == BackButton_Enable);
620     }
621
622     FOREACH(it, windowModes)
623     {
624         std::string viewMode = DPL::ToUTF8String(*it);
625         if (viewMode == VIEWMODE_TYPE_FULLSCREEN) {
626             fullscreen = true;
627             break;
628         } else if (viewMode == VIEWMODE_TYPE_MAXIMIZED) {
629             break;
630         }
631     }
632
633     m_windowData->setViewMode(fullscreen,
634                               backbutton);
635 }
636
637 void WrtClient::backButtonCallback(void* data,
638                                    Evas_Object * /*obj*/,
639                                    void * /*event_info*/)
640 {
641     LogInfo("BackButtonCallback");
642     Assert(data);
643
644     WrtClient* This = static_cast<WrtClient*>(data);
645
646     This->m_widget->Backward();
647 }
648
649 int WrtClient::appcoreLowMemoryCallback(void* /*data*/)
650 {
651     LogInfo("appcoreLowMemoryCallback");
652     //WrtClient* This = static_cast<WrtClient*>(data);
653
654     // TODO call RunnableWidgetObject API regarding low memory
655     // The API should be implemented
656
657     return 0;
658 }
659
660 void WrtClient::setOrientationWindow(void)
661 {
662     Assert(m_windowData);
663     Assert(m_dao);
664
665     WidgetSettings widgetSettings;
666     m_dao->getWidgetSettings(widgetSettings);
667     WidgetSettingList settings(widgetSettings);
668     WidgetSettingScreenLock rotationValue = settings.getRotationValue();
669     if (rotationValue == Screen_Portrait) {
670         elm_win_wm_rotation_preferred_rotation_set(
671             m_windowData->m_win,
672             WIN_ORIENTATION_PORTRAIT_PRIMARY_ANGLE);
673     } else if (rotationValue == Screen_Landscape) {
674         elm_win_wm_rotation_preferred_rotation_set(
675             m_windowData->m_win,
676             WIN_ORIENTATION_LANDSCAPE_PRIMARY_ANGLE);
677     } else {
678         elm_win_wm_rotation_preferred_rotation_set(
679             m_windowData->m_win,
680             WIN_ORIENTATION_PORTRAIT_PRIMARY_ANGLE);
681     }
682 }
683
684 void WrtClient::setOrientationEwk(void)
685 {
686     Assert(m_widget);
687     Assert(m_dao);
688
689     WidgetSettings widgetSettings;
690     m_dao->getWidgetSettings(widgetSettings);
691     WidgetSettingList settings(widgetSettings);
692     WidgetSettingScreenLock rotationValue = settings.getRotationValue();
693     if (rotationValue == Screen_Portrait) {
694         ewk_view_orientation_send(
695             m_widget->GetCurrentWebview(),
696              W3C_ORIENTATION_PORTRAIT_PRIMARY_ANGLE);
697     } else if (rotationValue == Screen_Landscape) {
698         ewk_view_orientation_send(
699             m_widget->GetCurrentWebview(),
700             W3C_ORIENTATION_LANDSCAPE_PRIMARY_ANGLE);
701     } else {
702         ewk_view_orientation_send(
703             m_widget->GetCurrentWebview(),
704             W3C_ORIENTATION_PORTRAIT_PRIMARY_ANGLE);
705     }
706 }
707
708 void WrtClient::connectElmCallback()
709 {
710     Assert(m_windowData);
711     Assert(m_dao);
712     WidgetSettings widgetSettings;
713     m_dao->getWidgetSettings(widgetSettings);
714     WidgetSettingList settings(widgetSettings);
715     if (settings.getBackButtonPresence() == BackButton_Enable) {
716         m_windowData->addFloatBackButtonCallback(
717             "clicked",
718             &WrtClient::backButtonCallback,
719             this);
720     }
721 }
722
723 void WrtClient::setLayout(Evas_Object* newBuffer)
724 {
725     LogDebug("add new webkit buffer to window");
726     Assert(newBuffer);
727
728     elm_object_part_content_set(m_windowData->m_user_layout,
729                                 ELM_SWALLOW_CONTENT,
730                                 newBuffer);
731
732     evas_object_show(newBuffer);
733 }
734
735 void WrtClient::unsetLayout(Evas_Object* currentBuffer)
736 {
737     LogDebug("remove current webkit buffer from window");
738     Assert(currentBuffer);
739     evas_object_hide(currentBuffer);
740
741     elm_object_part_content_unset(m_windowData->m_user_layout,
742                                   ELM_SWALLOW_CONTENT);
743 }
744
745 void WrtClient::shutdownStep()
746 {
747     LogDebug("Closing Wrt connection ...");
748
749     if (m_widget && m_widgetState) {
750         m_widgetState = WidgetState_Stopped;
751         m_widget->Hide();
752         m_widget.reset();
753         ewk_context_delete(s_preparedEwkContext);
754         PrepareExternalStorageSingleton::Instance().Deinitialize();
755         WRT::CoreModuleSingleton::Instance().Terminate();
756     }
757     if (m_initialized) {
758         m_initialized = false;
759     }
760     m_windowData.reset();
761     Quit();
762 }
763
764 int WrtClient::languageChangedCallback(void *data)
765 {
766     LogDebug("Language Changed");
767     if (!data) {
768         return 0;
769     }
770     WrtClient* wrtClient = static_cast<WrtClient*>(data);
771     if (!(wrtClient->m_dao)) {
772         return 0;
773     }
774
775     // reset function fetches system locales and recreates language tags
776     LanguageTagsProviderSingleton::Instance().resetLanguageTags();
777     // widget default locales are added to language tags below
778     DPL::OptionalString defloc = wrtClient->m_dao->getDefaultlocale();
779     if (!defloc.IsNull()) {
780         LanguageTagsProviderSingleton::Instance().addWidgetDefaultLocales(
781             *defloc);
782     }
783
784     if (wrtClient->m_launched &&
785         wrtClient->m_widgetState != WidgetState_Stopped)
786     {
787         wrtClient->m_widget->ReloadStartPage();
788     }
789     return 0;
790 }
791
792 void WrtClient::Quit()
793 {
794     ewk_shutdown();
795     DPL::Application::Quit();
796 }
797
798 static Eina_Bool proces_pool_fd_handler(void* /*data*/, Ecore_Fd_Handler *handler)
799 {
800     int fd = ecore_main_fd_handler_fd_get(handler);
801
802     if (ecore_main_fd_handler_active_get(handler, ECORE_FD_ERROR))
803     {
804         LogDebug("ECORE_FD_ERROR");
805
806         if (fd != -1)
807         {
808             close(fd);
809         }
810
811         exit(-1);
812         return ECORE_CALLBACK_CANCEL;
813     }
814
815     if (ecore_main_fd_handler_active_get(handler, ECORE_FD_READ))
816     {
817         LogDebug("ECORE_FD_READ");
818         {
819             app_pkt_t* pkt = (app_pkt_t*) malloc(sizeof(char) * AUL_SOCK_MAXBUFF);
820             memset(pkt, 0, AUL_SOCK_MAXBUFF);
821
822             int recv_ret = recv(fd, pkt, AUL_SOCK_MAXBUFF, 0);
823
824             if (fd != -1)
825             {
826                 close(fd);
827             }
828
829             if (recv_ret == -1)
830             {
831                 LogDebug("recv error!");
832                 exit(-1);
833             }
834             LogDebug("recv_ret : " << recv_ret << ", pkt->len : " << pkt->len);
835
836             ecore_main_fd_handler_del(handler);
837
838             __wrt_launchpad_main_loop(pkt, app_argv[0], &app_argc, &app_argv);
839
840             free(pkt);
841         }
842
843         ecore_main_loop_quit();
844         return ECORE_CALLBACK_CANCEL;
845     }
846
847     return ECORE_CALLBACK_CANCEL;
848 }
849
850
851 void set_env()
852 {
853     // set evas backend type
854     if (!getenv("ELM_ENGINE"))
855     {
856         if (!setenv("ELM_ENGINE", "gl", 1))
857         {
858             LogDebug("Enable backend");
859         }
860     }
861     else
862     {
863         LogDebug("ELM_ENGINE : " << getenv("ELM_ENGINE"));
864     }
865
866 #ifndef TIZEN_PUBLIC
867     setenv("COREGL_FASTPATH", "1", 1);
868 #endif
869     setenv("CAIRO_GL_COMPOSITOR", "msaa", 1);
870     setenv("CAIRO_GL_LAZY_FLUSHING", "yes", 1);
871     setenv("ELM_IMAGE_CACHE", "0", 1);
872 }
873
874
875 int main(int argc,
876          char *argv[])
877 {
878     // process pool - store arg's value
879     app_argc = argc;
880     app_argv = argv;
881
882     UNHANDLED_EXCEPTION_HANDLER_BEGIN
883     {
884         ADD_PROFILING_POINT("main-entered", "point");
885
886         // Set log tagging
887         DPL::Log::LogSystemSingleton::Instance().SetTag("WRT");
888
889         // Set environment variables
890         set_env();
891
892         if (argc > 1 && argv[1] != NULL && !strcmp(argv[1], "-d"))
893         {
894             LogInfo("Entered dummy process mode");
895             sprintf(argv[0], "%s                                              ",
896                     DUMMY_PROCESS_PATH);
897
898             LogInfo("Prepare ewk_context");
899             appcore_set_i18n("wrt-client", NULL);
900             ewk_set_arguments(argc, argv);
901             setenv("WRT_LAUNCHING_PERFORMANCE", "1", 1);
902             s_preparedEwkContext = ewk_context_new_with_injected_bundle_path(BUNDLE_PATH);
903
904             if (s_preparedEwkContext == NULL)
905             {
906                 LogInfo("Creating webkit context was failed!");
907                 exit(-1);
908             }
909
910             LogInfo("ewk_context_certificate_file_set()");
911             ewk_context_certificate_file_set(s_preparedEwkContext, caCertPath);
912
913             int client_fd = __connect_process_pool_server();
914
915             if (client_fd == -1)
916             {
917                 LogInfo("Connecting process_pool_server was failed!");
918                 exit(-1);
919             }
920
921             LogInfo("Prepare window_data");
922             // Temporarily change HOME path to app
923             // This change is needed for getting elementary profile
924             // /opt/home/app/.elementary/config/mobile/base.cfg
925             const char* backupEnv = getenv(HOME);
926             setenv(HOME, APP_HOME_PATH, 1);
927             LogInfo("elm_init()");
928             elm_init(argc, argv);
929             setenv(HOME, backupEnv, 1);
930
931             LogInfo("WindowData()");
932             s_preparedWindowData = new WindowData(static_cast<unsigned long>(getpid()));
933
934             Ecore_Fd_Handler* fd_handler = ecore_main_fd_handler_add(client_fd,
935                                            (Ecore_Fd_Handler_Flags)(ECORE_FD_READ|ECORE_FD_ERROR),
936                                            proces_pool_fd_handler, NULL, NULL, NULL);
937
938             if (fd_handler == NULL)
939             {
940                 LogInfo("fd_handler is NULL");
941                 exit(-1);
942             }
943
944             setpriority(PRIO_PROCESS, 0, 0);
945
946             LogDebug("ecore_main_loop_begin()");
947             ecore_main_loop_begin();
948             LogDebug("ecore_main_loop_begin()_end");
949
950             std::string tizenId = WrtClient::getTizenIdFromArgument(argc, argv);
951             PluginModuleSupport::init(s_preparedEwkContext, tizenId);
952
953         }
954         else
955         {
956             // This code is to fork a web process without exec.
957             std::string tizenId = WrtClient::getTizenIdFromArgument(argc, argv);
958
959             if (!tizenId.empty())
960             {
961 #ifdef MULTIPROCESS_SERVICE_SUPPORT
962                 std::size_t pos = tizenId.find("-__SERVICE_PROCESS__");
963                 if (pos != std::string::npos) {
964                     tizenId.erase(pos);
965                 }
966 #endif
967                 LogDebug("Launching by fork mode");
968                 // Language env setup
969                 appcore_set_i18n("wrt-client", NULL);
970                 ewk_set_arguments(argc, argv);
971                 setenv("WRT_LAUNCHING_PERFORMANCE", "1", 1);
972                 s_preparedEwkContext = ewk_context_new_with_injected_bundle_path(
973                         BUNDLE_PATH);
974
975                 if (s_preparedEwkContext == NULL)
976                 {
977                     LogInfo("Creating webkit context was failed!");
978                     Wrt::Popup::PopupInvoker().showInfo("Error", "Creating webkit context was failed.", "OK");
979                     exit(-1);
980                 }
981
982                 // plugin init
983                 PluginModuleSupport::init(s_preparedEwkContext, tizenId);
984
985                 LogInfo("ewk_context_certificate_file_set()");
986                 ewk_context_certificate_file_set(s_preparedEwkContext, caCertPath);
987             }
988         }
989
990         // Output on stdout will be flushed after every newline character,
991         // even if it is redirected to a pipe. This is useful for running
992         // from a script and parsing output.
993         // (Standard behavior of stdlib is to use full buffering when
994         // redirected to a pipe, which means even after an end of line
995         // the output may not be flushed).
996         setlinebuf(stdout);
997
998         WrtClient app(app_argc, app_argv);
999
1000         ADD_PROFILING_POINT("Before appExec", "point");
1001         int ret = app.Exec();
1002         LogDebug("App returned: " << ret);
1003         ret = app.getReturnStatus();
1004         LogDebug("WrtClient returned: " << ret);
1005         return ret;
1006     }
1007     UNHANDLED_EXCEPTION_HANDLER_END
1008 }