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 = "/";
72 class JSPageSession::Impl
75 typedef std::set<PluginPtr> LoadedPlugins;
76 typedef std::set<JSGlobalContextRef> LoadedContexts;
79 ///< Widget handle using this session
82 //view for this session
83 JSGlobalContextRef m_context;
85 bool m_sessionStarted;
87 ///< JS object explorer for this session
88 Explorer* m_objectExplorer;
90 PluginContainerSupportPtr m_pluginsSupport;
92 ///< All loaded plugins. Each one must be unloaded. Plugins means
93 //set of features connected with such plugin (library)
94 LoadedPlugins m_loadedPlugins;
96 // Set of currently loaded web pages' contexts. These contexts are
97 // exactly matching with each frames' global context.
98 LoadedContexts m_loadedContexts;
101 PluginPtr loadLibrary(PluginModelPtr& pluginModel);
103 void loadInjectedJavaScript();
104 void installStandardFunctions();
105 void installRootPlugins();
106 void installRequestedFeatures();
108 //returns true if success or false if failed
109 bool installPlugin(PluginModelPtr plugin);
110 bool installPluginOnDemand(PluginModelPtr plugin,
111 JavaScriptObject& parentObject,
112 JSGlobalContextRef context);
114 void unloadPluginsFromSession();
117 Impl(const PluginContainerSupportPtr& containerSupport);
121 void startSession(int widgetHandle,
122 JSGlobalContextRef view,
124 const char* encodedBundle,
129 void performLibrariesUnload();
131 bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle,
132 JavaScriptObject& parentObject,
133 JSGlobalContextRef context);
135 void loadFrame(JSGlobalContextRef context);
136 void unloadFrame(JSGlobalContextRef context);
138 void setCustomProperties(double scaleFactor,
139 const char* encodedBundle,
142 void dispatchJavaScriptEvent(CustomEventType eventType, void* data);
145 JSPageSession::Impl::Impl(const PluginContainerSupportPtr& support) :
148 m_sessionStarted(false),
149 m_objectExplorer(NULL)
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()
162 if (m_sessionStarted) {
163 LogError("Must stop widget session before exit!");
167 LogDebug("Deinitializing plugin Logic...");
170 void JSPageSession::Impl::installStandardFunctions()
172 LogInfo("Installing standard functions...");
174 //add standard functions
175 FOREACH(it, JsFunctionManagerSingleton::Instance().getFunctions()) {
176 m_objectExplorer->registerObject(*it, NULL);
179 LogInfo("Standard functions installed.");
182 void JSPageSession::Impl::installRootPlugins()
184 LogInfo("Installing requested root plugins...");
186 PluginContainerSupport::PluginsList rootPlugins =
187 m_pluginsSupport->getRootPlugins();
188 FOREACH(it, rootPlugins)
193 LogInfo("requested root plugins installed.");
196 bool JSPageSession::Impl::installPlugin(PluginModelPtr plugin)
198 Assert(plugin && "Plugin Model is NULL");
199 auto library = loadLibrary(plugin);
201 LogInfo("Install Plugin '" << library->GetFileName());
204 LogError("Loading library failed");
208 // Register new class
209 FOREACH(it, *(library->GetClassList()))
211 if (!m_objectExplorer->registerObject(*it, NULL)) {
212 LogError("Object Registration failed : " << (*it)->getName());
216 LogDebug("Registered feature.");
220 void JSPageSession::Impl::installRequestedFeatures()
222 LogInfo("Installing requested widget features...");
224 std::list<std::string> allowedFeatures =
225 m_pluginsSupport->getAllowedFeatures(m_widgetHandle);
227 PluginContainerSupport::PluginsList allowedPlugins;
229 FOREACH(feature, allowedFeatures)
231 LogDebug("Processing feature: " << *feature);
233 auto plugin = m_pluginsSupport->getPluginForFeature(*feature);
234 ImplementedObjectsList implObjs =
236 getImplementedObjectsForPluginHandle(plugin->Handle.Get());
238 FOREACH(obj, implObjs)
240 LogDebug("Processing object: " << *obj);
241 /* This can be optimalized, but would need extra data in database.
242 * There should be a list of features that are allowed to be
243 * installed at widget start */
244 if (obj->find(".") == obj->rfind(".")) {
245 allowedPlugins.push_back(plugin);
246 LogWarning("Plugin will be added: "
247 << plugin->LibraryName.Get());
253 FOREACH(plugin, allowedPlugins)
255 LogDebug("Installation plugin: " << (*plugin)->LibraryName.Get());
256 installPlugin(*plugin);
259 LogInfo("requested features installed.");
262 bool JSPageSession::Impl::loadPluginOnDemand(
263 const WrtDB::DbPluginHandle &pluginHandle,
264 JavaScriptObject& parentObject,
265 JSGlobalContextRef context)
267 LogDebug("load plugin with feature");
269 Assert(parentObject.instance &&
270 !parentObject.name.empty()
271 && "Wrong arguments");
273 if (!m_sessionStarted) {
274 LogError("Session not started");
277 // //TODO here may be a bug. if plugin contains feature rejected and
279 // LogInfo("Installing feature : " << widgetFeature.name);
280 // if (widgetFeature.rejected) {
281 // LogWarning("This api-feature was rejected");
285 // auto plugin = m_pluginsSupport->getPluginModelById(pluginHandle);
287 // LogError("Failed to load plugin. plugin handle: " <<
291 m_pluginsSupport->registerPluginModel(pluginHandle);
292 return installPluginOnDemand(
293 m_pluginsSupport->getPluginModelById(pluginHandle),
298 bool JSPageSession::Impl::installPluginOnDemand(PluginModelPtr plugin,
299 JavaScriptObject& parentObject,
300 JSGlobalContextRef context)
302 Assert(plugin && "Plugin Model is NULL");
303 auto library = loadLibrary(plugin);
305 LogInfo("Install Plugin '" << library->GetFileName());
308 LogError("Loading library failed");
312 if (!(parentObject.instance)) {
313 LogError("NULL pointer value");
317 JSObjectPtr parent(new JSObject(parentObject.instance));
319 if (!parent->getObject()) {
320 LogError("NULL pointer value");
325 FOREACH(it, *(library->GetClassList()))
327 bool installationStatus =
328 m_objectExplorer->registerObject(*it,
333 if (!installationStatus) {
335 "Object Registration failed : " << (*it)->getName()
337 "; Parent object name: " << parentObject.name);
342 LogDebug("Plugin on demand registration completed");
346 void JSPageSession::Impl::setCustomProperties(double scaleFactor,
347 const char* encodedBundle,
351 "set properties of window object " << scaleFactor << ", "
352 << encodedBundle << ", " <<
355 m_objectExplorer->getWindowPropertySupport()
356 ->setScaleToNavigatorProperty(scaleFactor);
357 m_objectExplorer->getWindowPropertySupport()
358 ->setBundleToWindowProperty(encodedBundle);
359 m_objectExplorer->getWindowPropertySupport()
360 ->setThemeToNavigatorProperty(theme);
363 void JSPageSession::Impl::dispatchJavaScriptEvent(CustomEventType eventType,
366 // Check if session is already started
367 if (!m_sessionStarted) {
368 LogWarning("Session not started!");
372 LogInfo("Request dispatching javascript event");
373 m_objectExplorer->callEventListeners(eventType, data);
376 void JSPageSession::Impl::loadInjectedJavaScript()
380 std::string DIR_PATH = "/usr/etc/wrt/injected-javascript";
381 std::string JS_EXTENSION = ".js";
383 DIR *dir = opendir(DIR_PATH.c_str());
386 LogError("opendir(\"" << DIR_PATH << "\") error!");
391 struct dirent libdir;
392 struct dirent* result;
393 std::list<std::string> jsFiles;
395 // make file list from DIR_PATH
396 for (return_code = readdir_r(dir, &libdir, &result);
397 result != NULL && return_code == 0;
398 return_code = readdir_r(dir, &libdir, &result)) {
399 if (strncmp(libdir.d_name, ".", 2) == 0 ||
400 strncmp(libdir.d_name, "..", 3) == 0)
405 std::string filepath = DIR_PATH;
407 filepath += libdir.d_name;
409 std::string lowercase = filepath;
410 std::transform(lowercase.begin(), lowercase.end(), lowercase.begin(),
413 if (lowercase.rfind(JS_EXTENSION) == std::string::npos ||
414 lowercase.length() !=
415 lowercase.rfind(JS_EXTENSION) + JS_EXTENSION.length() )
417 LogError("This is not js file" << filepath);
423 if (stat(filepath.c_str(), &tmp) == -1) {
424 LogError("Failed to open file " << filepath);
428 if (!S_ISREG(tmp.st_mode)) {
429 LogError("This is not a regular file " << filepath);
433 LogInfo("Added : " << filepath);
434 jsFiles.push_back(filepath);
436 if (0 != return_code)
437 LogError("Error while reading directory.");
443 LogDebug("load file : " << (*it));
446 std::ifstream fin(it->c_str());
450 std::getline(fin, line);
451 content += line + "\n";
456 if (!content.empty()) {
457 JSValueRef exception = NULL;
459 JSStringCreateWithUTF8CString(content.c_str());
461 JSEvaluateScript(m_context, script, NULL, NULL, 1, &exception);
463 JSStringRelease(script);
466 LogDebug("Exception Occured while injecting javascript "
469 JSStringRef exceptionJSString =
470 JSValueToStringCopy(m_context, exception, NULL);
472 JSStringGetMaximumUTF8CStringSize(exceptionJSString);
473 char* exceptionString = new char[size];
474 JSStringGetUTF8CString(exceptionJSString,
475 exceptionString, size);
476 LogDebug("Exception : " << exceptionString);
478 delete[] exceptionString;
479 JSStringRelease(exceptionJSString);
485 void JSPageSession::Impl::startSession(int widgetHandle,
486 JSGlobalContextRef context,
488 const char* encodedBundle,
491 LogInfo("Starting widget session...");
493 // Check if corresponding session if not already created
494 if (m_sessionStarted) {
495 LogWarning("Session already started!");
499 // Create js object explorer object
500 m_objectExplorer = new Explorer(context);
502 m_sessionStarted = true;
503 m_widgetHandle = widgetHandle;
504 m_loadedPlugins.clear();
507 // Register standard features
508 installStandardFunctions();
510 WidgetDAOReadOnly dao(m_widgetHandle);
511 WidgetType appType = dao.getWidgetType();
512 if (appType == WrtDB::APP_TYPE_TIZENWEBAPP) {
513 installRootPlugins();
515 // Register special features
516 installRequestedFeatures();
518 // set scale, bundle as window's property
519 setCustomProperties(scaleFactor, encodedBundle, theme);
521 // Load injected javascript files
522 loadInjectedJavaScript();
523 LogInfo("Widget session started.");
526 void JSPageSession::Impl::stopSession()
528 LogInfo("Stopping widget session...");
530 if (!m_sessionStarted) {
531 LogWarning("Session not started!");
535 unloadPluginsFromSession();
536 m_sessionStarted = false;
538 LogInfo("Widget session stopped.");
541 void JSPageSession::Impl::unloadPluginsFromSession()
543 LogDebug("Unload plugins from session");
545 m_objectExplorer->removePluginsFromIframes();
546 m_objectExplorer->cleanIframesData();
548 // delete js object for overlayed js functions
549 FOREACH(it, JsFunctionManagerSingleton::Instance().getFunctions())
551 m_objectExplorer->deregisterObject(*it);
554 // delete js object for plugins
555 FOREACH(pluginIt, m_loadedPlugins)
557 LogDebug("Unregistering plugin " << (*pluginIt)->GetFileName());
559 (*pluginIt)->OnWidgetStop(m_widgetHandle);
560 LogDebug("Emitted WidgetStop for plugin: " <<
561 (*pluginIt)->GetFileName());
563 FOREACH(it, *((*pluginIt)->GetClassList()))
565 m_objectExplorer->deregisterObject(*it);
569 JavaScriptInterfaceSingleton::Instance().invokeGarbageCollector(m_context);
571 m_loadedPlugins.clear();
573 delete m_objectExplorer;
574 m_objectExplorer = NULL;
577 void JSPageSession::Impl::performLibrariesUnload()
580 LogDebug("Perform library unload");
582 size_t unloadedLibraries = 0;
584 FOREACH(pluginIt, m_loadedPlugins)
586 LogDebug("Preparing library: " << (*pluginIt)->LibraryName.Get());
588 PluginPtr plugin = (*pluginIt)->LibraryInstance.Get();
590 LogWarning("Library not loaded " << (*pluginIt)->LibraryName.Get());
594 (*pluginIt)->LibraryInstance.Set(PluginPtr());
597 LogInfo("unloaded " << unloadedLibraries << " unreferenced libraries!");
601 PluginPtr JSPageSession::Impl::loadLibrary(PluginModelPtr& pluginModel)
603 PluginPtr pluginLib = pluginModel->LibraryInstance.Get();
605 std::string path = pluginModel->LibraryPath.Get() +
606 std::string(LIBRARY_PATH_SEPARATOR) +
607 pluginModel->LibraryName.Get();
609 pluginLib = Plugin::LoadFromFile(path);
612 LogError("Loading library failed");
614 pluginModel->LibraryInstance.Set(pluginLib);
616 LogDebug("On widget start");
617 // This is first time for this plugin, start widget Session
618 pluginLib->OnWidgetStart(
620 m_loadedPlugins.insert(pluginLib);
622 FOREACH(context, m_loadedContexts)
624 pluginLib->OnFrameLoad(*context);
628 LogDebug("Get from LibraryInstance");
629 LogDebug("On widget start");
630 // This is first time for this plugin, start widget Session
631 pluginLib->OnWidgetStart(
633 m_loadedPlugins.insert(pluginLib);
635 FOREACH(context, m_loadedContexts)
637 pluginLib->OnFrameLoad(*context);
644 void JSPageSession::Impl::loadFrame(JSGlobalContextRef context)
646 LogDebug("Load a frame");
648 if (!m_sessionStarted) {
649 LogWarning("Session NOT started!");
653 m_loadedContexts.insert(context);
655 FOREACH(pluginIt, m_loadedPlugins)
657 LogDebug("load plugin to frame" << (*pluginIt)->GetFileName());
659 (*pluginIt)->OnFrameLoad(context);
662 m_objectExplorer->loadFrame(context);
665 void JSPageSession::Impl::unloadFrame(JSGlobalContextRef context)
667 LogDebug("Unload a frame");
669 if (!m_sessionStarted) {
670 LogWarning("Session NOT started!");
674 m_loadedContexts.erase(context);
676 FOREACH(pluginIt, m_loadedPlugins)
678 LogDebug("unload plugin to frame" << (*pluginIt)->GetFileName());
680 (*pluginIt)->OnFrameUnload(context);
683 m_objectExplorer->unloadFrame(context);
686 void JSPageSession::startSession(int widgetHandle,
687 JSGlobalContextRef ctx,
689 const char* encodedBundle,
692 m_impl->startSession(widgetHandle, ctx, scaleFactor, encodedBundle, theme);
695 void JSPageSession::stopSession()
697 m_impl->stopSession();
700 void JSPageSession::performLibrariesUnload()
702 m_impl->performLibrariesUnload();
705 bool JSPageSession::loadPluginOnDemand(
706 const WrtDB::DbPluginHandle &pluginHandle,
707 JavaScriptObject& parentObject,
708 JSGlobalContextRef context)
710 return m_impl->loadPluginOnDemand(pluginHandle, parentObject, context);
713 void JSPageSession::setCustomProperties(double scaleFactor,
714 const char* encodedBundle,
717 m_impl->setCustomProperties(scaleFactor, encodedBundle, theme);
720 void JSPageSession::dispatchJavaScriptEvent(CustomEventType eventType,
723 m_impl->dispatchJavaScriptEvent(eventType, data);
726 void JSPageSession::loadFrame(JSGlobalContextRef context)
728 m_impl->loadFrame(context);
731 void JSPageSession::unloadFrame(JSGlobalContextRef context)
733 m_impl->unloadFrame(context);
736 JSPageSession::JSPageSession(const PluginContainerSupportPtr& containerSupport)
738 m_impl(new JSPageSession::Impl(containerSupport))
741 JSPageSession::~JSPageSession()