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