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