reenable build of declarative scriptengine

just builds, is still pretty broken
This commit is contained in:
Marco Martin 2013-02-04 16:10:53 +01:00
parent 81449003bb
commit 60b37cff34
26 changed files with 3244 additions and 3 deletions

View File

@ -196,6 +196,7 @@ include(KConfigMacros)
add_subdirectory( declarativeimports )
add_subdirectory( desktoptheme )
add_subdirectory( plasma )
add_subdirectory( scriptengines )
add_subdirectory( shell )
feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)

View File

@ -1,3 +1,2 @@
kde4_no_enable_final(javascript)
add_subdirectory(javascript)
add_subdirectory(qml)
#add_subdirectory(javascript)

View File

@ -0,0 +1,46 @@
# APPLET
if(KDE_PLATFORM_FEATURE_BINARY_COMPATIBLE_FEATURE_REDUCTION)
set(PLASMA_NO_KDEWEBKIT TRUE)
set(PLASMA_NO_KNEWSTUFF TRUE)
set(PLASMA_NO_SOLID TRUE)
set(PLASMA_NO_KIO TRUE)
endif(KDE_PLATFORM_FEATURE_BINARY_COMPATIBLE_FEATURE_REDUCTION)
include_directories(${KDE4_INCLUDE_DIR}/KDE ${PHONON_INCLUDES} ${CMAKE_CURRENT_SOURCE_DIR}/common)
#DECLARATIVE APPLET
set(declarative_appletscript_SRCS
common/scriptenv.cpp
#declarative/toolboxproxy.cpp
#declarative/appletcontainer.cpp
#declarative/declarativeitemcontainer.cpp
declarative/packageaccessmanager.cpp
declarative/packageaccessmanagerfactory.cpp
declarative/qmlobject.cpp
plasmoid/abstractjsappletscript.cpp
plasmoid/appletauthorization.cpp
plasmoid/appletinterface.cpp
plasmoid/declarativeappletscript.cpp
)
include_directories(${PHONON_INCLUDES} ${CMAKE_CURRENT_SOURCE_DIR}/common)
kde4_add_plugin(plasma_appletscript_declarative ${declarative_appletscript_SRCS})
target_link_libraries(plasma_appletscript_declarative
${KDE4_PLASMA_LIBS}
${KDE4_KIO_LIBS}
${KDE4_KDE4SUPPORT_LIBS}
${QT_QTSCRIPT_LIBRARY}
${QT_QTQML_LIBRARY}
${QT_QTUITOOLS_LIBRARY}
kdeclarative
)
install(TARGETS plasma_appletscript_declarative DESTINATION ${PLUGIN_INSTALL_DIR})
install(FILES data/plasma-scriptengine-applet-declarative.desktop DESTINATION ${SERVICES_INSTALL_DIR})

View File

@ -0,0 +1,2 @@
#! /usr/bin/env bash
$XGETTEXT common/*.cpp dataengine/*.cpp plasmoid/*.cpp runner/*.cpp simplebindings/*.cpp -o $podir/plasma_scriptengine_qscript.pot

View File

@ -0,0 +1,38 @@
/*
* Copyright 2010 Aaron J. Seigo <aseigo@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef AUTHORIZATION_H
#define AUTHORIZATION_H
#include <QString>
#include <KAuthorized>
class Authorization
{
public:
Authorization() {}
virtual ~Authorization() {}
virtual bool authorizeRequiredExtension(const QString &) { return true; }
virtual bool authorizeOptionalExtension(const QString &) { return true; }
virtual bool authorizeExternalExtensions() { return true;}// KAuthorized::authorize("plasma/external_script_extensions"); }
};
#endif

View File

@ -0,0 +1,22 @@
/*
* Copyright 2010 Aaron J. Seigo <aseigo@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#define USEGUI
#define DECLARATIVE
#include "scriptenv.cpp"

View File

@ -0,0 +1,527 @@
/*
* Copyright 2007-2008 Richard J. Moore <rich@kde.org>
* Copyright 2009 Aaron J. Seigo <aseigo@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "scriptenv.h"
#include <iostream>
#include <QFile>
#include <QMetaEnum>
#include <KDebug>
#include <KDesktopFile>
#include <KIO/Job>
#include <KLocale>
#include <KMimeType>
#include <KPluginInfo>
#include <KService>
#include <KServiceTypeTrader>
#include <KShell>
#include <KStandardDirs>
#include <KRun>
#include <klocalizedstring.h>
#include <Plasma/Package>
#include <Plasma/PackageStructure>
Q_DECLARE_METATYPE(ScriptEnv*)
ScriptEnv::ScriptEnv(QObject *parent, QScriptEngine *engine)
: QObject(parent),
m_allowedUrls(NoUrls),
m_engine(engine)
{
connect(m_engine, SIGNAL(signalHandlerException(QScriptValue)), this, SLOT(signalException()));
setupGlobalObject();
}
ScriptEnv::~ScriptEnv()
{
}
void ScriptEnv::setupGlobalObject()
{
QScriptValue global = m_engine->globalObject();
// Add an accessor so we can find the scriptenv given only the engine. The
// property is hidden from scripts.
global.setProperty("__plasma_scriptenv", m_engine->newQObject(this),
QScriptValue::ReadOnly|QScriptValue::Undeletable|QScriptValue::SkipInEnumeration);
// Add utility functions
#ifndef DECLARATIVE
global.setProperty("print", m_engine->newFunction(ScriptEnv::print));
#endif
global.setProperty("debug", m_engine->newFunction(ScriptEnv::debug));
}
void ScriptEnv::addMainObjectProperties(QScriptValue &value)
{
value.setProperty("listAddons", m_engine->newFunction(ScriptEnv::listAddons));
value.setProperty("loadAddon", m_engine->newFunction(ScriptEnv::loadAddon));
value.setProperty("addEventListener", m_engine->newFunction(ScriptEnv::addEventListener));
value.setProperty("removeEventListener", m_engine->newFunction(ScriptEnv::removeEventListener));
value.setProperty("hasExtension", m_engine->newFunction(ScriptEnv::hasExtension));
}
QScriptEngine *ScriptEnv::engine() const
{
return m_engine;
}
ScriptEnv *ScriptEnv::findScriptEnv(QScriptEngine *engine)
{
QScriptValue global = engine->globalObject();
return qscriptvalue_cast<ScriptEnv*>(global.property("__plasma_scriptenv"));
}
void ScriptEnv::signalException()
{
checkForErrors(false);
}
void ScriptEnv::registerEnums(QScriptValue &scriptValue, const QMetaObject &meta)
{
//manually create enum values. ugh
QScriptEngine *engine = scriptValue.engine();
for (int i = 0; i < meta.enumeratorCount(); ++i) {
QMetaEnum e = meta.enumerator(i);
//kDebug() << e.name();
for (int i=0; i < e.keyCount(); ++i) {
//kDebug() << e.key(i) << e.value(i);
scriptValue.setProperty(e.key(i), QScriptValue(engine, e.value(i)));
}
}
}
bool ScriptEnv::include(const QString &path)
{
QFile file(path);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
kWarning() << i18n("Unable to load script file: %1", path);
return false;
}
QString script = file.readAll();
//kDebug() << "Script says" << script;
// change the context to the parent context so that the include is actually
// executed in the same context as the caller; seems to be what javascript
// coders expect :)
QScriptContext *ctx = m_engine->currentContext();
if (ctx && ctx->parentContext()) {
ctx->setActivationObject(ctx->parentContext()->activationObject());
ctx->setThisObject(ctx->parentContext()->thisObject());
}
m_engine->evaluate(script, path);
return !checkForErrors(true);
}
bool ScriptEnv::checkForErrors(bool fatal)
{
if (m_engine->hasUncaughtException()) {
emit reportError(this, fatal);
if (!fatal) {
m_engine->clearExceptions();
}
return true;
}
return false;
}
bool ScriptEnv::importBuiltinExtension(const QString &extension, QScriptValue &obj)
{
kDebug() << extension;
/*if ("filedialog" == extension) {
#ifdef USEGUI
FileDialogProxy::registerWithRuntime(m_engine);
return true;
#endif
} else */if ("launchapp" == extension) {
m_allowedUrls |= AppLaunching;
obj.setProperty("runApplication", m_engine->newFunction(ScriptEnv::runApplication));
obj.setProperty("runCommand", m_engine->newFunction(ScriptEnv::runCommand));
registerOpenUrl(obj);
return true;
} else if ("http" == extension) {
m_allowedUrls |= HttpUrls;
registerGetUrl(obj);
registerOpenUrl(obj);
return true;
} else if ("networkio" == extension) {
m_allowedUrls |= HttpUrls | NetworkUrls;
registerGetUrl(obj);
return true;
} else if ("localio" == extension) {
m_allowedUrls |= LocalUrls;
registerGetUrl(obj);
obj.setProperty("userDataPath", m_engine->newFunction(ScriptEnv::userDataPath));
obj.setProperty("runCommand", m_engine->newFunction(ScriptEnv::runCommand));
return true;
} else if ("download" == extension) {
obj.setProperty("download", m_engine->newFunction(ScriptEnv::download));
return true;
}
return false;
}
bool ScriptEnv::importExtensions(const KPluginInfo &info, QScriptValue &obj, Authorization &auth)
{
QStringList requiredExtensions = info.service()->property("X-Plasma-RequiredExtensions", QVariant::StringList).toStringList();
if (!requiredExtensions.isEmpty()) {
kDebug() << "required extensions are" << requiredExtensions;
}
foreach (const QString &ext, requiredExtensions) {
QString extension = ext.toLower();
if (m_extensions.contains(extension)) {
continue;
}
if (!auth.authorizeRequiredExtension(extension)) {
return false;
}
if (!importBuiltinExtension(extension, obj)) {
if (auth.authorizeExternalExtensions()) {
m_engine->importExtension(extension);
}
}
if (checkForErrors(true)) {
return false;
} else {
m_extensions << extension;
}
}
QStringList optionalExtensions = info.service()->property("X-Plasma-OptionalExtensions", QVariant::StringList).toStringList();
if (!optionalExtensions.isEmpty()) {
kDebug() << "optional extensions are" << optionalExtensions;
}
foreach (const QString &ext, optionalExtensions) {
QString extension = ext.toLower();
if (m_extensions.contains(extension)) {
continue;
}
if (!auth.authorizeOptionalExtension(extension)) {
continue;
}
if (!importBuiltinExtension(extension, obj)) {
if (auth.authorizeExternalExtensions()) {
m_engine->importExtension(extension);
}
}
if (!checkForErrors(false)) {
m_extensions << extension;
}
}
return true;
}
QSet<QString> ScriptEnv::loadedExtensions() const
{
return m_extensions;
}
QScriptValue ScriptEnv::debug(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) {
return throwNonFatalError(i18n("debug takes one argument"), context, engine);
}
kDebug() << context->argument(0).toString();
return engine->undefinedValue();
}
QScriptValue ScriptEnv::throwNonFatalError(const QString &msg, QScriptContext *context, QScriptEngine *engine)
{
QScriptValue rv = context->throwError(msg);
ScriptEnv *env = ScriptEnv::findScriptEnv(engine);
if (env) {
env->checkForErrors(false);
}
return rv;
}
QScriptValue ScriptEnv::print(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) {
return throwNonFatalError(i18n("print() takes one argument"), context, engine);
}
std::cout << context->argument(0).toString().toLocal8Bit().constData() << std::endl;
return engine->undefinedValue();
}
QScriptValue ScriptEnv::listAddons(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() < 1) {
return throwNonFatalError(i18n("listAddons takes one argument: addon type"), context, engine);
}
const QString type = context->argument(0).toString();
if (type.isEmpty()) {
return engine->undefinedValue();
}
const QString constraint = QString("[X-KDE-PluginInfo-Category] == '%1'").arg(type);
KService::List offers = KServiceTypeTrader::self()->query("Plasma/JavascriptAddon", constraint);
int i = 0;
QScriptValue addons = engine->newArray(offers.count());
foreach (KService::Ptr offer, offers) {
KPluginInfo info(offer);
QScriptValue v = engine->newObject();
v.setProperty("id", info.pluginName(), QScriptValue::ReadOnly);
v.setProperty("name", info.name(), QScriptValue::ReadOnly);
addons.setProperty(i++, v);
}
return addons;
}
QScriptValue ScriptEnv::loadAddon(QScriptContext *context, QScriptEngine *engine)
{/*
if (context->argumentCount() < 2) {
return throwNonFatalError(i18n("loadAddon takes two arguments: addon type and addon name to load"), context, engine);
}
const QString type = context->argument(0).toString();
const QString plugin = context->argument(1).toString();
if (type.isEmpty() || plugin.isEmpty()) {
return throwNonFatalError(i18n("loadAddon takes two arguments: addon type and addon name to load"), context, engine);
}
const QString constraint = QString("[X-KDE-PluginInfo-Category] == '%1' and [X-KDE-PluginInfo-Name] == '%2'")
.arg(type, plugin);
KService::List offers = KServiceTypeTrader::self()->query("Plasma/JavascriptAddon", constraint);
if (offers.isEmpty()) {
return throwNonFatalError(i18n("Failed to find Addon %1 of type %2", plugin, type), context, engine);
}
Plasma::PackageStructure::Ptr structure(new JavascriptAddonPackageStructure);
const QString subPath = structure->defaultPackageRoot() + '/' + plugin + '/';
const QString path = KStandardDirs::locate("data", subPath);
Plasma::Package package(path, structure);
QFile file(package.filePath("mainscript"));
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return throwNonFatalError(i18n("Failed to open script file for Addon %1: %2", plugin, package.filePath("mainscript")), context, engine);
}
QTextStream buffer(&file);
QString code(buffer.readAll());
QScriptContext *innerContext = engine->pushContext();
innerContext->activationObject().setProperty("registerAddon", engine->newFunction(ScriptEnv::registerAddon));
QScriptValue v = engine->newVariant(QVariant::fromValue(package));
innerContext->activationObject().setProperty("__plasma_package", v,
QScriptValue::ReadOnly |
QScriptValue::Undeletable |
QScriptValue::SkipInEnumeration);
//kDebug() << "context is" << innerContext;
engine->evaluate(code, file.fileName());
engine->popContext();
ScriptEnv *env = ScriptEnv::findScriptEnv(engine);
if (env && env->checkForErrors(false)) {
return false;
}*/
return true;
}
QScriptValue ScriptEnv::registerAddon(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() > 0) {
QScriptValue func = context->argument(0);
if (func.isFunction()) {
QScriptValue obj = func.construct();
obj.setProperty("__plasma_package",
context->parentContext()->activationObject().property("__plasma_package"),
QScriptValue::ReadOnly |
QScriptValue::Undeletable |
QScriptValue::SkipInEnumeration);
ScriptEnv *env = ScriptEnv::findScriptEnv(engine);
if (env) {
QScriptValueList args;
args << obj;
env->callEventListeners("addoncreated", args);
}
}
}
return engine->undefinedValue();
}
QString ScriptEnv::filePathFromScriptContext(const char *type, const QString &file) const
{
//kDebug() << type << file;
QScriptContext *c = m_engine->currentContext();
while (c) {
QScriptValue v = c->activationObject().property("__plasma_package");
//kDebug() << "variant in parent context?" << v.isVariant();
if (v.isVariant()) {
const QString path = v.toVariant().value<Plasma::Package>().filePath(type, file);
if (!path.isEmpty()) {
return path;
}
}
c = c->parentContext();
}
//kDebug() << "fail";
return QString();
}
QScriptValue ScriptEnv::addEventListener(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() < 2) {
return false;
}
ScriptEnv *env = ScriptEnv::findScriptEnv(engine);
if (!env) {
return false;
}
return env->addEventListener(context->argument(0).toString(), context->argument(1));
}
QScriptValue ScriptEnv::removeEventListener(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() < 2) {
return false;
}
ScriptEnv *env = ScriptEnv::findScriptEnv(engine);
if (!env) {
return false;
}
return env->removeEventListener(context->argument(0).toString(), context->argument(1));
}
QScriptValue ScriptEnv::hasExtension(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() < 1) {
return false;
}
ScriptEnv *env = ScriptEnv::findScriptEnv(engine);
if (!env) {
return false;
}
return env->m_extensions.contains(context->argument(0).toString().toLower());
}
QScriptValue ScriptEnv::callFunction(QScriptValue &func, const QScriptValueList &args, const QScriptValue &activator)
{
if (!func.isFunction()) {
return m_engine->undefinedValue();
}
QScriptContext *ctx = m_engine->pushContext();
ctx->setActivationObject(activator);
QScriptValue rv = func.call(activator, args);
m_engine->popContext();
if (m_engine->hasUncaughtException()) {
emit reportError(this, false);
m_engine->clearExceptions();
return m_engine->undefinedValue();
}
return rv;
}
bool ScriptEnv::hasEventListeners(const QString &event) const
{
return m_eventListeners.contains(event);
}
bool ScriptEnv::callEventListeners(const QString &event, const QScriptValueList &args)
{
if (!m_eventListeners.contains(event.toLower())) {
return false;
}
QScriptValueList funcs = m_eventListeners.value(event.toLower());
QMutableListIterator<QScriptValue> it(funcs);
while (it.hasNext()) {
callFunction(it.next(), args);
}
return true;
}
bool ScriptEnv::addEventListener(const QString &event, const QScriptValue &func)
{
if (func.isFunction() && !event.isEmpty()) {
m_eventListeners[event.toLower()].append(func);
return true;
}
return false;
}
bool ScriptEnv::removeEventListener(const QString &event, const QScriptValue &func)
{
bool found = false;
if (func.isFunction()) {
QScriptValueList funcs = m_eventListeners.value(event);
QMutableListIterator<QScriptValue> it(funcs);
while (it.hasNext()) {
if (it.next().equals(func)) {
it.remove();
found = true;
}
}
if (funcs.isEmpty()) {
m_eventListeners.remove(event.toLower());
} else {
m_eventListeners.insert(event.toLower(), funcs);
}
}
return found;
}
#ifndef USEGUI
#include "scriptenv.moc"
#endif

