[Release] wrt_0.8.178
[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 "webkit/bundles/plugin_module_support.h"
36 #include <popup-runner/PopupInvoker.h>
37 #include <prepare_external_storage.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 std::string VIEWMODE_TYPE_FULLSCREEN = "fullscreen";
49 const std::string VIEWMODE_TYPE_MAXIMIZED = "maximized";
50 char const* const ELM_SWALLOW_CONTENT = "elm.swallow.content";
51 const char* const BUNDLE_PATH = "/usr/lib/wrt-wk2-bundles/libwrt-wk2-bundle.so";
52 const char* const caCertPath = "/opt/usr/share/certs/ca-certificate.crt";
53
54 // process pool
55 const char* const DUMMY_PROCESS_PATH = "/usr/bin/wrt_launchpad_daemon_candidate";
56 static Ewk_Context* s_preparedEwkContext = NULL;
57 static WindowData*  s_preparedWindowData = NULL;
58 static int    app_argc = 0;
59 static char** app_argv = NULL;
60
61 // orientation
62 const int WIN_ORIENTATION_PORTRAIT_PRIMARY_ANGLE = 0;
63 const int WIN_ORIENTATION_LANDSCAPE_PRIMARY_ANGLE = 270;
64 const int W3C_ORIENTATION_PORTRAIT_PRIMARY_ANGLE = 0;
65 const int W3C_ORIENTATION_LANDSCAPE_PRIMARY_ANGLE = 90;
66
67 // env
68 const char* const HOME = "HOME";
69 const char* const APP_HOME_PATH = "/opt/home/app";
70
71 WrtClient::WrtClient(int argc, char **argv) :
72     Application(argc, argv, "wrt-client", false),
73     DPL::TaskDecl<WrtClient>(this),
74     m_launched(false),
75     m_initializing(false),
76     m_initialized(false),
77     m_sdkLauncherPid(0),
78     m_debugMode(false),
79     m_debuggerPort(0),
80     m_returnStatus(ReturnStatus::Succeeded),
81     m_widgetState(WidgetState::WidgetState_Stopped)
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
136     if (true == m_initializing) {
137         LogDebug("can not handle reset event");
138         return;
139     }
140     if (true == m_launched) {
141         if (m_widgetState == WidgetState_Stopped) {
142             LogError("Widget is not running to be reset");
143             return;
144         }
145         m_widget->Reset();
146         m_windowData->emitSignalForUserLayout(EDJE_SHOW_BACKWARD_SIGNAL, "");
147         m_widgetState = WidgetState_Running;
148     } else {
149         if (true == checkArgument()) {
150             setStep();
151         } else {
152             showHelpAndQuit();
153         }
154     }
155
156     // low memory callback set
157     appcore_set_event_callback(
158             APPCORE_EVENT_LOW_MEMORY,
159             WrtClient::appcoreLowMemoryCallback,
160             this);
161 }
162
163 void WrtClient::OnTerminate()
164 {
165     LogDebug("Wrt Shutdown now");
166     shutdownStep();
167 }
168
169 void WrtClient::showHelpAndQuit()
170 {
171     printf("Usage: wrt-client [OPTION]... [WIDGET: ID]...\n"
172            "launch widgets.\n"
173            "Mandatory arguments to long options are mandatory for short "
174            "options too.\n"
175            "  -h,    --help                                 show this help\n"
176            "  -l,    --launch                               "
177            "launch widget with given tizen ID\n"
178            "  -t,    --tizen                                "
179            "launch widget with given tizen ID\n"
180            "\n");
181
182     Quit();
183 }
184
185 bool WrtClient::checkArgument()
186 {
187     std::string tizenId = getTizenIdFromArgument(m_argc, m_argv);
188
189     if (tizenId.empty()) {
190         // Just show help
191         return false;
192     } else {
193         m_tizenId = tizenId;
194         LogDebug("Tizen id: " << m_tizenId);
195         return true;
196     }
197 }
198
199 std::string WrtClient::getTizenIdFromArgument(int argc, char **argv)
200 {
201     LogInfo("checkArgument");
202     std::string arg = argv[0];
203
204     if (arg.empty()) {
205         return "";
206     }
207
208     if (arg.find("wrt-client") != std::string::npos) {
209         if (argc <= 1) {
210             return "";
211         }
212
213         arg = argv[1];
214
215         if (arg == "-h" || arg == "--help") {
216             return "";
217         } else if (arg == "-l" || arg == "--launch" ||
218                    arg == "-t" || arg == "--tizen")
219         {
220             if (argc != 3) {
221                 return "";
222             }
223             return argv[2];
224         } else {
225             return "";
226         }
227     } else {
228         // Launch widget based on application basename
229         size_t pos = arg.find_last_of('/');
230
231         if (pos != std::string::npos) {
232             arg = arg.erase(0, pos + 1);
233         }
234
235         return arg;
236     }
237 }
238
239 void WrtClient::setStep()
240 {
241     LogInfo("setStep");
242
243     AddStep(&WrtClient::initStep);
244
245     setSdkLauncherDebugData();
246
247     AddStep(&WrtClient::launchStep);
248     AddStep(&WrtClient::shutdownStep);
249
250     m_initializing = true;
251
252     DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(NextStepEvent());
253 }
254
255 void WrtClient::setSdkLauncherDebugData()
256 {
257     LogDebug("setSdkLauncherDebugData");
258
259     /* check bundle from sdk launcher */
260     bundle *bundleFromSdkLauncher;
261     bundleFromSdkLauncher = bundle_import_from_argv(m_argc, m_argv);
262     const char *bundle_debug = bundle_get_val(bundleFromSdkLauncher, "debug");
263     const char *bundle_pid = bundle_get_val(bundleFromSdkLauncher, "pid");
264     if (bundle_debug != NULL && bundle_pid != NULL) {
265         if (strcmp(bundle_debug, "true") == 0) {
266             m_debugMode = true;
267             m_sdkLauncherPid = atoi(bundle_pid);
268         } else {
269             m_debugMode = false;
270         }
271     }
272     bundle_free(bundleFromSdkLauncher);
273 }
274
275 bool WrtClient::checkDebugMode(SDKDebugData* debugData)
276 {
277     LogError("Checking for debug mode");
278     Assert(m_dao);
279
280     bool debugMode = debugData->debugMode;
281
282     LogInfo("[DEBUG_MODE] Widget is launched in " <<
283             (debugMode ? "DEBUG" : "RETAIL") <<
284             " mode.");
285
286     if (debugMode == true) {
287         // In WAC widget, only test widgets can use web inspector.
288         // In TIZEN widget,
289         // every launched widgets as debug mode can use it.
290         if (m_dao->getWidgetType().appType == WrtDB::APP_TYPE_WAC20) {
291             bool developerMode =
292                 WRT::CoreModuleSingleton::Instance().developerMode();
293             //This code will be activated
294             //after WAC test certificate is used by SDK
295             //bool isTestWidget = view->m_widgetModel->IsTestWidget.Get();
296             //if(!isTestWidget)
297             //{
298             //    LogInfo("This is not WAC Test Widget");
299             //    break;
300             //}
301             if (!developerMode) {
302                 LogInfo("This is not WAC Developer Mode");
303                 debugMode = false;
304             }
305         }
306     }
307     return debugMode;
308 }
309
310 void WrtClient::OnEventReceived(const NextStepEvent& /*event*/)
311 {
312     LogDebug("Executing next step");
313     NextStep();
314 }
315
316 void WrtClient::initStep()
317 {
318     LogDebug("");
319     if (WRT::CoreModuleSingleton::Instance().Init()) {
320         m_initialized = true;
321     } else {
322         m_returnStatus = ReturnStatus::Failed;
323         SwitchToStep(&WrtClient::shutdownStep);
324     }
325
326     // ecore_event_jobs are processed sequentially without concession to
327     // other type events. To give a chance of execute to other events,
328     // ecore_timer_add was used.
329     DPL::Event::ControllerEventHandler<NextStepEvent>::PostTimedEvent(
330         NextStepEvent(), 0.001);
331 }
332
333 bool WrtClient::checkWACTestCertififedWidget()
334 {
335     // WAC Waikiki Beta Release Core Specification: Widget Runtime
336     // 10 Dec 2010
337     //
338     // WR-4710 The WRT MUST enable debug functions only for WAC test widgets
339     // i.e. the functions must not be usable for normal WAC widgets, even when
340     // a WAC test widget is executing.
341     ADD_PROFILING_POINT("DeveloperModeCheck", "start");
342     Assert(!!m_dao);
343     // WAC test widget
344     // A widget signed with a WAC-issued test certificate as described in
345     // Developer Mode.
346
347     bool developerWidget = m_dao->isTestWidget();
348     bool developerMode = WRT::CoreModuleSingleton::Instance().developerMode();
349
350     LogDebug("Is WAC test widget: " << developerWidget);
351     LogDebug("Is developer Mode: " << developerMode);
352
353     if (developerWidget) {
354         if (!developerMode) {
355             LogError("WAC test certified developer widget is needed for " <<
356                      "developer mode");
357             return false;
358         } else {
359             //TODO: WR-4660 (show popup about developer widget
360             //      during launch
361             LogInfo("POPUP: THIS IS TEST WIDGET!");
362         }
363     }
364     ADD_PROFILING_POINT("DeveloperModeCheck", "stop");
365     return true;
366 }
367
368 void WrtClient::loadFinishCallback(Evas_Object* webview)
369 {
370     ADD_PROFILING_POINT("loadFinishCallback", "start");
371     SDKDebugData* debug = new SDKDebugData;
372     debug->debugMode = m_debugMode;
373     debug->pid = new unsigned long(getpid());
374
375     LogInfo("Post result of launch");
376
377     // Start inspector server, if current mode is debugger mode.
378     // In the WK2 case, ewk_view_inspector_server_start should
379     // be called after WebProcess is created.
380     if (checkDebugMode(debug)) {
381         debug->portnum =
382             ewk_view_inspector_server_start(m_widget->GetCurrentWebview(), 0);
383         if (debug->portnum == 0) {
384             LogWarning("Failed to get portnum");
385         } else {
386             LogInfo("Assigned port number for inspector : "
387                     << debug->portnum);
388         }
389     } else {
390         LogDebug("Debug mode is disabled");
391     }
392
393     //w3c packaging test debug (message on 4>)
394     const char * makeScreen = getenv(W3C_DEBUG_ENV_VARIABLE);
395     if (makeScreen != NULL && strcmp(makeScreen, "1") == 0) {
396         FILE* doutput = fdopen(4, "w");
397         fprintf(doutput, "didFinishLoadForFrameCallback: ready\n");
398         fclose(doutput);
399     }
400
401     if (webview) {
402         LogDebug("Launch succesfull");
403
404         m_launched = true;
405         m_initializing = false;
406         setlinebuf(stdout);
407         ADD_PROFILING_POINT("loadFinishCallback", "stop");
408         printf("launched\n");
409         fflush(stdout);
410     } else {
411         printf("failed\n");
412
413         m_returnStatus = ReturnStatus::Failed;
414         //shutdownStep
415         DPL::Event::ControllerEventHandler<NextStepEvent>::
416             PostEvent(NextStepEvent());
417     }
418
419     if (debug->debugMode) {
420         LogDebug("Send RT signal to wrt-launcher(pid: " << m_sdkLauncherPid);
421         union sigval sv;
422         /* send real time signal with result to wrt-launcher */
423         if (webview) {
424             LogDebug("userData->portnum : " << debug->portnum);
425             sv.sival_int = debug->portnum;
426         } else {
427             sv.sival_int = -1;
428         }
429         sigqueue(m_sdkLauncherPid, SIGRTMIN, sv);
430     }
431
432     ApplicationDataSingleton::Instance().freeBundle();
433
434     LogDebug("Cleaning wrtClient launch resources...");
435     delete debug->pid;
436     delete debug;
437 }
438
439 void WrtClient::progressFinishCallback()
440 {
441     m_splashScreen->stopSplashScreen();
442 }
443
444 void WrtClient::webkitExitCallback()
445 {
446     LogDebug("window close called, terminating app");
447     SwitchToStep(&WrtClient::shutdownStep);
448     DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
449         NextStepEvent());
450 }
451
452 void WrtClient::webCrashCallback()
453 {
454     LogError("webProcess crashed");
455     SwitchToStep(&WrtClient::shutdownStep);
456     DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
457         NextStepEvent());
458 }
459
460 void WrtClient::launchStep()
461 {
462     ADD_PROFILING_POINT("launchStep", "start");
463     LogDebug("Launching widget ...");
464
465     ADD_PROFILING_POINT("getRunnableWidgetObject", "start");
466     m_widget = WRT::CoreModuleSingleton::Instance()
467             .getRunnableWidgetObject(m_tizenId);
468     ADD_PROFILING_POINT("getRunnableWidgetObject", "stop");
469
470     if (!m_widget) {
471         LogError("RunnableWidgetObject is NULL, stop launchStep");
472         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
473             NextStepEvent());
474         return;
475     }
476
477     if (m_widgetState == WidgetState_Running) {
478         LogWarning("Widget already running, stop launchStep");
479         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
480             NextStepEvent());
481         return;
482     }
483
484     if (m_widgetState == WidgetState_Authorizing) {
485         LogWarning("Widget already authorizing, stop launchStep");
486         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
487             NextStepEvent());
488         return;
489     }
490
491     m_dao.reset(new WrtDB::WidgetDAOReadOnly(DPL::FromASCIIString(m_tizenId)));
492     DPL::Optional<DPL::String> defloc = m_dao->getDefaultlocale();
493     if (!defloc.IsNull()) {
494         LanguageTagsProviderSingleton::Instance().addWidgetDefaultLocales(
495             *defloc);
496     }
497
498     PrepareExternalStorageSingleton::Instance().Initialize(m_dao->getTizenPkgId());
499
500     /* remove language change callback */
501     /*
502     LocalizationSetting::SetLanguageChangedCallback(
503             languageChangedCallback, this);
504     */
505
506     ADD_PROFILING_POINT("CreateWindow", "start");
507     if (s_preparedWindowData == NULL) {
508         m_windowData.reset(new WindowData(static_cast<unsigned long>(getpid()), true));
509     } else {
510         m_windowData.reset(s_preparedWindowData);
511         s_preparedWindowData = NULL;
512     }
513     ADD_PROFILING_POINT("CreateWindow", "stop");
514     evas_object_show(m_windowData->m_win);
515     // rotate window to initial value
516     setOrientationWindow();
517
518     WRT::UserDelegatesPtr cbs(new WRT::UserDelegates);
519     ADD_PROFILING_POINT("Create splash screen", "start");
520     m_splashScreen.reset(
521         new SplashScreenSupport(m_windowData->m_win));
522     if (m_splashScreen->createSplashScreen(m_dao->getSplashImgSrc())) {
523         m_splashScreen->startSplashScreen();
524         cbs->progressFinish = DPL::MakeDelegate(
525                 this,
526                 &WrtClient::
527                     progressFinishCallback);
528     }
529     ADD_PROFILING_POINT("Create splash screen", "stop");
530     DPL::OptionalString startUrl = W3CFileLocalization::getStartFile(m_dao);
531     if (!m_widget->PrepareView(DPL::ToUTF8String(*startUrl),
532             m_windowData->m_win, s_preparedEwkContext))
533     {
534         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
535             NextStepEvent());
536         return;
537     }
538     // send rotate information to ewk
539     setOrientationEwk();
540
541     //you can't show window with splash screen before PrepareView
542     //ewk_view_add_with_context() in viewLogic breaks window
543
544     m_windowData->init();
545
546     WrtDB::WidgetLocalizedInfo localizedInfo =
547         W3CFileLocalization::getLocalizedInfo(m_dao);
548     std::string name = "";
549     if (!(localizedInfo.name.IsNull())) {
550         name = DPL::ToUTF8String(*(localizedInfo.name));
551     }
552     elm_win_title_set(m_windowData->m_win, name.c_str());
553
554     initializeWindowModes();
555     connectElmCallback();
556
557     if (!checkWACTestCertififedWidget()) {
558         LogWarning("WAC Certificate failed, stop launchStep");
559         return;
560     }
561
562     m_widgetState = WidgetState_Authorizing;
563     if (!m_widget->CheckBeforeLaunch()) {
564         LogError("CheckBeforeLaunch failed, stop launchStep");
565         DPL::Event::ControllerEventHandler<NextStepEvent>::PostEvent(
566             NextStepEvent());
567         return;
568     }
569     LogInfo("Widget launch accepted. Entering running state");
570     m_widgetState = WidgetState_Running;
571
572     cbs->loadFinish = DPL::MakeDelegate(this, &WrtClient::loadFinishCallback);
573     cbs->bufferSet = DPL::MakeDelegate(this, &WrtClient::setLayout);
574     cbs->bufferUnset = DPL::MakeDelegate(this, &WrtClient::unsetLayout);
575     cbs->webkitExit = DPL::MakeDelegate(this, &WrtClient::webkitExitCallback);
576     cbs->webCrash = DPL::MakeDelegate(this, &WrtClient::webCrashCallback);
577     cbs->toggleFullscreen = DPL::MakeDelegate(
578             m_windowData.get(), &WindowData::toggleFullscreen);
579
580     m_widget->SetUserDelegates(cbs);
581     m_widget->Show();
582
583     m_windowData->emitSignalForUserLayout(EDJE_SHOW_BACKWARD_SIGNAL, "");
584
585     ADD_PROFILING_POINT("launchStep", "stop");
586 }
587
588 void WrtClient::initializeWindowModes()
589 {
590     Assert(m_windowData);
591     Assert(m_dao);
592     auto windowModes = m_dao->getWindowModes();
593     bool fullscreen = false;
594     bool backbutton = false;
595     if (m_dao->getWidgetType().appType == WrtDB::APP_TYPE_TIZENWEBAPP) {
596         WidgetSettings widgetSettings;
597         m_dao->getWidgetSettings(widgetSettings);
598         WidgetSettingList settings(widgetSettings);
599         backbutton =
600             (settings.getBackButtonPresence() == BackButton_Enable);
601     }
602
603     FOREACH(it, windowModes)
604     {
605         std::string viewMode = DPL::ToUTF8String(*it);
606         if (viewMode == VIEWMODE_TYPE_FULLSCREEN) {
607             fullscreen = true;
608             break;
609         } else if (viewMode == VIEWMODE_TYPE_MAXIMIZED) {
610             break;
611         }
612     }
613
614     m_windowData->setViewMode(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
627     This->m_widget->Backward();
628 }
629
630 int WrtClient::appcoreLowMemoryCallback(void* /*data*/)
631 {
632     LogInfo("appcoreLowMemoryCallback");
633     //WrtClient* This = static_cast<WrtClient*>(data);
634
635     // TODO call RunnableWidgetObject API regarding low memory
636     // The API should be implemented
637
638     return 0;
639 }
640
641 void WrtClient::setOrientationWindow(void)
642 {
643     Assert(m_windowData);
644     Assert(m_dao);
645
646     WidgetSettings widgetSettings;
647     m_dao->getWidgetSettings(widgetSettings);
648     WidgetSettingList settings(widgetSettings);
649     WidgetSettingScreenLock rotationValue = settings.getRotationValue();
650     if (rotationValue == Screen_Portrait) {
651         elm_win_wm_rotation_preferred_rotation_set(
652             m_windowData->m_win,
653             WIN_ORIENTATION_PORTRAIT_PRIMARY_ANGLE);
654     } else if (rotationValue == Screen_Landscape) {
655         elm_win_wm_rotation_preferred_rotation_set(
656             m_windowData->m_win,
657             WIN_ORIENTATION_LANDSCAPE_PRIMARY_ANGLE);
658     } else {
659         elm_win_wm_rotation_preferred_rotation_set(
660             m_windowData->m_win,
661             WIN_ORIENTATION_PORTRAIT_PRIMARY_ANGLE);
662     }
663 }
664
665 void WrtClient::setOrientationEwk(void)
666 {
667     Assert(m_widget);
668     Assert(m_dao);
669
670     WidgetSettings widgetSettings;
671     m_dao->getWidgetSettings(widgetSettings);
672     WidgetSettingList settings(widgetSettings);
673     WidgetSettingScreenLock rotationValue = settings.getRotationValue();
674     if (rotationValue == Screen_Portrait) {
675         ewk_view_orientation_send(
676             m_widget->GetCurrentWebview(),
677              W3C_ORIENTATION_PORTRAIT_PRIMARY_ANGLE);
678     } else if (rotationValue == Screen_Landscape) {
679         ewk_view_orientation_send(
680             m_widget->GetCurrentWebview(),
681             W3C_ORIENTATION_LANDSCAPE_PRIMARY_ANGLE);
682     } else {
683         ewk_view_orientation_send(
684             m_widget->GetCurrentWebview(),
685             W3C_ORIENTATION_PORTRAIT_PRIMARY_ANGLE);
686     }
687 }
688
689 void WrtClient::connectElmCallback()
690 {
691     Assert(m_windowData);
692     Assert(m_dao);
693     WidgetSettings widgetSettings;
694     m_dao->getWidgetSettings(widgetSettings);
695     WidgetSettingList settings(widgetSettings);
696     if (settings.getBackButtonPresence() == BackButton_Enable) {
697         m_windowData->addFloatBackButtonCallback(
698             "clicked",
699             &WrtClient::backButtonCallback,
700             this);
701     }
702 }
703
704 void WrtClient::setLayout(Evas_Object* newBuffer)
705 {
706     LogDebug("add new webkit buffer to window");
707     Assert(newBuffer);
708
709     elm_object_part_content_set(m_windowData->m_user_layout,
710                                 ELM_SWALLOW_CONTENT,
711                                 newBuffer);
712
713     evas_object_show(newBuffer);
714 }
715
716 void WrtClient::unsetLayout(Evas_Object* currentBuffer)
717 {
718     LogDebug("remove current webkit buffer from window");
719     Assert(currentBuffer);
720     evas_object_hide(currentBuffer);
721
722     elm_object_part_content_unset(m_windowData->m_user_layout,
723                                   ELM_SWALLOW_CONTENT);
724 }
725
726 void WrtClient::shutdownStep()
727 {
728     LogDebug("Closing Wrt connection ...");
729
730     if (m_widget && m_widgetState) {
731         m_widgetState = WidgetState_Stopped;
732         m_widget->Hide();
733         m_widget.reset();
734         ewk_context_delete(s_preparedEwkContext);
735         PrepareExternalStorageSingleton::Instance().Deinitialize();
736         WRT::CoreModuleSingleton::Instance().Terminate();
737     }
738     if (m_initialized) {
739         m_initialized = false;
740     }
741     m_windowData.reset();
742     Quit();
743 }
744
745 int WrtClient::languageChangedCallback(void *data)
746 {
747     LogDebug("Language Changed");
748     if (!data) {
749         return 0;
750     }
751     WrtClient* wrtClient = static_cast<WrtClient*>(data);
752     if (!(wrtClient->m_dao)) {
753         return 0;
754     }
755
756     // reset function fetches system locales and recreates language tags
757     LanguageTagsProviderSingleton::Instance().resetLanguageTags();
758     // widget default locales are added to language tags below
759     DPL::OptionalString defloc = wrtClient->m_dao->getDefaultlocale();
760     if (!defloc.IsNull()) {
761         LanguageTagsProviderSingleton::Instance().addWidgetDefaultLocales(
762             *defloc);
763     }
764
765     if (wrtClient->m_launched &&
766         wrtClient->m_widgetState != WidgetState_Stopped)
767     {
768         wrtClient->m_widget->ReloadStartPage();
769     }
770     return 0;
771 }
772
773 void WrtClient::Quit()
774 {
775     ewk_shutdown();
776     DPL::Application::Quit();
777 }
778
779 static Eina_Bool proces_pool_fd_handler(void* /*data*/, Ecore_Fd_Handler *handler)
780 {
781     int fd = ecore_main_fd_handler_fd_get(handler);
782
783     if (ecore_main_fd_handler_active_get(handler, ECORE_FD_ERROR))
784     {
785         LogDebug("ECORE_FD_ERROR");
786         close(fd);
787         exit(-1);
788         return ECORE_CALLBACK_CANCEL;
789     }
790
791     if (ecore_main_fd_handler_active_get(handler, ECORE_FD_READ))
792     {
793         LogDebug("ECORE_FD_READ");
794         {
795             app_pkt_t* pkt = (app_pkt_t*) malloc(sizeof(char) * AUL_SOCK_MAXBUFF);
796             memset(pkt, 0, AUL_SOCK_MAXBUFF);
797
798             int recv_ret = recv(fd, pkt, AUL_SOCK_MAXBUFF, 0);
799
800             close(fd);
801
802             if (recv_ret == -1)
803             {
804                 LogDebug("recv error!");
805                 exit(-1);
806             }
807             LogDebug("recv_ret : " << recv_ret << ", pkt->len : " << pkt->len);
808
809             ecore_main_fd_handler_del(handler);
810
811             __wrt_launchpad_main_loop(pkt, app_argv[0], &app_argc, &app_argv);
812
813             free(pkt);
814         }
815
816         ecore_main_loop_quit();
817         return ECORE_CALLBACK_CANCEL;
818     }
819
820     return ECORE_CALLBACK_CANCEL;
821 }
822
823
824 void set_env()
825 {
826     // set evas backend type
827     if (!getenv("ELM_ENGINE"))
828     {
829         if (!setenv("ELM_ENGINE", "gl", 1))
830         {
831             LogDebug("Enable backend");
832         }
833     }
834     else
835     {
836         LogDebug("ELM_ENGINE : " << getenv("ELM_ENGINE"));
837     }
838
839 #ifndef TIZEN_PUBLIC
840     setenv("COREGL_FASTPATH", "1", 1);
841 #endif
842     setenv("CAIRO_GL_COMPOSITOR", "msaa", 1);
843     setenv("CAIRO_GL_LAZY_FLUSHING", "yes", 1);
844     setenv("ELM_IMAGE_CACHE", "0", 1);
845 }
846
847
848 int main(int argc,
849          char *argv[])
850 {
851     // process pool - store arg's value
852     app_argc = argc;
853     app_argv = argv;
854
855     UNHANDLED_EXCEPTION_HANDLER_BEGIN
856     {
857         ADD_PROFILING_POINT("main-entered", "point");
858
859         // Set log tagging
860         DPL::Log::LogSystemSingleton::Instance().SetTag("WRT");
861
862         // Set environment variables
863         set_env();
864
865         if (argc > 1 && argv[1] != NULL && !strcmp(argv[1], "-d"))
866         {
867             LogInfo("Entered dummy process mode");
868             sprintf(argv[0], "%s                                              ",
869                     DUMMY_PROCESS_PATH);
870
871             LogInfo("Prepare ewk_context");
872             appcore_set_i18n("wrt-client", NULL);
873             ewk_set_arguments(argc, argv);
874             setenv("WRT_LAUNCHING_PERFORMANCE", "1", 1);
875             s_preparedEwkContext = ewk_context_new_with_injected_bundle_path(BUNDLE_PATH);
876
877             if (s_preparedEwkContext == NULL)
878             {
879                 LogInfo("Creating webkit context was failed!");
880                 exit(-1);
881             }
882
883             LogInfo("ewk_context_certificate_file_set()");
884             ewk_context_certificate_file_set(s_preparedEwkContext, caCertPath);
885
886             int client_fd = __connect_process_pool_server();
887
888             if (client_fd == -1)
889             {
890                 LogInfo("Connecting process_pool_server was failed!");
891                 exit(-1);
892             }
893
894             LogInfo("Prepare window_data");
895             // Temporarily change HOME path to app
896             // This change is needed for getting elementary profile
897             // /opt/home/app/.elementary/config/mobile/base.cfg
898             const char* backupEnv = getenv(HOME);
899             setenv(HOME, APP_HOME_PATH, 1);
900             LogInfo("elm_init()");
901             elm_init(argc, argv);
902             setenv(HOME, backupEnv, 1);
903
904             LogInfo("WindowData()");
905             s_preparedWindowData = new WindowData(static_cast<unsigned long>(getpid()));
906
907             Ecore_Fd_Handler* fd_handler = ecore_main_fd_handler_add(client_fd,
908                                            (Ecore_Fd_Handler_Flags)(ECORE_FD_READ|ECORE_FD_ERROR),
909                                            proces_pool_fd_handler, NULL, NULL, NULL);
910
911             if (fd_handler == NULL)
912             {
913                 LogInfo("fd_handler is NULL");
914                 exit(-1);
915             }
916
917             setpriority(PRIO_PROCESS, 0, 0);
918
919             LogDebug("ecore_main_loop_begin()");
920             ecore_main_loop_begin();
921             LogDebug("ecore_main_loop_begin()_end");
922
923             std::string tizenId = WrtClient::getTizenIdFromArgument(argc, argv);
924             PluginModuleSupport::init(s_preparedEwkContext, tizenId);
925
926         }
927         else
928         {
929             // This code is to fork a web process without exec.
930             std::string tizenId = WrtClient::getTizenIdFromArgument(argc, argv);
931
932             if (!tizenId.empty())
933             {
934                 LogDebug("Launching by fork mode");
935                 // Language env setup
936                 appcore_set_i18n("wrt-client", NULL);
937                 ewk_set_arguments(argc, argv);
938                 setenv("WRT_LAUNCHING_PERFORMANCE", "1", 1);
939                 s_preparedEwkContext = ewk_context_new_with_injected_bundle_path(
940                         BUNDLE_PATH);
941
942                 if (s_preparedEwkContext == NULL)
943                 {
944                     LogInfo("Creating webkit context was failed!");
945                     Wrt::Popup::PopupInvoker().showInfo("Error", "Creating webkit context was failed.", "OK");
946                     exit(-1);
947                 }
948
949                 // plugin init
950                 PluginModuleSupport::init(s_preparedEwkContext, tizenId);
951
952                 LogInfo("ewk_context_certificate_file_set()");
953                 ewk_context_certificate_file_set(s_preparedEwkContext, caCertPath);
954             }
955         }
956
957         // Output on stdout will be flushed after every newline character,
958         // even if it is redirected to a pipe. This is useful for running
959         // from a script and parsing output.
960         // (Standard behavior of stdlib is to use full buffering when
961         // redirected to a pipe, which means even after an end of line
962         // the output may not be flushed).
963         setlinebuf(stdout);
964
965         WrtClient app(app_argc, app_argv);
966
967         ADD_PROFILING_POINT("Before appExec", "point");
968         int ret = app.Exec();
969         LogDebug("App returned: " << ret);
970         ret = app.getReturnStatus();
971         LogDebug("WrtClient returned: " << ret);
972         return ret;
973     }
974     UNHANDLED_EXCEPTION_HANDLER_END
975 }