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