View File

@ -0,0 +1,125 @@
/*
* Copyright 2007-2008 Richard J. Moore <rich@kde.org>
* Copyright 2009 Aaron J. Seigo <aseigo@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef SCRIPTENV_H
#define SCRIPTENV_H
#define USEGUI
#define DECLARATIVE
#include <kdemacros.h>
#include <QScriptEngine>
#include <QSet>
#include <KPluginInfo>
#include "authorization.h"
namespace Plasma
{
class Package;
} // namespace Plasma
class ScriptEnv : public QObject
{
Q_OBJECT
public:
enum AllowedUrl { NoUrls = 0,
HttpUrls = 1,
NetworkUrls = 2,
LocalUrls = 4,
AppLaunching = 8};
Q_DECLARE_FLAGS(AllowedUrls, AllowedUrl)
ScriptEnv(QObject *parent, QScriptEngine *engine);
~ScriptEnv();
/**
* Adds common properties (e.g. registerEventFilter)
* for a 'main' object (e.g. plasmoid, engine, runner)
*/
void addMainObjectProperties(QScriptValue &value);
/** Returns the QScriptEngine in use. */
QScriptEngine *engine() const;
/** Returns the ScriptEnv in use for a given QScriptEngine or 0. */
static ScriptEnv *findScriptEnv(QScriptEngine *engine);
static void registerEnums(QScriptValue &scriptValue, const QMetaObject &meta);
bool include(const QString &path);
bool importExtensions(const KPluginInfo &info, QScriptValue &obj, Authorization &authorizer);
QSet<QString> loadedExtensions() const;
bool checkForErrors(bool fatal);
bool addEventListener(const QString &event, const QScriptValue &func);
bool removeEventListener(const QString &event, const QScriptValue &func);
QScriptValue callFunction(QScriptValue &func, const QScriptValueList &args = QScriptValueList(), const QScriptValue &activator = QScriptValue());
bool callEventListeners(const QString &event, const QScriptValueList &args = QScriptValueList());
bool hasEventListeners(const QString &event) const;
QString filePathFromScriptContext(const char *type, const QString &file) const;
Q_SIGNALS:
void reportError(ScriptEnv *engine, bool fatal);
private:
void registerGetUrl(QScriptValue &obj){}
void registerOpenUrl(QScriptValue &obj){}
bool importBuiltinExtension(const QString &extension, QScriptValue &obj);
static QScriptValue debug(QScriptContext *context, QScriptEngine *engine);
static QScriptValue print(QScriptContext *context, QScriptEngine *engine);
static QScriptValue runApplication(QScriptContext *context, QScriptEngine *engine){return QScriptValue();}
static QScriptValue runCommand(QScriptContext *context, QScriptEngine *engine){return QScriptValue();}
static QScriptValue defaultApplication(QScriptContext *context, QScriptEngine *engine);
static QScriptValue applicationPath(QScriptContext *context, QScriptEngine *engine);
static QScriptValue applicationExists(QScriptContext *context, QScriptEngine *engine);
static QScriptValue openUrl(QScriptContext *context, QScriptEngine *engine);
static QScriptValue getUrl(QScriptContext *context, QScriptEngine *engine);
static QScriptValue download(QScriptContext *context, QScriptEngine *engine){return QScriptValue();}
static QScriptValue userDataPath(QScriptContext *context, QScriptEngine *engine){return QScriptValue();}
static QScriptValue listAddons(QScriptContext *context, QScriptEngine *engine);
static QScriptValue loadAddon(QScriptContext *context, QScriptEngine *engine);
static QScriptValue registerAddon(QScriptContext *context, QScriptEngine *engine);
static QScriptValue addEventListener(QScriptContext *context, QScriptEngine *engine);
static QScriptValue removeEventListener(QScriptContext *context, QScriptEngine *engine);
static QScriptValue hasExtension(QScriptContext *context, QScriptEngine *engine);
static QScriptValue throwNonFatalError(const QString &msg, QScriptContext *context, QScriptEngine *engine);
private Q_SLOTS:
void signalException();
private:
/** Call to set common properties on the global object **/
void setupGlobalObject();
QSet<QString> m_extensions;
AllowedUrls m_allowedUrls;
QScriptEngine *m_engine;
QHash<QString, QScriptValueList> m_eventListeners;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(ScriptEnv::AllowedUrls)
#endif

