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