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