View File

@ -0,0 +1,139 @@
[Desktop Entry]
Name=Declarative widget
Name[ast]=Elementu gráficu declarativu
Name[bg]=Декларативна джаджа
Name[bs]=Deklarativna grafička kontrola
Name[ca]=Estri declaratiu
Name[ca@valencia]=Estri declaratiu
Name[cs]=Deklarativní widget
Name[da]=Erklærende widget
Name[de]=Deklaratives Bedienelement
Name[el]=Δηλωτικό συστατικό
Name[en_GB]=Declarative widget
Name[eo]=Deklarema fenestraĵo
Name[es]=Elemento gráfico declarativo
Name[et]=Deklaratiivne vidin
Name[eu]=Trepeta ezagutarazlea
Name[fi]=Deklaratiivinen sovelma
Name[fr]=Composant graphique « Declarative »
Name[ga]=Giuirléid fhógrach
Name[gl]=Widget declarativo
Name[he]=ווידג׳ט מוצהר
Name[hi]= ि
Name[hr]=Deklarativni widget
Name[hu]=Deklaratív widget
Name[ia]=Widget declarative
Name[is]=Skilgreiningagræja
Name[it]=Oggetto dichiarativo
Name[kk]=Мәлімдеме виджеті
Name[km]=
Name[ko]=Declarative
Name[lt]=Deklaratyvus valdiklis
Name[lv]=Deklaratīvais sīkrīks
Name[mr]= ि
Name[nb]=Deklarativt skjermelement
Name[nds]=Stüerelement för Verkloren
Name[nl]=Widget voor declaratie
Name[nn]=Deklarativt skjermelement
Name[pa]=ਿਿ ਿ
Name[pl]=Deklaratywny element interfejsu
Name[pt]=Item declarativo
Name[pt_BR]=Widget declarativo
Name[ro]=Control declarativ
Name[ru]=Декларативный виджет
Name[si]=
Name[sk]=Deklaratívny widget
Name[sl]=Deklarativni gradnik
Name[sr]=Декларативни виџет
Name[sr@ijekavian]=Декларативни виџет
Name[sr@ijekavianlatin]=Deklarativni vidžet
Name[sr@latin]=Deklarativni vidžet
Name[sv]=Deklarativ grafisk komponent
Name[tg]=Видҷети эълонкунӣ
Name[tr]=Bildirim parçacığı
Name[ug]=ئېنىقلىما ۋىجېت
Name[uk]=Декларативний віджет
Name[vi]=Widget khai báo
Name[wa]=Ahesse di gåyotaedje
Name[x-test]=xxDeclarative widgetxx
Name[zh_CN]=
Name[zh_TW]=
Comment=Native Plasma widget written in QML and JavaScript
Comment[ast]=Elementu gráficu nativu de Plasma escritu en QML y JavaScript
Comment[bg]=Оригинална джаджа за Plasma, написана наQML и JavaScript
Comment[bs]=Samosvojni plazma grafičkih kontrola napisana u QMLu i javaskriptu
Comment[ca]=Estri nadiu del Plasma escrit en QML i JavaScript
Comment[ca@valencia]=Estri nadiu del Plasma escrit en QML i JavaScript
Comment[cs]=Nativní Plasma widget napsaný v QML a JavaScriptu
Comment[da]=Hjemmehørende Plasma-widget skrevet i QML og JavaScript
Comment[de]=Echtes Plasma-Programm, geschrieben in QML und JavaScript
Comment[el]=Εγγενές συστατικό Plasma γραμμένο σε QML και JavaScript
Comment[en_GB]=Native Plasma widget written in QML and JavaScript
Comment[eo]=Indiĝena fenestraĵo de Plasmo programita per QML kaj Ĝavaskripto
Comment[es]=Elemento gráfico nativo de Plasma escrito en QML y JavaScript
Comment[et]=QML-is ja JavaScriptis kirjutatud Plasma vidin
Comment[eu]=Plasma jatorrizko trepeta QML eta JavaScript-en idatzia
Comment[fi]=Natiivi, QML-pohjainen Plasma-sovelma
Comment[fr]=Composant graphique natif de Plasma écrit en QML et JavaScript
Comment[ga]=Giuirléid dhúchasach Plasma, scríofa in QML agus JavaScript
Comment[gl]=Widget nativo de Plasma escrito en QML e JavaScript
Comment[he]=ווידג׳טים של Plasma הנכתבים ב־QML וב־JavaScript
Comment[hi]=QML ि ि ि ि
Comment[hr]=Izvorni Plasma widget napisan u QML-u i JavaScriptu
Comment[hu]=QML-ben és JavaScriptben írt natív Plazma-widget
Comment[ia]=Widget native de Plasma scribite in QLM e JavaScript
Comment[is]=Upprunabundin Plasma græja skrifuð í QML og JavaScript
Comment[it]=Oggetto nativo di Plasma scritto in QML e JavaScript
Comment[ja]=QML JavaScript Plasma
Comment[kk]=QML мен JavaScript-те жазылған Plasma тума виджеті
Comment[km]= JavaScript
Comment[kn]=QML ಿ ಿ ಿ ಿ (ಿ)
Comment[ko]=QML Plasma
Comment[lt]=Nuosavas Plasma valdiklis parašytas QML ir JavaScript kalba
Comment[lv]=Plasma sīkrīks, rakstīts QML un JavaScript valodās
Comment[mr]=ि QML ि ि
Comment[nb]=Plasmaelement for dette systemet, skrevet i QML og JavaScript
Comment[nds]=En orginaal Plasmaelement, schreven in QML un JavaScript
Comment[nl]=Hier thuishorend Plasma-widget geschreven in QML en JavaScript
Comment[nn]=Plasma-element skriven i QML og JavaScript
Comment[pa]=QML -ਿ ਿ ਿ ਿ ਿ
Comment[pl]=Element interfejsu Plazmy napisany w QML lub JavaScript
Comment[pt]=Elemento nativo do Plasma feito em QML e JavaScript
Comment[pt_BR]=Widget do Plasma nativo escrito em QML e JavaScript
Comment[ro]=Miniaplicație Plasma nativă scrisă în QML și JavaScript
Comment[ru]=Виджет Plasma, написанный на языках QML и JavaScript
Comment[si]= QML
Comment[sk]=Natívny plasma widget napísaný v QML a JavaScripte
Comment[sl]=Pravi gradnik za Plasmo, ki je napisan v QML-u in JavaScriptu
Comment[sr]=Самосвојни плазма виџет написан у КуМЛу и јаваскрипту
Comment[sr@ijekavian]=Самосвојни плазма виџет написан у КуМЛу и јаваскрипту
Comment[sr@ijekavianlatin]=Samosvojni plasma vidžet napisan u QMLu i JavaScriptu
Comment[sr@latin]=Samosvojni plasma vidžet napisan u QMLu i JavaScriptu
Comment[sv]=Inbyggd grafisk Plasma-komponent skriven i QML och Javascript
Comment[tg]=Ин модули Plasma дар QML ва JavaScript навишта шуд
Comment[th]= QML
Comment[tr]=JavaScript ve QML ile yazılmış gerçek Plasma gereci
Comment[ug]=QML ۋە JavaScript بىلەن يېزىلغان ئەسلى Plasma ۋىجېتى
Comment[uk]=Віджет Плазми, написаний на QML та JavaScript
Comment[vi]=Widget Plasma viết bi QML và JavaScript
Comment[wa]=Ahesse askepieye po Plasma eyet scrîte e QML eyet JavaScript
Comment[x-test]=xxNative Plasma widget written in QML and JavaScriptxx
Comment[zh_CN]=使 QML JavaScript Plasma
Comment[zh_TW]= QML JavaScript Plasma
Type=Service
Icon=text-x-script
X-KDE-ServiceTypes=Plasma/ScriptEngine
X-KDE-Library=plasma_appletscript_declarative
X-EngineName=declarativeappletscript
X-Plasma-API=declarativeappletscript
X-Plasma-ComponentTypes=Applet
X-KDE-PluginInfo-Author=Alexis Menard
X-KDE-PluginInfo-Email=menard@kde.org
X-KDE-PluginInfo-Name=qmlscript
X-KDE-PluginInfo-Version=0.1
X-KDE-PluginInfo-Category=Examples
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=LGPL
X-KDE-PluginInfo-EnabledByDefault=true

View File

