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