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