@ -0,0 +1,88 @@
/*
* Copyright 2010 Marco Martin <notmart@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "packageaccessmanager.h"
#include <QNetworkReply>
#include <Plasma/Package>
#include "plasmoid/appletauthorization.h"
class ErrorReply : public QNetworkReply
{
public:
ErrorReply(QNetworkAccessManager::Operation op, const QNetworkRequest &req)
: QNetworkReply()
{
setError(QNetworkReply::ContentOperationNotPermittedError, "The plasmoid has not been authorized to load remote content");
setOperation(op);
setRequest(req);
setUrl(req.url());
}
qint64 readData(char *data, qint64 maxSize)
{
Q_UNUSED(data);
Q_UNUSED(maxSize);
return 0;
}
void abort()
{
}
};
PackageAccessManager::PackageAccessManager(const Plasma::Package *package, AppletAuthorization *auth, QObject *parent)
: KIO::AccessManager(parent),
m_package(package),
m_auth(auth)
{
}
PackageAccessManager::~PackageAccessManager()
{
}
QNetworkReply *PackageAccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *outgoingData)
{
QUrl reqUrl(req.url());
if (reqUrl.scheme() == "plasmapackage") {
QNetworkRequest request = req;
reqUrl.setScheme("file");
reqUrl.setPath(m_package->filePath(0, reqUrl.path()));
request.setUrl(reqUrl);
return QNetworkAccessManager::createRequest(op, request, outgoingData);
} else if ((reqUrl.scheme() == "http" && !m_auth->authorizeRequiredExtension("http")) ||
((reqUrl.scheme() == "file" || reqUrl.scheme() == "desktop") && !m_auth->authorizeRequiredExtension("localio")) ||
(!m_auth->authorizeRequiredExtension("networkio"))) {
return new ErrorReply(op, req);
} else {
#ifndef PLASMA_NO_KIO
return KIO::AccessManager::createRequest(op, req, outgoingData);
#else
return QNetworkAccessManager::createRequest(op, req, outgoingData);
#endif
}
}

View File

@ -0,0 +1,57 @@
/*
* Copyright 2010 Marco Martin <notmart@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef PACKAGEACCESSMANAGER_H
#define PACKAGEACCESSMANAGER_H
#include <kdemacros.h>
#ifndef PLASMA_NO_KIO
#include <kio/accessmanager.h>
#else
#include <QtNetwork/QNetworkAccessManager>
#endif
namespace Plasma
{
class Package;
}
class AppletAuthorization;
class PackageAccessManager :
#ifdef PLASMA_NO_KIO
public QNetworkAccessManager
#else
public KIO::AccessManager
#endif
{
public:
PackageAccessManager(const Plasma::Package *package, AppletAuthorization *auth, QObject *parent = 0);
~PackageAccessManager();
protected:
QNetworkReply *createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *outgoingData = 0);
private:
const Plasma::Package *m_package;
AppletAuthorization *m_auth;
};
#endif

View File

@ -0,0 +1,43 @@
/*
* Copyright 2010 Marco Martin <notmart@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "packageaccessmanagerfactory.h"
#include <Plasma/Package>
#include "packageaccessmanager.h"
#include "plasmoid/appletauthorization.h"
PackageAccessManagerFactory::PackageAccessManagerFactory(const Plasma::Package *package, AppletAuthorization *auth)
: QQmlNetworkAccessManagerFactory(),
m_package(package),
m_auth(auth)
{
}
PackageAccessManagerFactory::~PackageAccessManagerFactory()
{
}
QNetworkAccessManager *PackageAccessManagerFactory::create(QObject *parent)
{
return new PackageAccessManager(m_package, m_auth, parent);
}

View File

@ -0,0 +1,45 @@
/*
* Copyright 2010 Marco Martin <notmart@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef PACKAGEACCESSMANAGERFACTORY_H
#define PACKAGEACCESSMANAGERFACTORY_H
#include <QQmlNetworkAccessManagerFactory>
namespace Plasma
{
class Package;
}
class AppletAuthorization;
class PackageAccessManagerFactory : public QQmlNetworkAccessManagerFactory
{
public:
PackageAccessManagerFactory(const Plasma::Package *package, AppletAuthorization *auth);
~PackageAccessManagerFactory();
QNetworkAccessManager *create(QObject *parent);
private:
const Plasma::Package *m_package;
AppletAuthorization *m_auth;
};
#endif

View File

@ -0,0 +1,197 @@
/*
* Copyright 2010 Marco Martin <mart@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "qmlobject.h"
#include <QQmlComponent>
#include <QQmlEngine>
#include <QQmlContext>
#include <QTimer>
#include <kdebug.h>
#include <kdeclarative.h>
#include "packageaccessmanagerfactory.h"
//#include "private/declarative/dataenginebindings_p.h"
class QmlObjectPrivate
{
public:
QmlObjectPrivate(QmlObject *parent)
: q(parent),
engine(0),
component(0),
root(0),
delay(false)
{
}
~QmlObjectPrivate()
{
}
void errorPrint();
void execute(const QString &fileName);
void finishExecute();
void scheduleExecutionEnd();
void minimumWidthChanged();
void minimumHeightChanged();
void maximumWidthChanged();
void maximumHeightChanged();
void preferredWidthChanged();
void preferredHeightChanged();
QmlObject *q;
QString qmlPath;
QQmlEngine* engine;
QQmlComponent* component;
QObject *root;
bool delay : 1;
};
void QmlObjectPrivate::errorPrint()
{
QString errorStr = "Error loading QML file.\n";
if(component->isError()){
QList<QQmlError> errors = component->errors();
foreach (const QQmlError &error, errors) {
errorStr += (error.line()>0?QString(QString::number(error.line()) + QLatin1String(": ")):QLatin1String(""))
+ error.description() + '\n';
}
}
kWarning() << component->url().toString() + '\n' + errorStr;
}
void QmlObjectPrivate::execute(const QString &fileName)
{
if (fileName.isEmpty()) {
#ifndef NDEBUG
kDebug() << "File name empty!";
#endif
return;
}
KDeclarative kdeclarative;
kdeclarative.setDeclarativeEngine(engine);
kdeclarative.initialize();
//binds things like kconfig and icons
kdeclarative.setupBindings();
component->loadUrl(QUrl::fromLocalFile(fileName));
if (delay) {
QTimer::singleShot(0, q, SLOT(scheduleExecutionEnd()));
} else {
scheduleExecutionEnd();
}
}
void QmlObjectPrivate::scheduleExecutionEnd()
{
if (component->isReady() || component->isError()) {
finishExecute();
} else {
QObject::connect(component, SIGNAL(statusChanged(QQmlComponent::Status)), q, SLOT(finishExecute()));
}
}
void QmlObjectPrivate::finishExecute()
{
if (component->isError()) {
errorPrint();
}
root = component->create();
if (!root) {
errorPrint();
}
#ifndef NDEBUG
kDebug() << "Execution of QML done!";
#endif
emit q->finished();
}
QmlObject::QmlObject(QObject *parent)
: QObject(parent),
d(new QmlObjectPrivate(this))
{
d->engine = new QQmlEngine(this);
//d->engine->setNetworkAccessManagerFactory(new PackageAccessManagerFactory());
d->component = new QQmlComponent(d->engine, this);
}
QmlObject::~QmlObject()
{
// QDeclarativeNetworkAccessManagerFactory *factory = d->engine->networkAccessManagerFactory();
// d->engine->setNetworkAccessManagerFactory(0);
// delete factory;
delete d;
}
void QmlObject::setQmlPath(const QString &path)
{
d->qmlPath = path;
d->execute(path);
}
QString QmlObject::qmlPath() const
{
return d->qmlPath;
}
void QmlObject::setInitializationDelayed(const bool delay)
{
d->delay = delay;
}
bool QmlObject::isInitializationDelayed() const
{
return d->delay;
}
QQmlEngine* QmlObject::engine()
{
return d->engine;
}
QObject *QmlObject::rootObject() const
{
return d->root;
}
QQmlComponent *QmlObject::mainComponent() const
{
return d->component;
}
#include "moc_qmlobject.cpp"

View File

@ -0,0 +1,122 @@
/*
* Copyright 2010 Marco Martin <mart@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef QMLOBJECT_H
#define QMLOBJECT_H
#include <QObject>
class QQmlEngine;
class QQmlComponent;
class QmlObjectPrivate;
/**
* @class QmlObject plasma/declarativewidget.h <Plasma/QmlObject>
*
* @author Marco Martin <mart@kde.org>
*
* @short An object that instantiates an entire QML context, with its own declarative engine
*
* Plasma::QmlObject provides a class for conveniently use QML based
* declarative user interfaces inside Plasma widgets.
* To one QmlObject corresponds one QML file (that can eventually include others)
* tere will be its own QQmlEngine with a single root object,
* described in the QML file.
*/
class QmlObject : public QObject
{
Q_OBJECT
Q_PROPERTY(QString qmlPath READ qmlPath WRITE setQmlPath)
Q_PROPERTY(bool initializationDelayed READ isInitializationDelayed WRITE setInitializationDelayed)
Q_PROPERTY(QObject * rootObject READ rootObject)
public:
/**
* Constructs a new QmlObject
*
* @param parent the parent of this object
*/
explicit QmlObject(QObject *parent = 0);
~QmlObject();
/**
* Sets the path of the QML file to parse and execute
*
* @param path the absolute path of a QML file
*/
void setQmlPath(const QString &path);
/**
* @return the absolute path of the current QML file
*/
QString qmlPath() const;
/**
* Sets whether the execution of the QML file has to be delayed later in the event loop. It has to be called before setQmlPath().
* In this case will be possible to assign new objects in the main engine context
* before the main component gets initialized.
* So it will be possible to access it immediately from the QML code.
*
* @param delay if true the initialization of the QML file will be delayed
* at the end of the event loop
*/
void setInitializationDelayed(const bool delay);
/**
* @return true if the initialization of the QML file will be delayed
* at the end of the event loop
*/
bool isInitializationDelayed() const;
/**
* @return the declarative engine that runs the qml file assigned to this widget.
*/
QQmlEngine* engine();
/**
* @return the root object of the declarative object tree
*/
QObject *rootObject() const;
/**
* @return the main QQmlComponent of the engine
*/
QQmlComponent *mainComponent() const;
Q_SIGNALS:
/**
* Emitted when the parsing and execution of the QML file is terminated
*/
void finished();
private:
friend class QmlObjectPrivate;
QmlObjectPrivate * const d;
Q_PRIVATE_SLOT(d, void finishExecute())
Q_PRIVATE_SLOT(d, void scheduleExecutionEnd())
};
#endif // multiple inclusion guard

View File

