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