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