2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * @file plugin_logic.cpp
18 * @author Piotr Fatyga (p.fatyga@samsung.com)
19 * @author Grzegorz Krawczyk (g.krawczyk@samsung.com)
20 * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
22 * @brief This file is the implementation file of plugin and
23 * feature loading routines
24 * @brief This code is intended to work behind view controller
27 #include "plugin_logic.h"
29 #include <dpl/assert.h>
30 #include <dpl/scoped_array.h>
31 #include <dpl/log/log.h>
32 #include <dpl/foreach.h>
33 #include <dpl/singleton_impl.h>
34 #include <dpl/wrt-dao-ro/widget_dao_read_only.h>
35 #include <dpl/wrt-dao-ro/common_dao_types.h>
36 #include <dpl/wrt-dao-ro/global_config.h>
38 #include <JavaScriptCore/JavaScript.h>
41 #include <sys/types.h>
52 #include <wrt_plugin_export.h>
53 #include <js_overlay_types.h>
57 #include "plugin_model.h"
58 #include "javascript_interface.h"
59 #include "js_function_manager.h"
60 #include "plugin_container_support.h"
62 #include "js_page_session.h"
65 using namespace WrtDB;
66 using namespace WrtPlugins::W3C;
69 const char *LIBRARY_PATH_SEPARATOR = "/";
70 const char *TIZEN_ROOT_FEATURES = "http://tizen.org/privilege/tizen";
73 class JSPageSession::Impl
76 typedef std::set<PluginPtr> LoadedPlugins;
77 typedef std::set<JSGlobalContextRef> LoadedContexts;
80 ///< Widget handle using this session
83 //view for this session
84 JSGlobalContextRef m_context;
86 bool m_sessionStarted;
88 ///< JS object explorer for this session
89 Explorer* m_objectExplorer;
91 PluginContainerSupportPtr m_pluginsSupport;
93 ///< All loaded plugins. Each one must be unloaded. Plugins means
94 //set of features connected with such plugin (library)
95 LoadedPlugins m_loadedPlugins;
97 // Set of currently loaded web pages' contexts. These contexts are
98 // exactly matching with each frames' global context.
99 LoadedContexts m_loadedContexts;
102 PluginPtr loadLibrary(PluginModelPtr& pluginModel);
104 void loadInjectedJavaScript();
105 void installStandardFeatures();
106 void installRootFeatures();
107 void installRequestedFeatures();
109 //returns true if success or false if failed
110 bool installPlugin(PluginModelPtr plugin);
111 bool installPluginOnDemand(PluginModelPtr plugin,
112 JavaScriptObject& parentObject,
113 JSGlobalContextRef context);
115 void unloadPluginsFromSession();
118 Impl(const PluginContainerSupportPtr& containerSupport);
122 void startSession(int widgetHandle,
123 JSGlobalContextRef view,
125 const char* encodedBundle,
130 void performLibrariesUnload();
132 bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle,
133 JavaScriptObject& parentObject,
134 JSGlobalContextRef context);
136 void loadFrame(JSGlobalContextRef context);
137 void unloadFrame(JSGlobalContextRef context);
139 void setCustomProperties(double scaleFactor,
140 const char* encodedBundle,
143 void dispatchJavaScriptEvent(CustomEventType eventType, void* data);
148 JSPageSession::Impl::Impl(const PluginContainerSupportPtr& support) :
149 m_sessionStarted(false)
151 // DPL::Log::LogSystemSingleton::Instance().SetTag("WRT_PLUGINS");
152 LogDebug("Initializing Page Session");
153 m_pluginsSupport = support;
155 // explicit call to keep singleton's lifetime until calling destructor.
156 // JsFunctionManagerSingleton::Instance();
157 // JavaScriptInterfaceSingleton::Instance();
160 JSPageSession::Impl::~Impl()
164 LogError("Must stop widget session before exit!");
168 LogDebug("Deinitializing plugin Logic...");
171 void JSPageSession::Impl::installStandardFeatures()
173 LogInfo("Installing standard widget features...");
175 //add standard functions
176 FOREACH(it, JsFunctionManagerSingleton::Instance().getFunctions())
178 m_objectExplorer->registerObject(*it, NULL);
181 //add standard objects
182 LogDebug("Installing standard extensions...");
184 auto standardPlugins = m_pluginsSupport->getStandardPlugins();
185 FOREACH(it, standardPlugins)
187 //loadFeatureToSession(*it);
191 LogInfo("Standard widget features installed.");
194 void JSPageSession::Impl::installRootFeatures()
196 LogInfo("Installing requested widget features...");
197 WrtDB::FeatureDAOReadOnly dao(TIZEN_ROOT_FEATURES);
198 auto plugin = m_pluginsSupport->getPluginModelById(dao.GetPluginHandle());
199 installPlugin(plugin);
200 LogInfo("requested root feature installed.");
203 bool JSPageSession::Impl::installPlugin(PluginModelPtr plugin)
205 Assert(plugin && "Plugin Model is NULL");
206 auto library = loadLibrary(plugin);
208 LogInfo("Install Plugin '" << library->GetFileName());
213 LogError("Loading library failed");
217 // Register new class
218 FOREACH(it, *(library->GetClassList()))
220 if (!m_objectExplorer->registerObject(*it, NULL)) {
221 LogError("Object Registration failed : " << (*it)->getName());
225 LogDebug("Registered feature.");
229 void JSPageSession::Impl::installRequestedFeatures()
231 LogInfo("Installing requested widget features...");
233 std::list<std::string> allowedFeatures =
234 m_pluginsSupport->getAllowedFeatures(m_widgetHandle);
236 PluginContainerSupport::PluginsList allowedPlugins;
238 FOREACH(feature, allowedFeatures)
240 LogDebug("Processing feature: " << *feature);
242 auto plugin = m_pluginsSupport->getPluginForFeature(*feature);
243 ImplementedObjectsList implObjs =
245 getImplementedObjectsForPluginHandle(plugin->Handle.Get());
247 FOREACH(obj, implObjs)
249 LogDebug("Processing object: " << *obj);
250 /* This can be optimalized, but would need extra data in database.
251 There should be a list of features that are allowed to be
252 installed at widget start */
253 if (obj->find(".") == obj->rfind(".")) {
254 allowedPlugins.push_back(plugin);
255 LogWarning("Plugin will be added: "
256 << plugin->LibraryName.Get());
262 FOREACH(plugin, allowedPlugins)
264 LogDebug("Installation plugin: " << (*plugin)->LibraryName.Get());
265 installPlugin(*plugin);
268 LogInfo("requested features installed.");
271 bool JSPageSession::Impl::loadPluginOnDemand(
272 const WrtDB::DbPluginHandle &pluginHandle,
273 JavaScriptObject& parentObject,
274 JSGlobalContextRef context)
276 LogDebug("load plugin with feature");
278 Assert(parentObject.instance &&
279 !parentObject.name.empty()
280 && "Wrong arguments");
282 if (!m_sessionStarted) {
283 LogError("Session not started");
286 // //TODO here may be a bug. if plugin contains feature rejected and accepted
287 // LogInfo("Installing feature : " << widgetFeature.name);
288 // if (widgetFeature.rejected) {
289 // LogWarning("This api-feature was rejected");
293 // auto plugin = m_pluginsSupport->getPluginModelById(pluginHandle);
295 // LogError("Failed to load plugin. plugin handle: " << pluginHandle);
298 m_pluginsSupport->registerPluginModel(pluginHandle);
299 return installPluginOnDemand(
300 m_pluginsSupport->getPluginModelById(pluginHandle),
305 bool JSPageSession::Impl::installPluginOnDemand(PluginModelPtr plugin,
306 JavaScriptObject& parentObject,
307 JSGlobalContextRef context)
309 Assert(plugin && "Plugin Model is NULL");
310 auto library = loadLibrary(plugin);
312 LogInfo("Install Plugin '" << library->GetFileName());
316 LogError("Loading library failed");
320 if(!(parentObject.instance))
322 LogError("NULL pointer value");
326 JSObjectPtr parent(new JSObject(parentObject.instance));
328 if (!parent->getObject())
330 LogError("NULL pointer value");
335 FOREACH(it, *(library->GetClassList()))
337 bool installationStatus =
338 m_objectExplorer->registerObject(*it,
343 if(!installationStatus)
345 LogError("Object Registration failed : " << (*it)->getName()
346 << "; Parent object name: " << parentObject.name);
351 LogDebug("Plugin on demand registration completed");
355 void JSPageSession::Impl::setCustomProperties(double scaleFactor,
356 const char* encodedBundle,
359 LogInfo("set properties of window object " << scaleFactor << ", "
360 << encodedBundle << ", " << theme);
362 m_objectExplorer->getWindowPropertySupport()
363 ->setScaleToNavigatorProperty(scaleFactor);
364 m_objectExplorer->getWindowPropertySupport()
365 ->setBundleToWindowProperty(encodedBundle);
366 m_objectExplorer->getWindowPropertySupport()
367 ->setThemeToNavigatorProperty(theme);
370 void JSPageSession::Impl::dispatchJavaScriptEvent(CustomEventType eventType, void* data)
372 // Check if session is already started
373 if (!m_sessionStarted) {
374 LogWarning("Session not started!");
378 LogInfo("Request dispatching javascript event");
379 m_objectExplorer->callEventListeners(eventType, data);
382 void JSPageSession::Impl::loadInjectedJavaScript()
386 std::string DIR_PATH = "/usr/etc/wrt/injected-javascript";
387 std::string JS_EXTENSION = ".js";
389 DIR *dir = opendir(DIR_PATH.c_str());
392 LogError("opendir(\"" << DIR_PATH << "\") error!" );
396 struct dirent* libdir;
397 std::list<std::string> jsFiles;
399 // make file list from DIR_PATH
400 while ((libdir = readdir(dir)) != 0)
402 if (strncmp(libdir->d_name, ".", 2) == 0 ||
403 strncmp(libdir->d_name, "..", 3) == 0)
408 std::string filepath = DIR_PATH;
410 filepath += libdir->d_name;
412 std::string lowercase = filepath;
413 std::transform(lowercase.begin(), lowercase.end(), lowercase.begin(),
416 if( lowercase.rfind(JS_EXTENSION) == std::string::npos ||
417 lowercase.length() !=
418 lowercase.rfind(JS_EXTENSION) + JS_EXTENSION.length() )
420 LogError("This is not js file" << filepath);
426 if (stat(filepath.c_str(), &tmp) == -1) {
427 LogError("Failed to open file " << filepath);
431 if (!S_ISREG(tmp.st_mode)) {
432 LogError("This is not a regular file " << filepath);
436 LogInfo("Added : " << filepath);
437 jsFiles.push_back(filepath);
445 LogDebug("load file : " << (*it));
448 std::ifstream fin(it->c_str());
453 std::getline(fin, line);
454 content += line + "\n";
461 JSValueRef exception = NULL;
463 JSStringCreateWithUTF8CString(content.c_str());
465 JSEvaluateScript(m_context, script, NULL, NULL, 1, &exception);
467 JSStringRelease(script);
471 LogDebug("Exception Occured while injecting javascript "
474 JSStringRef exceptionJSString =
475 JSValueToStringCopy(m_context, exception, NULL);
477 JSStringGetMaximumUTF8CStringSize(exceptionJSString);
478 char* exceptionString = new char[size];
479 JSStringGetUTF8CString(exceptionJSString,
480 exceptionString, size);
481 LogDebug("Exception : " << exceptionString);
483 delete [] exceptionString;
484 JSStringRelease(exceptionJSString);
490 void JSPageSession::Impl::startSession(int widgetHandle,
491 JSGlobalContextRef context,
493 const char* encodedBundle,
496 LogInfo("Starting widget session...");
498 // Check if corresponding session if not already created
499 if (m_sessionStarted) {
500 LogWarning("Session already started!");
504 // Create js object explorer object
505 m_objectExplorer = new Explorer(context);
507 m_sessionStarted = true;
508 m_widgetHandle = widgetHandle;
509 m_loadedPlugins.clear();
512 // Register standard features
513 installStandardFeatures();
515 WidgetDAOReadOnly dao(m_widgetHandle);
516 WidgetType appType = dao.getWidgetType();
517 if (appType == WrtDB::APP_TYPE_TIZENWEBAPP) {
518 installRootFeatures();
520 // Register special features
521 installRequestedFeatures();
523 // set scale, bundle as window's property
524 setCustomProperties(scaleFactor, encodedBundle, theme);
526 // Load injected javascript files
527 loadInjectedJavaScript();
528 LogInfo("Widget session started.");
531 void JSPageSession::Impl::stopSession()
533 LogInfo("Stopping widget session...");
535 if (!m_sessionStarted) {
536 LogWarning("Session not started!");
540 unloadPluginsFromSession();
541 m_sessionStarted = false;
543 LogInfo("Widget session stopped.");
547 void JSPageSession::Impl::unloadPluginsFromSession()
549 LogDebug("Unload plugins from session");
551 m_objectExplorer->removePluginsFromIframes();
552 m_objectExplorer->cleanIframesData();
554 // delete js object for overlayed js functions
555 FOREACH(it, JsFunctionManagerSingleton::Instance().getFunctions())
557 m_objectExplorer->deregisterObject(*it);
560 // delete js object for plugins
561 FOREACH(pluginIt, m_loadedPlugins)
563 LogDebug("Unregistering plugin " << (*pluginIt)->GetFileName());
565 (*pluginIt)->OnWidgetStop(m_widgetHandle);
566 LogDebug("Emitted WidgetStop for plugin: " <<
567 (*pluginIt)->GetFileName());
569 FOREACH(it, *((*pluginIt)->GetClassList()))
571 m_objectExplorer->deregisterObject(*it);
575 JavaScriptInterfaceSingleton::Instance().invokeGarbageCollector(m_context);
577 m_loadedPlugins.clear();
579 delete m_objectExplorer;
580 m_objectExplorer = NULL;
586 void JSPageSession::Impl::performLibrariesUnload()
589 LogDebug("Perform library unload");
591 size_t unloadedLibraries = 0;
593 FOREACH(pluginIt, m_loadedPlugins)
595 LogDebug("Preparing library: " << (*pluginIt)->LibraryName.Get());
597 PluginPtr plugin = (*pluginIt)->LibraryInstance.Get();
599 LogWarning("Library not loaded " << (*pluginIt)->LibraryName.Get());
603 (*pluginIt)->LibraryInstance.Set(PluginPtr());
606 LogInfo("unloaded " << unloadedLibraries << " unreferenced libraries!");
610 PluginPtr JSPageSession::Impl::loadLibrary(PluginModelPtr& pluginModel)
612 PluginPtr pluginLib = pluginModel->LibraryInstance.Get();
615 std::string path = pluginModel->LibraryPath.Get() +
616 std::string(LIBRARY_PATH_SEPARATOR) +
617 pluginModel->LibraryName.Get();
619 pluginLib = Plugin::LoadFromFile(path);
623 LogError("Loading library failed");
626 pluginModel->LibraryInstance.Set(pluginLib);
628 LogDebug("On widget start");
629 // This is first time for this plugin, start widget Session
630 pluginLib->OnWidgetStart(
632 m_loadedPlugins.insert(pluginLib);
634 FOREACH(context, m_loadedContexts)
636 pluginLib->OnFrameLoad(*context);
642 LogDebug("Get from LibraryInstance");
643 LogDebug("On widget start");
644 // This is first time for this plugin, start widget Session
645 pluginLib->OnWidgetStart(
647 m_loadedPlugins.insert(pluginLib);
649 FOREACH(context, m_loadedContexts)
651 pluginLib->OnFrameLoad(*context);
659 void JSPageSession::Impl::loadFrame(JSGlobalContextRef context)
661 LogDebug("Load a frame");
663 if (!m_sessionStarted) {
664 LogWarning("Session NOT started!");
668 m_loadedContexts.insert(context);
670 FOREACH(pluginIt, m_loadedPlugins)
672 LogDebug("load plugin to frame" << (*pluginIt)->GetFileName());
674 (*pluginIt)->OnFrameLoad(context);
677 m_objectExplorer->loadFrame(context);
680 void JSPageSession::Impl::unloadFrame(JSGlobalContextRef context)
682 LogDebug("Unload a frame");
684 if (!m_sessionStarted) {
685 LogWarning("Session NOT started!");
689 m_loadedContexts.erase(context);
691 FOREACH(pluginIt, m_loadedPlugins)
693 LogDebug("unload plugin to frame" << (*pluginIt)->GetFileName());
695 (*pluginIt)->OnFrameUnload(context);
698 m_objectExplorer->unloadFrame(context);
702 void JSPageSession::startSession(int widgetHandle,
703 JSGlobalContextRef ctx,
705 const char* encodedBundle,
708 m_impl->startSession(widgetHandle, ctx, scaleFactor, encodedBundle, theme);
711 void JSPageSession::stopSession()
713 m_impl->stopSession();
716 void JSPageSession::performLibrariesUnload()
718 m_impl->performLibrariesUnload();
721 bool JSPageSession::loadPluginOnDemand(
722 const WrtDB::DbPluginHandle &pluginHandle,
723 JavaScriptObject& parentObject,
724 JSGlobalContextRef context)
726 return m_impl->loadPluginOnDemand(pluginHandle, parentObject, context);
729 void JSPageSession::setCustomProperties(double scaleFactor,
730 const char* encodedBundle,
733 m_impl->setCustomProperties(scaleFactor, encodedBundle, theme);
736 void JSPageSession::dispatchJavaScriptEvent(CustomEventType eventType, void* data)
738 m_impl->dispatchJavaScriptEvent(eventType, data);
741 void JSPageSession::loadFrame(JSGlobalContextRef context)
743 m_impl->loadFrame(context);
746 void JSPageSession::unloadFrame(JSGlobalContextRef context)
748 m_impl->unloadFrame(context);
751 JSPageSession::JSPageSession(const PluginContainerSupportPtr& containerSupport)
752 : m_impl(new JSPageSession::Impl(containerSupport))
756 JSPageSession::~JSPageSession()