@ -0,0 +1,180 @@
/*
* Copyright 2007 by Aaron Seigo <aseigo@kde.org>
* Copyright 2008 by Marco Martin <notmart@gmail.com>
* Copyright 2012 by Sebastian Kügler <sebas@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "toolboxproxy.h"
#include "../plasmoid/appletinterface.h"
#include <QAction>
#include <KIcon>
#include <KDebug>
#include <Plasma/Corona>
class ToolBoxProxyPrivate {
public:
bool showing;
Plasma::Containment *containment;
QList<QAction*> actions;
AppletInterface* appletInterface;
QAction* addPanelAction;
QAction* addWidgetsAction;
QAction* configureAction;
};
ToolBoxProxy::ToolBoxProxy(Plasma::Containment *parent, AppletInterface *appletInterface)
: AbstractToolBox(parent)
{
d = new ToolBoxProxyPrivate;
d->containment = parent;
d->appletInterface = appletInterface;
init();
}
ToolBoxProxy::ToolBoxProxy(QObject *parent, const QVariantList &args)
: AbstractToolBox(parent, args)
{
d = new ToolBoxProxyPrivate;
d->containment = qobject_cast<Plasma::Containment *>(parent);
d->appletInterface = 0;
init();
}
ToolBoxProxy::~ToolBoxProxy()
{
delete d;
}
void ToolBoxProxy::init()
{
d->showing = false;
d->addPanelAction = 0;
d->addWidgetsAction = 0;
d->configureAction = 0;
if (d->containment) {
connect(d->containment, SIGNAL(immutabilityChanged(Plasma::ImmutabilityType)),
this, SLOT(immutabilityChanged(Plasma::ImmutabilityType)));
connect(this, SIGNAL(configureRequested(Plasma::Containment*)),
d->containment, SIGNAL(configureRequested(Plasma::Containment*)));
connect(this, SIGNAL(showAddWidgetsInterface(const QPointF&)),
d->containment, SIGNAL(showAddWidgetsInterface(const QPointF&)));
}
loadActions();
}
void ToolBoxProxy::loadActions()
{
d->actions.clear();
if (d->containment) {
if (!d->configureAction) {
d->configureAction = new QAction(this);
d->configureAction->setText(i18n("%1 Settings", d->containment->name()));
d->configureAction->setIcon(KIcon("configure"));
d->configureAction->setObjectName("configure");
connect(d->configureAction, SIGNAL(triggered()), this, SLOT(configureRequested()));
}
addTool(d->configureAction);
if (d->appletInterface) {
foreach (QAction *action, d->appletInterface->contextualActions()) {
addTool(action);
}
}
foreach (QAction *action, d->containment->actions()) {
addTool(action);
}
foreach (QAction *action, d->containment->corona()->actions()) {
addTool(action);
}
if (!d->addWidgetsAction) {
d->addWidgetsAction = new QAction(this);
d->addWidgetsAction->setObjectName("add widgets");
d->addWidgetsAction->setText(i18n("Add Widgets"));
d->addWidgetsAction->setIcon(KIcon("list-add"));
connect(d->addWidgetsAction, SIGNAL(triggered()), this, SLOT(addWidgetsRequested()));
}
if (d->appletInterface && !d->appletInterface->immutable()) {
addTool(d->addWidgetsAction);
}
}
emit actionsChanged();
}
QDeclarativeListProperty<QAction> ToolBoxProxy::actions()
{
return QDeclarativeListProperty<QAction>(this, d->actions);
}
void ToolBoxProxy::addTool(QAction *action)
{
if (!action || d->actions.contains(action)) {
return;
}
if (d->appletInterface && d->appletInterface->immutable() && action->objectName() == "add panel") {
d->addPanelAction = action;
return;
}
connect(action, SIGNAL(destroyed(QObject*)), this, SLOT(actionDestroyed(QObject*)), Qt::UniqueConnection);
d->actions.append(action);
}
void ToolBoxProxy::removeTool(QAction *action)
{
disconnect(action, 0, this, 0);
d->actions.removeAll(action);
emit actionsChanged();
}
void ToolBoxProxy::actionDestroyed(QObject *object)
{
d->actions.removeAll(static_cast<QAction*>(object));
}
void ToolBoxProxy::configureRequested()
{
emit configureRequested(d->containment);
}
void ToolBoxProxy::addWidgetsRequested()
{
emit showAddWidgetsInterface(QPointF(0, 0));
}
bool ToolBoxProxy::isShowing() const
{
return d->showing;
}
void ToolBoxProxy::setShowing(const bool show)
{
if (d->showing == show) {
return;
}
d->showing = show;
}
void ToolBoxProxy::immutabilityChanged(Plasma::ImmutabilityType immutability)
{
Q_UNUSED(immutability);
loadActions();
}
#include "toolboxproxy.moc"

View File

@ -0,0 +1,81 @@
/*
* Copyright 2007 by Aaron Seigo <aseigo@kde.org>
* Copyright 2008 by Marco Martin <notmart@gmail.com>
* Copyright 2012 by Sebastian Kügler <sebas@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef TOOLBOXPROXY_H
#define TOOLBOXPROXY_H
#include <Plasma/AbstractToolBox>
#include <Plasma/Plasma>
#include <QDeclarativeListProperty>
class QAction;
class ToolBoxProxyPrivate;
class AppletInterface;
class ToolBoxProxy : public Plasma::AbstractToolBox
{
Q_OBJECT
Q_PROPERTY(QDeclarativeListProperty<QAction> actions READ actions NOTIFY actionsChanged)
public:
explicit ToolBoxProxy(Plasma::Containment *parent, AppletInterface *appletInterface);
explicit ToolBoxProxy(QObject *parent = 0, const QVariantList &args = QVariantList());
~ToolBoxProxy();
bool isShowing() const; // satisfy badly named API
void setShowing(const bool show);
QDeclarativeListProperty<QAction> actions();
public Q_SLOTS:
void configureRequested();
void addWidgetsRequested();
Q_SIGNALS:
void actionsChanged();
void immutableChanged();
void configureRequested(Plasma::Containment* containment);
void showAddWidgetsInterface(const QPointF& pos);
private Q_SLOTS:
void actionDestroyed(QObject *object);
void immutabilityChanged(Plasma::ImmutabilityType immutability);
private:
void init();
void loadActions();
/**
* create a toolbox tool from the given action
* @p action the action to associate hte tool with
*/
void addTool(QAction *action);
/**
* remove the tool associated with this action
*/
void removeTool(QAction *action);
ToolBoxProxyPrivate* d;
};
#endif // TOOLBOXPROXY_H

View File

@ -0,0 +1,32 @@
/*
* Copyright 2010 Marco Martin <mart@kde.org>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "plasmoid/abstractjsappletscript.h"
AbstractJsAppletScript::AbstractJsAppletScript(QObject *parent, const QVariantList &args)
: Plasma::AppletScript(parent)
{
Q_UNUSED(args);
}
AbstractJsAppletScript::~AbstractJsAppletScript()
{
}

View File

@ -0,0 +1,40 @@
/*
* Copyright 2010 Marco Martin <mart@kde.org>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef ABSTRACTJS_APPLETSCRIPT_H
#define ABSTRACTJS_APPLETSCRIPT_H
#include <QQmlEngine>
#include <Plasma/AppletScript>
class AbstractJsAppletScript : public Plasma::AppletScript
{
Q_OBJECT
public:
AbstractJsAppletScript(QObject *parent, const QVariantList &args = QVariantList());
~AbstractJsAppletScript();
virtual QQmlEngine *engine() const = 0;
virtual bool include(const QString &path) = 0;
virtual QString filePath(const QString &type, const QString &file) const = 0;
};
#endif

View File

@ -0,0 +1,58 @@
/*
* Copyright 2010 Aaron J. Seigo <aseigo@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <kdemacros.h>
#include <KAuthorized>
#include <klocalizedstring.h>
#include "appletauthorization.h"
#include <Plasma/AppletScript>
#include <Plasma/Applet>
AppletAuthorization::AppletAuthorization(Plasma::AppletScript *scriptEngine)
: Authorization(),
m_scriptEngine(scriptEngine)
{
}
bool AppletAuthorization::authorizeRequiredExtension(const QString &extension)
{
bool ok = m_scriptEngine->applet()->hasAuthorization(extension);
if (!ok) {
m_scriptEngine->setFailedToLaunch(true,
i18n("Authorization for required extension '%1' was denied.",
extension));
}
return ok;
}
bool AppletAuthorization::authorizeOptionalExtension(const QString &extension)
{
return m_scriptEngine->applet()->hasAuthorization(extension);
}
bool AppletAuthorization::authorizeExternalExtensions()
{
return false;
}

View File

@ -0,0 +1,44 @@
/*
* Copyright 2010 Aaron J. Seigo <aseigo@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef APPLETAUTHORIZATION_H
#define APPLETAUTHORIZATION_H
#include "authorization.h"
namespace Plasma {
class AppletScript;
}
class SimpleJavaScriptApplet;
class AppletAuthorization : public Authorization
{
public:
AppletAuthorization(Plasma::AppletScript *scriptEngine);
bool authorizeRequiredExtension(const QString &extension);
bool authorizeOptionalExtension(const QString &extension);
bool authorizeExternalExtensions();
private:
Plasma::AppletScript *m_scriptEngine;
};
#endif

View File

@ -0,0 +1,490 @@
/*
* Copyright 2008 Chani Armitage <chani@kde.org>
* Copyright 2008, 2009 Aaron Seigo <aseigo@kde.org>
* Copyright 2010 Marco Martin <mart@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "appletinterface.h"
#include <QAction>
#include <QDir>
#include <QFile>
#include <QScriptEngine>
#include <QSignalMapper>
#include <QTimer>
#include <KDebug>
#include <KGlobalSettings>
#include <KIcon>
#include <KService>
#include <KServiceTypeTrader>
#include <Plasma/Plasma>
#include <Plasma/Applet>
#include <Plasma/Corona>
#include <Plasma/Package>
Q_DECLARE_METATYPE(AppletInterface*)
AppletInterface::AppletInterface(AbstractJsAppletScript *parent)
: QObject(parent),
m_appletScriptEngine(parent),
m_actionSignals(0)
{
connect(this, SIGNAL(releaseVisualFocus()), applet(), SIGNAL(releaseVisualFocus()));
connect(this, SIGNAL(configNeedsSaving()), applet(), SIGNAL(configNeedsSaving()));
connect(applet(), SIGNAL(immutabilityChanged(Plasma::ImmutabilityType)), this, SIGNAL(immutableChanged()));
connect(applet(), SIGNAL(newStatus(Plasma::ItemStatus)), this, SIGNAL(statusChanged()));
connect(m_appletScriptEngine, SIGNAL(formFactorChanged()),
this, SIGNAL(formFactorChanged()));
connect(m_appletScriptEngine, SIGNAL(locationChanged()),
this, SIGNAL(locationChanged()));
connect(m_appletScriptEngine, SIGNAL(contextChanged()),
this, SIGNAL(contextChanged()));
}
AppletInterface::~AppletInterface()
{
}
AppletInterface *AppletInterface::extract(QScriptEngine *engine)
{
QScriptValue appletValue = engine->globalObject().property("plasmoid");
return qobject_cast<AppletInterface*>(appletValue.toQObject());
}
Plasma::DataEngine* AppletInterface::dataEngine(const QString &name)
{
return applet()->dataEngine(name);
}
AppletInterface::FormFactor AppletInterface::formFactor() const
{
return static_cast<FormFactor>(applet()->formFactor());
}
AppletInterface::Location AppletInterface::location() const
{
return static_cast<Location>(applet()->location());
}
QString AppletInterface::currentActivity() const
{
return applet()->containment()->activity();
}
AppletInterface::AspectRatioMode AppletInterface::aspectRatioMode() const
{
return static_cast<AspectRatioMode>(applet()->aspectRatioMode());
}
void AppletInterface::setAspectRatioMode(AppletInterface::AspectRatioMode mode)
{
applet()->setAspectRatioMode(static_cast<Plasma::AspectRatioMode>(mode));
}
bool AppletInterface::shouldConserveResources() const
{
return applet()->shouldConserveResources();
}
void AppletInterface::setFailedToLaunch(bool failed, const QString &reason)
{
m_appletScriptEngine->setFailedToLaunch(failed, reason);
}
bool AppletInterface::isBusy() const
{
return applet()->isBusy();
}
void AppletInterface::setBusy(bool busy)
{
applet()->setBusy(busy);
}
AppletInterface::BackgroundHints AppletInterface::backgroundHints() const
{
return static_cast<BackgroundHints>(static_cast<int>(applet()->backgroundHints()));
}
void AppletInterface::setBackgroundHints(BackgroundHints hint)
{
applet()->setBackgroundHints(Plasma::BackgroundHints(hint));
}
void AppletInterface::setConfigurationRequired(bool needsConfiguring, const QString &reason)
{
m_appletScriptEngine->setConfigurationRequired(needsConfiguring, reason);
}
QString AppletInterface::activeConfig() const
{
return m_currentConfig.isEmpty() ? "main" : m_currentConfig;
}
void AppletInterface::setActiveConfig(const QString &name)
{
if (name == "main") {
m_currentConfig.clear();
return;
}
Plasma::ConfigLoader *loader = m_configs.value(name, 0);
if (!loader) {
QString path = m_appletScriptEngine->filePath("config", name + ".xml");
if (path.isEmpty()) {
return;
}
QFile f(path);
KConfigGroup cg = applet()->config();
loader = new Plasma::ConfigLoader(&cg, &f, this);
m_configs.insert(name, loader);
}
m_currentConfig = name;
}
void AppletInterface::writeConfig(const QString &entry, const QVariant &value)
{
Plasma::ConfigLoader *config = 0;
if (m_currentConfig.isEmpty()) {
config = applet()->configScheme();
} else {
config = m_configs.value(m_currentConfig, 0);
}
if (config) {
KConfigSkeletonItem *item = config->findItemByName(entry);
if (item) {
item->setProperty(value);
config->blockSignals(true);
config->writeConfig();
config->blockSignals(false);
m_appletScriptEngine->configNeedsSaving();
}
} else
kWarning() << "Couldn't find a configuration entry";
}
QVariant AppletInterface::readConfig(const QString &entry) const
{
Plasma::ConfigLoader *config = 0;
QVariant result;
if (m_currentConfig.isEmpty()) {
config = applet()->configScheme();
} else {
config = m_configs.value(m_currentConfig, 0);
}
if (config) {
result = config->property(entry);
}
return result;
}
QString AppletInterface::file(const QString &fileType)
{
return m_appletScriptEngine->filePath(fileType, QString());
}
QString AppletInterface::file(const QString &fileType, const QString &filePath)
{
return m_appletScriptEngine->filePath(fileType, filePath);
}
QList<QAction*> AppletInterface::contextualActions() const
{
QList<QAction*> actions;
Plasma::Applet *a = applet();
if (a->hasFailedToLaunch()) {
return actions;
}
foreach (const QString &name, m_actions) {
QAction *action = a->action(name);
if (action) {
actions << action;
}
}
return actions;
}
void AppletInterface::setActionSeparator(const QString &name)
{
Plasma::Applet *a = applet();
QAction *action = a->action(name);
if (action) {
action->setSeparator(true);
} else {
action = new QAction(this);
action->setSeparator(true);
a->addAction(name, action);
m_actions.append(name);
}
}
void AppletInterface::setAction(const QString &name, const QString &text, const QString &icon, const QString &shortcut)
{
Plasma::Applet *a = applet();
QAction *action = a->action(name);
if (action) {
action->setText(text);
} else {
action = new QAction(text, this);
a->addAction(name, action);
Q_ASSERT(!m_actions.contains(name));
m_actions.append(name);
if (!m_actionSignals) {
m_actionSignals = new QSignalMapper(this);
connect(m_actionSignals, SIGNAL(mapped(QString)),
m_appletScriptEngine, SLOT(executeAction(QString)));
}
connect(action, SIGNAL(triggered()), m_actionSignals, SLOT(map()));
m_actionSignals->setMapping(action, name);
}
if (!icon.isEmpty()) {
action->setIcon(KIcon(icon));
}
if (!shortcut.isEmpty()) {
action->setShortcut(shortcut);
}
action->setObjectName(name);
}
void AppletInterface::removeAction(const QString &name)
{
Plasma::Applet *a = applet();
QAction *action = a->action(name);
if (action) {
if (m_actionSignals) {
m_actionSignals->removeMappings(action);
}
delete action;
}
m_actions.removeAll(name);
}
QAction *AppletInterface::action(QString name) const
{
return applet()->action(name);
}
bool AppletInterface::immutable() const
{
return applet()->immutability() != Plasma::Mutable;
}
bool AppletInterface::userConfiguring() const
{
return applet()->isUserConfiguring();
}
int AppletInterface::apiVersion() const
{
const QString constraint("[X-Plasma-API] == 'javascript' and 'Applet' in [X-Plasma-ComponentTypes]");
KService::List offers = KServiceTypeTrader::self()->query("Plasma/ScriptEngine", constraint);
if (offers.isEmpty()) {
return -1;
}
return offers.first()->property("X-KDE-PluginInfo-Version", QVariant::Int).toInt();
}
bool AppletInterface::include(const QString &script)
{
const QString path = m_appletScriptEngine->filePath("scripts", script);
if (path.isEmpty()) {
return false;
}
return m_appletScriptEngine->include(path);
}
void AppletInterface::debug(const QString &msg)
{
kDebug() << msg;
}
void AppletInterface::setAssociatedApplication(const QString &string)
{
applet()->setAssociatedApplication(string);
}
QString AppletInterface::associatedApplication() const
{
return applet()->associatedApplication();
}
void AppletInterface::setStatus(const AppletInterface::ItemStatus &status)
{
applet()->setStatus((Plasma::ItemStatus)status);
}
AppletInterface::ItemStatus AppletInterface::status() const
{
return (AppletInterface::ItemStatus)((int)(applet()->status()));
}
/*
QString AppletInterface::downloadPath(const QString &file)
{
KDesktopFile config(v.toVariant().value<Plasma::Package>().path() + "/metadata.desktop");
KConfigGroup cg = config.desktopGroup();
const QString pluginName = cg.readEntry("X-KDE-PluginInfo-Name", QString());
destination = KGlobalSettings::downloadPath() + "/Plasma/" + pluginName + '/';
}
*/
QStringList AppletInterface::downloadedFiles() const
{
const QString downloadDir = KGlobalSettings::downloadPath() + "/Plasma/" + applet()->pluginName();
QDir dir(downloadDir);
return dir.entryList(QDir::Files | QDir::NoSymLinks | QDir::Readable);
}
void AppletInterface::gc()
{
QTimer::singleShot(0, m_appletScriptEngine, SLOT(collectGarbage()));
}
///////////// ContainmentInterface
ContainmentInterface::ContainmentInterface(AbstractJsAppletScript *parent)
: APPLETSUPERCLASS(parent),
m_movableApplets(true)
{
connect(containment(), SIGNAL(appletRemoved(Plasma::Applet *)), this, SLOT(appletRemovedForward(Plasma::Applet *)));
connect(containment(), SIGNAL(appletAdded(Plasma::Applet *, const QPointF &)), this, SLOT(appletAddedForward(Plasma::Applet *, const QPointF &)));
connect(containment(), SIGNAL(screenChanged(int, int, Plasma::Containment*)), this, SIGNAL(screenChanged()));
connect(containment(), SIGNAL(activityChanged()), this, SIGNAL(activityChanged()));
if (containment()->corona()) {
connect(containment()->corona(), SIGNAL(availableScreenRegionChanged()),
this, SIGNAL(availableScreenRegionChanged()));
}
}
QVariantList ContainmentInterface::applets()
{
QVariantList list;
int i = 0;
foreach (Plasma::Applet *applet, containment()->applets()) {
list << QVariant::fromValue(applet);
++i;
}
return list;
}
void ContainmentInterface::setDrawWallpaper(bool drawWallpaper)
{
m_appletScriptEngine->setDrawWallpaper(drawWallpaper);
}
bool ContainmentInterface::drawWallpaper()
{
return m_appletScriptEngine->drawWallpaper();
}
ContainmentInterface::Type ContainmentInterface::containmentType() const
{
return (ContainmentInterface::Type)m_appletScriptEngine->containmentType();
}
void ContainmentInterface::setContainmentType(ContainmentInterface::Type type)
{
m_appletScriptEngine->setContainmentType((Plasma::Containment::Type)type);
}
int ContainmentInterface::screen() const
{
return containment()->screen();
}
QRectF ContainmentInterface::screenGeometry(int id) const
{
QRectF rect;
if (containment()->corona()) {
rect = QRectF(containment()->corona()->screenGeometry(id));
}
return rect;
}
QVariantList ContainmentInterface::availableScreenRegion(int id) const
{
QRegion reg;
if (containment()->corona()) {
reg = containment()->corona()->availableScreenRegion(id);
}
QVariantList regVal;
int i = 0;
foreach (QRect rect, reg.rects()) {
regVal << QVariant::fromValue(QRectF(rect));
}
return regVal;
}
void ContainmentInterface::appletAddedForward(Plasma::Applet *applet, const QPointF &pos)
{
emit appletAdded(applet, pos);
}
void ContainmentInterface::appletRemovedForward(Plasma::Applet *applet)
{
emit appletRemoved(applet);
}
QString ContainmentInterface::activityName() const
{
//TODO
return QString();
//return containment()->activityName();
}
QString ContainmentInterface::activityId() const
{
return containment()->activity();
}
#ifndef USE_JS_SCRIPTENGINE
#include "appletinterface.moc"
#endif

