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