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