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