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