View File

@ -0,0 +1,377 @@
/*
* Copyright 2008 Chani Armitage <chani@kde.org>
* Copyright 2008, 2009 Aaron Seigo <aseigo@kde.org>
* Copyright 2010 Marco Martin <mart@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef APPLETINTERFACE_H
#define APPLETINTERFACE_H
#include <QAbstractAnimation>
#include <QObject>
#include <QScriptValue>
#include <Plasma/Applet>
#include <Plasma/Containment>
#include <Plasma/DataEngine>
#include <Plasma/Theme>
#include "abstractjsappletscript.h"
class QAction;
class QmlAppletScript;
class QSignalMapper;
class QSizeF;
namespace Plasma
{
class ConfigLoader;
} // namespace Plasa
class AppletInterface : public QObject
{
Q_OBJECT
Q_ENUMS(FormFactor)
Q_ENUMS(Location)
Q_ENUMS(AspectRatioMode)
Q_ENUMS(BackgroundHints)
Q_ENUMS(QtOrientation)
Q_ENUMS(QtModifiers)
Q_ENUMS(QtAnchorPoint)
Q_ENUMS(QtCorner)
Q_ENUMS(QtAlignment)
Q_ENUMS(QtMouseButton)
Q_ENUMS(AnimationDirection)
Q_ENUMS(IntervalAlignment)
Q_ENUMS(ThemeColors)
Q_ENUMS(ItemStatus)
Q_PROPERTY(AspectRatioMode aspectRatioMode READ aspectRatioMode WRITE setAspectRatioMode)
Q_PROPERTY(FormFactor formFactor READ formFactor NOTIFY formFactorChanged)
Q_PROPERTY(Location location READ location NOTIFY locationChanged)
Q_PROPERTY(QString currentActivity READ currentActivity NOTIFY contextChanged)
Q_PROPERTY(bool shouldConserveResources READ shouldConserveResources)
Q_PROPERTY(QString activeConfig WRITE setActiveConfig READ activeConfig)
Q_PROPERTY(bool busy WRITE setBusy READ isBusy)
Q_PROPERTY(BackgroundHints backgroundHints WRITE setBackgroundHints READ backgroundHints)
Q_PROPERTY(bool immutable READ immutable NOTIFY immutableChanged)
Q_PROPERTY(bool userConfiguring READ userConfiguring) // @since 4.5
Q_PROPERTY(int apiVersion READ apiVersion CONSTANT)
Q_PROPERTY(ItemStatus status READ status WRITE setStatus NOTIFY statusChanged)
Q_PROPERTY(QString associatedApplication WRITE setAssociatedApplication READ associatedApplication)
public:
AppletInterface(AbstractJsAppletScript *parent);
~AppletInterface();
//------------------------------------------------------------------
//enums copy&pasted from plasma.h because qtscript is evil
enum FormFactor {
Planar = 0, /**< The applet lives in a plane and has two
degrees of freedom to grow. Optimize for
desktop, laptop or tablet usage: a high
resolution screen 1-3 feet distant from the
viewer. */
MediaCenter, /**< As with Planar, the applet lives in a plane
but the interface should be optimized for
medium-to-high resolution screens that are
5-15 feet distant from the viewer. Sometimes
referred to as a "ten foot interface".*/
Horizontal, /**< The applet is constrained vertically, but
can expand horizontally. */
Vertical, /**< The applet is constrained horizontally, but
can expand vertically. */
Application /**< The Applet lives in a plane and should be optimized to look as a full application,
for the desktop or the particular device. */
};
enum Location {
Floating = 0, /**< Free floating. Neither geometry or z-ordering
is described precisely by this value. */
Desktop, /**< On the planar desktop layer, extending across
the full screen from edge to edge */
FullScreen, /**< Full screen */
TopEdge, /**< Along the top of the screen*/
BottomEdge, /**< Along the bottom of the screen*/
LeftEdge, /**< Along the left side of the screen */
RightEdge /**< Along the right side of the screen */
};
enum AspectRatioMode {
InvalidAspectRatioMode = -1, /**< Unsetted mode used for dev convenience
when there is a need to store the
aspectRatioMode somewhere */
IgnoreAspectRatio = 0, /**< The applet can be freely resized */
KeepAspectRatio = 1, /**< The applet keeps a fixed aspect ratio */
Square = 2, /**< The applet is always a square */
ConstrainedSquare = 3, /**< The applet is no wider (in horizontal
formfactors) or no higher (in vertical
ones) than a square */
FixedSize = 4 /** The applet cannot be resized */
};
enum ItemStatus {
UnknownStatus = 0, /**< The status is unknown **/
PassiveStatus = 1, /**< The Item is passive **/
ActiveStatus = 2, /**< The Item is active **/
NeedsAttentionStatus = 3, /**< The Item needs attention **/
AcceptingInputStatus = 4 /**< The Item is accepting input **/
};
//From Qt namespace
enum QtModifiers {
QtNoModifier = Qt::NoModifier,
QtShiftModifier = Qt::ShiftModifier,
QtControlModifier = Qt::ControlModifier,
QtAltModifier = Qt::AltModifier,
QtMetaModifier = Qt::MetaModifier
};
enum QtOrientation {
QtHorizontal= Qt::Horizontal,
QtVertical = Qt::Vertical
};
enum QtAnchorPoint {
QtAnchorLeft = Qt::AnchorLeft,
QtAnchorRight = Qt::AnchorRight,
QtAnchorBottom = Qt::AnchorBottom,
QtAnchorTop = Qt::AnchorTop,
QtAnchorHorizontalCenter = Qt::AnchorHorizontalCenter,
QtAnchorVerticalCenter = Qt::AnchorVerticalCenter
};
enum QtCorner {
QtTopLeftCorner = Qt::TopLeftCorner,
QtTopRightCorner = Qt::TopRightCorner,
QtBottomLeftCorner = Qt::BottomLeftCorner,
QtBottomRightCorner = Qt::BottomRightCorner
};
enum BackgroundHints {
NoBackground = Plasma::NoBackground,
StandardBackground = Plasma::StandardBackground,
TranslucentBackground = Plasma::TranslucentBackground,
DefaultBackground = Plasma::DefaultBackground
};
enum ThemeColors {
TextColor = Plasma::Theme::TextColor,
HighlightColor = Plasma::Theme::HighlightColor,
BackgroundColor = Plasma::Theme::BackgroundColor,
ButtonTextColor = Plasma::Theme::ButtonTextColor,
ButtonBackgroundColor = Plasma::Theme::ButtonBackgroundColor,
LinkColor = Plasma::Theme::LinkColor,
VisitedLinkColor = Plasma::Theme::VisitedLinkColor
};
enum QtAlignment {
QtAlignLeft = 0x0001,
QtAlignRight = 0x0002,
QtAlignHCenter = 0x0004,
QtAlignJustify = 0x0005,
QtAlignTop = 0x0020,
QtAlignBottom = 0x0020,
QtAlignVCenter = 0x0080
};
enum QtMouseButton {
QtNoButton = Qt::NoButton,
QtLeftButton = Qt::LeftButton,
QtRightButton = Qt::RightButton,
QtMidButton = Qt::MidButton,
QtXButton1 = Qt::XButton1,
QtXButton2 = Qt::XButton2
};
enum QtScrollBarPolicy {
QtScrollBarAsNeeded = Qt::ScrollBarAsNeeded,
QtScrollBarAlwaysOff = Qt::ScrollBarAlwaysOff,
QtScrollBarAlwaysOn = Qt::ScrollBarAlwaysOn
};
enum AnimationDirection {
AnimationForward = QAbstractAnimation::Forward,
AnimationBackward = QAbstractAnimation::Backward
};
enum IntervalAlignment {
NoAlignment = 0,
AlignToMinute,
AlignToHour
};
//-------------------------------------------------------------------
Q_INVOKABLE void gc();
Q_INVOKABLE FormFactor formFactor() const;
Location location() const;
QString currentActivity() const;
bool shouldConserveResources() const;
Q_INVOKABLE AspectRatioMode aspectRatioMode() const;
Q_INVOKABLE void setAspectRatioMode(AspectRatioMode mode);
Q_INVOKABLE void setFailedToLaunch(bool failed, const QString &reason = QString());
Q_INVOKABLE bool isBusy() const;
Q_INVOKABLE void setBusy(bool busy);
Q_INVOKABLE BackgroundHints backgroundHints() const;
Q_INVOKABLE void setBackgroundHints(BackgroundHints hint);
Q_INVOKABLE void setConfigurationRequired(bool needsConfiguring, const QString &reason = QString());
Q_INVOKABLE void setActionSeparator(const QString &name);
Q_INVOKABLE void setAction(const QString &name, const QString &text,
const QString &icon = QString(), const QString &shortcut = QString());
Q_INVOKABLE void removeAction(const QString &name);
Q_INVOKABLE QAction *action(QString name) const;
Q_INVOKABLE QString activeConfig() const;
Q_INVOKABLE void setActiveConfig(const QString &name);
Q_INVOKABLE QVariant readConfig(const QString &entry) const;
Q_INVOKABLE void writeConfig(const QString &entry, const QVariant &value);
Q_INVOKABLE QString file(const QString &fileType);
Q_INVOKABLE QString file(const QString &fileType, const QString &filePath);
Q_INVOKABLE bool include(const QString &script);
Q_INVOKABLE void debug(const QString &msg);
Plasma::DataEngine *dataEngine(const QString &name);
QList<QAction*> contextualActions() const;
bool immutable() const;
bool userConfiguring() const;
int apiVersion() const;
static AppletInterface *extract(QScriptEngine *engine);
inline Plasma::Applet *applet() const { return m_appletScriptEngine->applet(); }
void setAssociatedApplication(const QString &string);
QString associatedApplication() const;
void setStatus(const ItemStatus &status);
ItemStatus status() const;
// Q_INVOKABLE QString downloadPath(const QString &file);
Q_INVOKABLE QStringList downloadedFiles() const;
Q_SIGNALS:
void releaseVisualFocus();
void configNeedsSaving();
void formFactorChanged();
void locationChanged();
void contextChanged();
void immutableChanged();
void statusChanged();
protected:
AbstractJsAppletScript *m_appletScriptEngine;
private:
QStringList m_actions;
QSignalMapper *m_actionSignals;
QString m_currentConfig;
QMap<QString, Plasma::ConfigLoader*> m_configs;
};
class JsAppletInterface : public AppletInterface
{
Q_OBJECT
Q_PROPERTY(QObject *sender READ sender)
public:
JsAppletInterface(AbstractJsAppletScript *parent)
: AppletInterface(parent)
{
}
};
#ifdef USE_JS_SCRIPTENGINE
#define APPLETSUPERCLASS JsAppletInterface
#else
#define APPLETSUPERCLASS AppletInterface
#endif
class ContainmentInterface : public APPLETSUPERCLASS
{
Q_OBJECT
Q_PROPERTY(QVariantList applets READ applets)
Q_PROPERTY(bool drawWallpaper READ drawWallpaper WRITE setDrawWallpaper)
Q_PROPERTY(Type containmentType READ containmentType WRITE setContainmentType)
Q_PROPERTY(int screen READ screen NOTIFY screenChanged)
Q_PROPERTY(QString activityName READ activityName NOTIFY activityNameChanged)
Q_PROPERTY(QString activityId READ activityId NOTIFY activityIdChanged)
Q_ENUMS(Type)
public:
enum Type {
NoContainmentType = -1, /**< @internal */
DesktopContainment = 0, /**< A desktop containment */
PanelContainment, /**< A desktop panel */
CustomContainment = 127, /**< A containment that is neither a desktop nor a panel
but something application specific */
CustomPanelContainment = 128 /**< A customized desktop panel */
};
ContainmentInterface(AbstractJsAppletScript *parent);
inline Plasma::Containment *containment() const { return static_cast<Plasma::Containment *>(m_appletScriptEngine->applet()); }
QVariantList applets();
void setDrawWallpaper(bool drawWallpaper);
bool drawWallpaper();
Type containmentType() const;
void setContainmentType(Type type);
int screen() const;
QString activityName() const;
QString activityId() const;
Q_INVOKABLE QRectF screenGeometry(int id) const;
Q_INVOKABLE QVariantList availableScreenRegion(int id) const;
Q_SIGNALS:
void appletAdded(QObject *applet, const QPointF &pos);
void appletRemoved(QObject *applet);
void screenChanged();
void activityNameChanged();
void activityIdChanged();
void availableScreenRegionChanged();
protected Q_SLOTS:
void appletAddedForward(Plasma::Applet *applet, const QPointF &pos);
void appletRemovedForward(Plasma::Applet *applet);
private:
bool m_movableApplets;
};
#endif

