File indexing completed on 2024-12-22 04:41:15

0001 /* ============================================================
0002 * Falkon - Qt web browser
0003 * Copyright (C) 2018 Anmol Gautam <tarptaeya@gmail.com>
0004 *
0005 * This program is free software: you can redistribute it and/or modify
0006 * it under the terms of the GNU General Public License as published by
0007 * the Free Software Foundation, either version 3 of the License, or
0008 * (at your option) any later version.
0009 *
0010 * This program is distributed in the hope that it will be useful,
0011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
0012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0013 * GNU General Public License for more details.
0014 *
0015 * You should have received a copy of the GNU General Public License
0016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
0017 * ============================================================ */
0018 #include "qmlpluginloader.h"
0019 #include "qmlengine.h"
0020 #include <QQmlContext>
0021 #include <QDir>
0022 #include "../config.h"
0023 
0024 #if HAVE_LIBINTL
0025 #include "qml/api/i18n/qmli18n.h"
0026 #endif
0027 
0028 QmlPluginLoader::QmlPluginLoader(const QString &name, const QString &path)
0029 {
0030     m_name = name;
0031     m_path = path;
0032     initEngineAndComponent();
0033 }
0034 
0035 void QmlPluginLoader::createComponent()
0036 {
0037     m_interface = qobject_cast<QmlPluginInterface*>(m_component->create(m_component->creationContext()));
0038 
0039     if (!m_interface) {
0040         return;
0041     }
0042 
0043     m_interface->setEngine(m_engine);
0044     m_interface->setName(m_name);
0045     connect(m_interface, &QmlPluginInterface::qmlPluginUnloaded, this, [this] {
0046         delete m_component;
0047         delete m_engine;
0048         initEngineAndComponent();
0049     });
0050 }
0051 
0052 QQmlComponent *QmlPluginLoader::component() const
0053 {
0054     return m_component;
0055 }
0056 
0057 QmlPluginInterface *QmlPluginLoader::instance() const
0058 {
0059     return m_interface;
0060 }
0061 
0062 void QmlPluginLoader::initEngineAndComponent()
0063 {
0064     m_engine = new QmlEngine();
0065     m_component = new QQmlComponent(m_engine, QDir(m_path).filePath(QStringLiteral("main.qml")));
0066     m_engine->setExtensionPath(m_path);
0067     m_engine->setExtensionName(m_name);
0068 #if HAVE_LIBINTL
0069     auto i18n = new QmlI18n(m_name);
0070     m_engine->globalObject().setProperty(QSL("__falkon_i18n"), m_engine->newQObject(i18n));
0071     m_engine->evaluate(QSL("i18n = function (s) { return __falkon_i18n.i18n(s) };"));
0072     m_engine->evaluate(QSL("i18np = function (s1, s2) { return __falkon_i18n.i18np(s1, s2) }"));
0073 #else
0074     m_engine->evaluate(QSL("i18n = function (s) { return s; };"));
0075     m_engine->evaluate(QSL("i18np = function (s1, s2) { return s1; }"));
0076 #endif
0077 }