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