View File

@ -0,0 +1,379 @@
/*
* Copyright 2009 by Alan Alpert <alan.alpert@nokia.com>
* Copyright 2010 by Ménard Alexis <menard@kde.org>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <QQmlComponent>
#include <QQmlContext>
#include <QQmlEngine>
#include <QQmlExpression>
#include <QFile>
#include <QTimer>
#include <QUiLoader>
#include <QWidget>
#include <KConfigGroup>
#include <KDebug>
#include <KGlobal>
#include <KLocale>
#include <KGlobalSettings>
#include <klocalizedstring.h>
#include <Plasma/Applet>
#include <Plasma/Package>
#include <Plasma/PluginLoader>
#include "plasmoid/declarativeappletscript.h"
#include "plasmoid/appletinterface.h"
#include "common/scriptenv.h"
#include "declarative/qmlobject.h"
//#include "declarative/declarativeitemcontainer_p.h"
#include "declarative/packageaccessmanagerfactory.h"
K_EXPORT_PLASMA_APPLETSCRIPTENGINE(declarativeappletscript, DeclarativeAppletScript)
QScriptValue constructIconClass(QScriptEngine *engine);
QScriptValue constructKUrlClass(QScriptEngine *engine);
QScriptValue constructQPointClass(QScriptEngine *engine);
void registerSimpleAppletMetaTypes(QScriptEngine *engine);
DeclarativeAppletScript::DeclarativeAppletScript(QObject *parent, const QVariantList &args)
: AbstractJsAppletScript(parent, args),
m_qmlObject(0),
m_toolBoxWidget(0),
m_interface(0),
m_env(0),
m_auth(this)
{
Q_UNUSED(args);
}
DeclarativeAppletScript::~DeclarativeAppletScript()
{
}
bool DeclarativeAppletScript::init()
{
m_qmlObject = new QmlObject(applet());
m_qmlObject->setInitializationDelayed(true);
connect(m_qmlObject, SIGNAL(finished()), this, SLOT(qmlCreationFinished()));
//FIXME: what replaced this?
//KGlobal::locale()->insertCatalog("plasma_applet_" % description().pluginName());
//make possible to import extensions from the package
//FIXME: probably to be removed, would make possible to use native code from within the package :/
//m_qmlObject->engine()->addImportPath(package()->path()+"/contents/imports");
//use our own custom network access manager that will access Plasma packages and to manage security (i.e. deny access to remote stuff when the proper extension isn't enabled
QQmlEngine *engine = m_qmlObject->engine();
QQmlNetworkAccessManagerFactory *factory = engine->networkAccessManagerFactory();
engine->setNetworkAccessManagerFactory(0);
delete factory;
engine->setNetworkAccessManagerFactory(new PackageAccessManagerFactory(&package(), &m_auth));
m_qmlObject->setQmlPath(mainScript());
if (!m_qmlObject->engine() || !m_qmlObject->engine()->rootContext() || !m_qmlObject->engine()->rootContext()->isValid() || m_qmlObject->mainComponent()->isError()) {
QString reason;
foreach (QQmlError error, m_qmlObject->mainComponent()->errors()) {
reason += error.toString()+'\n';
}
setFailedToLaunch(true, reason);
return false;
}
Plasma::Applet *a = applet();
Plasma::Containment *cont = qobject_cast<Plasma::Containment *>(a);
//TODO: assign the graphical root object
if (cont) {
m_interface = new ContainmentInterface(this);
//fail? so it's a normal Applet
} else {
m_interface = new AppletInterface(this);
}
connect(applet(), SIGNAL(activate()),
this, SLOT(activate()));
setupObjects();
return true;
}
void DeclarativeAppletScript::qmlCreationFinished()
{
//If it's a popupapplet and the root object has a "compactRepresentation" component, use that instead of the icon
Plasma::Applet *a = applet();
m_self->setProperty("rootItem", QVariant::fromValue(m_qmlObject->rootObject()));
/*TODO: all applets must become pa
if (pa) {
QQmlComponent *iconComponent = m_qmlObject->rootObject()->property("compactRepresentation").value<QQmlComponent *>();
if (iconComponent) {
QDeclarativeItem *declarativeIcon = qobject_cast<QDeclarativeItem *>(iconComponent->create(iconComponent->creationContext()));
if (declarativeIcon) {
pa->setPopupIcon(QIcon());
QGraphicsLinearLayout *lay = new QGraphicsLinearLayout(a);
lay->setContentsMargins(0, 0, 0, 0);
DeclarativeItemContainer *declarativeItemContainer = new DeclarativeItemContainer(a);
lay->addItem(declarativeItemContainer);
declarativeItemContainer->setDeclarativeItem(declarativeIcon, true);
} else {
pa->setPopupIcon(a->icon());
}
} else {
pa->setPopupIcon(a->icon());
}
}*/
Plasma::Containment *pc = qobject_cast<Plasma::Containment *>(a);
if (pc) {
Plasma::Package pkg = Plasma::PluginLoader::self()->loadPackage("Plasma/Generic");
pkg.setPath("org.kde.toolbox");
if (pkg.isValid()) {
const QString qmlPath = pkg.filePath("mainscript");
m_toolBoxWidget = new QmlObject(pc);
m_toolBoxWidget->setInitializationDelayed(true);
m_toolBoxWidget->setQmlPath(qmlPath);
m_toolBoxWidget->rootObject()->setProperty("plasmoid", QVariant::fromValue(m_self));
} else {
kWarning() << "Could not load org.kde.toolbox package.";
}
}
}
QString DeclarativeAppletScript::filePath(const QString &type, const QString &file) const
{
const QString path = m_env->filePathFromScriptContext(type.toLocal8Bit().constData(), file);
if (!path.isEmpty()) {
return path;
}
return package().filePath(type.toLocal8Bit().constData(), file);
}
void DeclarativeAppletScript::configChanged()
{
if (!m_env) {
return;
}
m_env->callEventListeners("configchanged");
}
QObject *DeclarativeAppletScript::loadui(const QString &filename)
{
QFile f(filename);
if (!f.open(QIODevice::ReadOnly)) {
kWarning() << i18n("Unable to open '%1'",filename);
return 0;
}
QUiLoader loader;
QWidget *w = loader.load(&f);
f.close();
return w;
}
void DeclarativeAppletScript::constraintsEvent(Plasma::Constraints constraints)
{
if (constraints & Plasma::FormFactorConstraint) {
emit formFactorChanged();
}
if (constraints & Plasma::LocationConstraint) {
emit locationChanged();
}
if (constraints & Plasma::ContextConstraint) {
emit contextChanged();
}
}
void DeclarativeAppletScript::popupEvent(bool popped)
{
if (!m_env) {
return;
}
QScriptValueList args;
args << popped;
m_env->callEventListeners("popupEvent", args);
}
void DeclarativeAppletScript::dataUpdated(const QString &name, const Plasma::DataEngine::Data &data)
{
#if 0
TODO: callEventListeners is broken without qscriptengine
if (!m_engine) {
return;
}
QScriptValueList args;
args << m_engine->toScriptValue(name) << m_engine->toScriptValue(data);
m_env->callEventListeners("dataUpdated", args);
#endif
}
void DeclarativeAppletScript::activate()
{
#if 0
TODO: callEventListeners is broken without qscriptengine
if (!m_env) {
return;
}
m_env->callEventListeners("activate");
#endif
}
void DeclarativeAppletScript::executeAction(const QString &name)
{
if (!m_env) {
return;
}
if (m_qmlObject->rootObject()) {
QMetaObject::invokeMethod(m_qmlObject->rootObject(), QString("action_" + name).toLatin1(), Qt::DirectConnection);
}
}
bool DeclarativeAppletScript::include(const QString &path)
{
return m_env->include(path);
}
ScriptEnv *DeclarativeAppletScript::scriptEnv()
{
return m_env;
}
void DeclarativeAppletScript::setupObjects()
{
#if 0
TODO: make this work with QQmlEngine
m_engine = m_qmlObject->scriptEngine();
if (!m_engine) {
return;
}
connect(m_engine, SIGNAL(signalHandlerException(const QScriptValue &)),
this, SLOT(signalHandlerException(const QScriptValue &)));
delete m_env;
m_env = new ScriptEnv(this, m_engine);
QScriptValue global = m_engine->globalObject();
QScriptValue v = m_engine->newVariant(QVariant::fromValue(*applet()->package()));
global.setProperty("__plasma_package", v,
QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
m_self = m_engine->newQObject(m_interface);
m_self.setScope(global);
global.setProperty("plasmoid", m_self);
m_env->addMainObjectProperties(m_self);
QScriptValue args = m_engine->newArray();
int i = 0;
foreach (const QVariant &arg, applet()->startupArguments()) {
args.setProperty(i, m_engine->newVariant(arg));
++i;
}
global.setProperty("startupArguments", args);
// Add a global loadui method for ui files
QScriptValue fun = m_engine->newFunction(DeclarativeAppletScript::loadui);
global.setProperty("loadui", fun);
ScriptEnv::registerEnums(global, AppletInterface::staticMetaObject);
//Make enum values accessible also as plasmoid.Planar etc
ScriptEnv::registerEnums(m_self, AppletInterface::staticMetaObject);
global.setProperty("dataEngine", m_engine->newFunction(DeclarativeAppletScript::dataEngine));
global.setProperty("service", m_engine->newFunction(DeclarativeAppletScript::service));
global.setProperty("loadService", m_engine->newFunction(DeclarativeAppletScript::loadService));
//Add stuff from Qt
//TODO: move to libkdeclarative?
ByteArrayClass *baClass = new ByteArrayClass(m_engine);
global.setProperty("ByteArray", baClass->constructor());
global.setProperty("QPoint", constructQPointClass(m_engine));
// Add stuff from KDE libs
qScriptRegisterSequenceMetaType<KUrl::List>(m_engine);
global.setProperty("Url", constructKUrlClass(m_engine));
// Add stuff from Plasma
global.setProperty("Svg", m_engine->newFunction(DeclarativeAppletScript::newPlasmaSvg));
global.setProperty("FrameSvg", m_engine->newFunction(DeclarativeAppletScript::newPlasmaFrameSvg));
if (!m_env->importExtensions(description(), m_self, m_auth)) {
return;
}
registerSimpleAppletMetaTypes(m_engine);
QTimer::singleShot(0, this, SLOT(configChanged()));
#endif
}
QObject *DeclarativeAppletScript::dataEngine(const QString &dataEngineName)
{
return applet()->dataEngine(dataEngineName);
}
QObject *DeclarativeAppletScript::service(const QString &dataEngine, const QString &source)
{
Plasma::DataEngine *data = applet()->dataEngine(dataEngine);
return data->serviceForSource(source);
}
QObject *DeclarativeAppletScript::loadService(const QString &pluginName)
{
return Plasma::PluginLoader::self()->loadService(pluginName, QVariantList(), applet());
}
QList<QAction*> DeclarativeAppletScript::contextualActions()
{
if (!m_interface) {
return QList<QAction *>();
}
return m_interface->contextualActions();
}
QQmlEngine *DeclarativeAppletScript::engine() const
{
return m_qmlObject->engine();
}
#include "declarativeappletscript.moc"

View File

@ -0,0 +1,87 @@
/*
* Copyright 2009 by Alan Alpert <alan.alpert@nokia.com>
* Copyright 2010 by Ménard Alexis <menard@kde.org>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef DECLARATIVE_APPLETSCRIPT_H
#define DECLARATIVE_APPLETSCRIPT_H
#include <kdemacros.h>
#include "abstractjsappletscript.h"
#include "plasmoid/appletauthorization.h"
#include <Plasma/DataEngine>
class AppletInterface;
class QmlObject;
class ScriptEnv;
class EngineAccess;
class DeclarativeAppletScript : public AbstractJsAppletScript
{
Q_OBJECT
public:
DeclarativeAppletScript(QObject *parent, const QVariantList &args);
~DeclarativeAppletScript();
QString filePath(const QString &type, const QString &file) const;
QList<QAction*> contextualActions();
void constraintsEvent(Plasma::Constraints constraints);
bool include(const QString &path);
ScriptEnv *scriptEnv();
QQmlEngine *engine() const;
static QObject *loadui(const QString &filename);
QObject *dataEngine(const QString &dataEngineName);
QObject *service(const QString &dataEngine, const QString &source);
QObject *loadService(const QString &pluginName);
public Q_SLOTS:
void executeAction(const QString &name);
void dataUpdated(const QString &name, const Plasma::DataEngine::Data &data);
//void signalHandlerException(const QObject &exception);
void popupEvent(bool popped);
void activate();
void configChanged();
void qmlCreationFinished();
protected:
bool init();
void setupObjects();
Q_SIGNALS:
void formFactorChanged();
void locationChanged();
void contextChanged();
private:
QmlObject *m_qmlObject;
QmlObject *m_toolBoxWidget;
AppletInterface *m_interface;
QObject *m_self;
ScriptEnv *m_env;
AppletAuthorization m_auth;
};
#endif

View File

@ -0,0 +1,22 @@
/*
* Copyright 2010 Marco Martin <mart@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#define USE_JS_SCRIPTENGINE
#include "appletinterface.cpp"
#include "appletinterface.moc"