ok, this time _really_ move it over. svn is sometimes a little too forgiving / sloppy :(

svn path=/trunk/KDE/kdebase/runtime/; revision=967245
This commit is contained in:
Aaron J. Seigo 2009-05-13 00:55:25 +00:00
parent d1d2e9078d
commit 71789306b7
36 changed files with 6549 additions and 0 deletions

View File

@ -0,0 +1,48 @@
set(simple_javascript_engine_SRCS
simplejavascriptapplet.cpp
appletinterface.cpp
uiloader.cpp
qtgui/font.cpp
qtgui/graphicsitem.cpp
qtgui/linearlayout.cpp
qtgui/painter.cpp
qtgui/point.cpp
qtgui/rect.cpp
qtgui/size.cpp
qtgui/timer.cpp
qtgui/url.cpp
)
include_directories(${PHONON_INCLUDES})
kde4_add_plugin(plasma_appletscript_simple_javascript
${simple_javascript_engine_SRCS})
target_link_libraries(plasma_appletscript_simple_javascript
${KDE4_KDECORE_LIBS}
${KDE4_PLASMA_LIBS}
${QT_QTSCRIPT_LIBRARY}
${QT_QTUITOOLS_LIBRARY}
${QT_QTXML_LIBRARY}
)
install(TARGETS plasma_appletscript_simple_javascript DESTINATION ${PLUGIN_INSTALL_DIR})
install(FILES plasma-scriptengine-applet-simple-javascript.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
set(javascript_runner_engine_SRCS
javascriptrunner.cpp
)
kde4_add_plugin(plasma_runnerscript_javascript ${javascript_runner_engine_SRCS})
target_link_libraries(plasma_runnerscript_javascript
${KDE4_KDECORE_LIBS}
${KDE4_PLASMA_LIBS}
${QT_QTSCRIPT_LIBRARY}
${QT_QTUITOOLS_LIBRARY}
${QT_QTXML_LIBRARY}
)
install(TARGETS plasma_runnerscript_javascript DESTINATION ${PLUGIN_INSTALL_DIR})
install(FILES plasma-scriptengine-runner-javascript.desktop DESTINATION ${SERVICES_INSTALL_DIR})

View File

@ -0,0 +1,2 @@
#! /usr/bin/env bash
$XGETTEXT *.cpp qtgui/*.cpp -o $podir/plasma_scriptengine_qscript.pot

View File

@ -0,0 +1,281 @@
/*
* Copyright 2008 Chani Armitage <chani@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 <QFile>
#include <QSignalMapper>
#include <KDE/KIcon>
#include <Plasma/Plasma>
#include <Plasma/Applet>
#include <Plasma/Context>
#include <Plasma/DataEngine>
#include <Plasma/Package>
#include "simplejavascriptapplet.h"
AppletInterface::AppletInterface(SimpleJavaScriptApplet *parent)
: QObject(parent),
m_appletScriptEngine(parent),
m_actionSignals(0)
{
connect(this, SIGNAL(releaseVisualFocus()), applet(), SIGNAL(releaseVisualFocus()));
connect(this, SIGNAL(configNeedsSaving()), applet(), SIGNAL(configNeedsSaving()));
}
AppletInterface::~AppletInterface()
{
}
Plasma::DataEngine* AppletInterface::dataEngine(const QString &name)
{
return applet()->dataEngine(name);
}
AppletInterface::FormFactor AppletInterface::formFactor()
{
return static_cast<FormFactor>(applet()->formFactor());
}
AppletInterface::Location AppletInterface::location()
{
return static_cast<Location>(applet()->location());
}
QString AppletInterface::currentActivity()
{
return applet()->context()->currentActivity();
}
AppletInterface::AspectRatioMode AppletInterface::aspectRatioMode()
{
return static_cast<AspectRatioMode>(applet()->aspectRatioMode());
}
void AppletInterface::setAspectRatioMode(AppletInterface::AspectRatioMode mode)
{
applet()->setAspectRatioMode(static_cast<Plasma::AspectRatioMode>(mode));
}
bool AppletInterface::shouldConserveResources()
{
return applet()->shouldConserveResources();
}
void AppletInterface::setFailedToLaunch(bool failed, const QString &reason)
{
m_appletScriptEngine->setFailedToLaunch(failed, reason);
}
bool AppletInterface::isBusy()
{
return applet()->isBusy();
}
void AppletInterface::setBusy(bool busy)
{
applet()->setBusy(busy);
}
void AppletInterface::setConfigurationRequired(bool needsConfiguring, const QString &reason)
{
m_appletScriptEngine->setConfigurationRequired(needsConfiguring, reason);
}
void AppletInterface::update()
{
applet()->update();
}
QString AppletInterface::activeConfig() const
{
return m_currentConfig.isEmpty() ? "main" : m_currentConfig;
}
void AppletInterface::setActiveConfig(const QString &name)
{
if (name == "main") {
m_currentConfig = QString();
return;
}
Plasma::ConfigLoader *loader = m_configs.value(name, 0);
if (!loader) {
QString path = applet()->package()->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->writeConfig();
m_appletScriptEngine->configNeedsSaving();
}
}
}
QScriptValue 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 m_appletScriptEngine->variantToScriptValue(result);
}
QString AppletInterface::file(const QString &fileType)
{
return m_appletScriptEngine->package()->filePath(fileType.toLocal8Bit().constData());
}
QString AppletInterface::file(const QString &fileType, const QString &filePath)
{
return m_appletScriptEngine->package()->filePath(fileType.toLocal8Bit().constData(), filePath);
}
const Plasma::Package *AppletInterface::package() const
{
kDebug() << "woot";
return m_appletScriptEngine->package();
}
QList<QAction*> AppletInterface::contextualActions() const
{
QList<QAction*> actions;
Plasma::Applet *a = applet();
foreach (const QString &name, m_actions) {
QAction *action = a->action(name);
if (action) {
actions << action;
}
}
return actions;
}
QSizeF AppletInterface::size() const
{
return applet()->size();
}
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.insert(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);
}
action->setIcon(icon.isEmpty() ? QIcon() : KIcon(icon));
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.remove(name);
}
void AppletInterface::resize(qreal w, qreal h)
{
applet()->resize(w,h);
}
void AppletInterface::setMinimumSize(qreal w, qreal h)
{
applet()->setMinimumSize(w,h);
}
void AppletInterface::setPreferredSize(qreal w, qreal h)
{
applet()->setPreferredSize(w,h);
}
void AppletInterface::dataUpdated(QString source, Plasma::DataEngine::Data data)
{
m_appletScriptEngine->dataUpdated(source, data);
}
Plasma::Applet *AppletInterface::applet() const
{
return m_appletScriptEngine->applet();
}
#include "appletinterface.moc"

View File

@ -0,0 +1,183 @@
/*
* Copyright 2008 Chani Armitage <chani@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 <QObject>
#include <QScriptValue>
#include <Plasma/DataEngine>
class QAction;
class QGraphicsLayout;
class SimpleJavaScriptApplet;
class QSignalMapper;
class QSizeF;
class KConfigGroup;
namespace Plasma
{
class Applet;
class ConfigLoader;
} // namespace Plasa
class AppletInterface : public QObject
{
Q_OBJECT
Q_ENUMS(FormFactor)
Q_ENUMS(Location)
Q_ENUMS(AspectRatioMode)
Q_ENUMS(QtOrientation)
Q_ENUMS(QtAlignment)
Q_PROPERTY(QString activeConfig WRITE setActiveConfig READ activeConfig)
public:
AppletInterface(SimpleJavaScriptApplet *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. */
};
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 */
};
//From Qt namespace
enum QtOrientation {
QtHorizontal= Qt::Horizontal,
QtVertical = Qt::Vertical
};
enum QtAlignment {
QtAlignLeft = 0x0001,
QtAlignRight = 0x0002,
QtAlignHCenter = 0x0004,
QtAlignJustify = 0x0005,
QtAlignTop = 0x0020,
QtAlignBottom = 0x0020,
QtAlignVCenter = 0x0080
};
//-------------------------------------------------------------------
Q_INVOKABLE FormFactor formFactor();
Q_INVOKABLE Location location();
Q_INVOKABLE QString currentActivity();
Q_INVOKABLE AspectRatioMode aspectRatioMode();
Q_INVOKABLE void setAspectRatioMode(AspectRatioMode mode);
Q_INVOKABLE bool shouldConserveResources();
Q_INVOKABLE void setFailedToLaunch(bool failed, const QString &reason = QString());
Q_INVOKABLE bool isBusy();
Q_INVOKABLE void setBusy(bool busy);
Q_INVOKABLE void setConfigurationRequired(bool needsConfiguring, const QString &reason = QString());
Q_INVOKABLE QSizeF size() const;
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 void resize(qreal w, qreal h);
Q_INVOKABLE void setMinimumSize(qreal w, qreal h);
Q_INVOKABLE void setPreferredSize(qreal w, qreal h);
Q_INVOKABLE void update();
Q_INVOKABLE QString activeConfig() const;
Q_INVOKABLE void setActiveConfig(const QString &name);
Q_INVOKABLE QScriptValue 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);
Plasma::DataEngine *dataEngine(const QString &name);
const Plasma::Package *package() const;
QList<QAction*> contextualActions() const;
Plasma::Applet *applet() const;
Q_SIGNALS:
void releaseVisualFocus();
void configNeedsSaving();
public Q_SLOTS:
void dataUpdated(QString source, Plasma::DataEngine::Data data);
private:
SimpleJavaScriptApplet *m_appletScriptEngine;
QSet<QString> m_actions;
QSignalMapper *m_actionSignals;
QString m_currentConfig;
QMap<QString, Plasma::ConfigLoader*> m_configs;
};
#endif

View File

@ -0,0 +1,363 @@
/****************************************************************************
**
** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.
**
** This file is part of the plugins of the Qt Toolkit.
**
** This file may be used under the terms of the GNU General Public
** License version 2.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of
** this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
** http://trolltech.com/products/qt/licenses/licensing/opensource/
**
** If you are unsure which license is appropriate for your use, please
** review the following information:
** http://trolltech.com/products/qt/licenses/licensing/licensingoverview
** or contact the sales department at sales@trolltech.com.
**
** In addition, as a special exception, Trolltech gives you certain
** additional rights. These rights are described in the Trolltech GPL
** Exception version 1.0, which can be found at
** http://www.trolltech.com/products/qt/gplexception/ and in the file
** GPL_EXCEPTION.txt in this package.
**
** In addition, as a special exception, Trolltech, as the sole copyright
** holder for Qt Designer, grants users of the Qt/Eclipse Integration
** plug-in the right for the Qt/Eclipse Integration to link to
** functionality provided by Qt Designer and its related libraries.
**
** Trolltech reserves all rights not expressly granted herein.
**
** Trolltech ASA (c) 2007
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
#ifndef QTSCRIPTEXTENSIONS_GLOBAL_H
#define QTSCRIPTEXTENSIONS_GLOBAL_H
#include <QtCore/QSharedData>
#define DECLARE_SELF(Class, __fn__) \
Class* self = qscriptvalue_cast<Class*>(ctx->thisObject()); \
if (!self) { \
return ctx->throwError(QScriptContext::TypeError, \
QString::fromLatin1("%0.prototype.%1: this object is not a %0") \
.arg(#Class).arg(#__fn__)); \
}
#define DECLARE_SELF2(Class, __fn__, __ret__) \
Class* self = qscriptvalue_cast<Class*>(thisObject()); \
if (!self) { \
context()->throwError(QScriptContext::TypeError, \
QString::fromLatin1("%0.prototype.%1: this object is not a %0") \
.arg(#Class).arg(#__fn__)); \
return __ret__; \
}
#define ADD_METHOD(__p__, __f__) \
__p__.setProperty(#__f__, __p__.engine()->newFunction(__f__))
#define ADD_GET_METHOD(__p__, __get__) \
ADD_METHOD(__p__, __get__)
#define ADD_GET_SET_METHODS(__p__, __get__, __set__) \
do { \
ADD_METHOD(__p__, __get__); \
ADD_METHOD(__p__, __set__); \
} while (0);
#define ADD_CTOR_FUNCTION(__c__, __f__) ADD_METHOD(__c__, __f__)
#define ADD_ENUM_VALUE(__c__, __ns__, __v__) \
__c__.setProperty(#__v__, QScriptValue(__c__.engine(), __ns__::__v__))
#define BEGIN_DECLARE_METHOD(Class, __mtd__) \
static QScriptValue __mtd__(QScriptContext *ctx, QScriptEngine *eng) \
{ \
DECLARE_SELF(Class, __mtd__);
#define END_DECLARE_METHOD \
}
#define DECLARE_GET_METHOD(Class, __get__) \
BEGIN_DECLARE_METHOD(Class, __get__) { \
return qScriptValueFromValue(eng, self->__get__()); \
} END_DECLARE_METHOD
#define DECLARE_SET_METHOD(Class, T, __set__) \
BEGIN_DECLARE_METHOD(Class, __set__) { \
self->__set__(qscriptvalue_cast<T>(ctx->argument(0))); \
return eng->undefinedValue(); \
} END_DECLARE_METHOD
#define DECLARE_GET_SET_METHODS(Class, T, __get__, __set__) \
DECLARE_GET_METHOD(Class, /*T,*/ __get__) \
DECLARE_SET_METHOD(Class, T, __set__)
#define DECLARE_SIMPLE_GET_METHOD(Class, __get__) \
BEGIN_DECLARE_METHOD(Class, __get__) { \
return QScriptValue(eng, self->__get__()); \
} END_DECLARE_METHOD
#define DECLARE_SIMPLE_SET_METHOD(Class, ToType, __set__) \
BEGIN_DECLARE_METHOD(Class, __set__) { \
self->__set__(ctx->argument(0).ToType()); \
return eng->undefinedValue(); \
} END_DECLARE_METHOD
#define DECLARE_BOOLEAN_GET_METHOD(Class, __set__) \
DECLARE_SIMPLE_GET_METHOD(Class, __set__)
#define DECLARE_BOOLEAN_SET_METHOD(Class, __set__) \
DECLARE_SIMPLE_SET_METHOD(Class, toBoolean, __set__)
#define DECLARE_INT_GET_METHOD(Class, __set__) \
DECLARE_SIMPLE_GET_METHOD(Class, __set__)
#define DECLARE_INT_SET_METHOD(Class, __set__) \
DECLARE_SIMPLE_SET_METHOD(Class, toInt32, __set__)
#define DECLARE_NUMBER_GET_METHOD(Class, __set__) \
DECLARE_SIMPLE_GET_METHOD(Class, __set__)
#define DECLARE_NUMBER_SET_METHOD(Class, __set__) \
DECLARE_SIMPLE_SET_METHOD(Class, toNumber, __set__)
#define DECLARE_STRING_GET_METHOD(Class, __set__) \
DECLARE_SIMPLE_GET_METHOD(Class, __set__)
#define DECLARE_STRING_SET_METHOD(Class, __set__) \
DECLARE_SIMPLE_SET_METHOD(Class, toString, __set__)
#define DECLARE_QOBJECT_GET_METHOD(Class, __get__) \
BEGIN_DECLARE_METHOD(Class, __get__) { \
return eng->newQObject(self->__get__()); \
} END_DECLARE_METHOD
#define DECLARE_QOBJECT_SET_METHOD(Class, __set__) \
DECLARE_SIMPLE_SET_METHOD(Class, toQObject, __set__)
#define DECLARE_BOOLEAN_GET_SET_METHODS(Class, __get__, __set__) \
DECLARE_BOOLEAN_GET_METHOD(Class, __get__) \
DECLARE_BOOLEAN_SET_METHOD(Class, __set__)
#define DECLARE_NUMBER_GET_SET_METHODS(Class, __get__, __set__) \
DECLARE_NUMBER_GET_METHOD(Class, __get__) \
DECLARE_NUMBER_SET_METHOD(Class, __set__)
#define DECLARE_INT_GET_SET_METHODS(Class, __get__, __set__) \
DECLARE_INT_GET_METHOD(Class, __get__) \
DECLARE_INT_SET_METHOD(Class, __set__)
#define DECLARE_STRING_GET_SET_METHODS(Class, __get__, __set__) \
DECLARE_STRING_GET_METHOD(Class, __get__) \
DECLARE_STRING_SET_METHOD(Class, __set__)
#define DECLARE_QOBJECT_GET_SET_METHODS(Class, __get__, __set__) \
DECLARE_QOBJECT_GET_METHOD(Class, __get__) \
DECLARE_QOBJECT_SET_METHOD(Class, __set__)
#define DECLARE_VOID_METHOD(Class, __fun__) \
BEGIN_DECLARE_METHOD(Class, __fun__) { \
self->__fun__(); \
return eng->undefinedValue(); \
} END_DECLARE_METHOD
#define DECLARE_VOID_NUMBER_METHOD(Class, __fun__) \
BEGIN_DECLARE_METHOD(Class, __fun__) { \
self->__fun__(ctx->argument(0).toNumber()); \
return eng->undefinedValue(); \
} END_DECLARE_METHOD
#define DECLARE_VOID_NUMBER_NUMBER_METHOD(Class, __fun__) \
BEGIN_DECLARE_METHOD(Class, __fun__) { \
self->__fun__(ctx->argument(0).toNumber(), ctx->argument(1).toNumber()); \
return eng->undefinedValue(); \
} END_DECLARE_METHOD
#define DECLARE_VOID_QUAD_NUMBER_METHOD(Class, __fun__) \
BEGIN_DECLARE_METHOD(Class, __fun__) { \
self->__fun__(ctx->argument(0).toNumber(), ctx->argument(1).toNumber(), ctx->argument(2).toNumber(), ctx->argument(3).toNumber()); \
return eng->undefinedValue(); \
} END_DECLARE_METHOD
#define DECLARE_VOID_1ARG_METHOD(Class, ArgType, __fun__) \
BEGIN_DECLARE_METHOD(Class, __fun__) { \
self->__fun__(qscriptvalue_cast<ArgType>(ctx->argument(0))); \
return eng->undefinedValue(); \
} END_DECLARE_METHOD
#define DECLARE_BOOLEAN_1ARG_METHOD(Class, ArgType, __fun__) \
BEGIN_DECLARE_METHOD(Class, __fun__) { \
return QScriptValue(eng, self->__fun__(qscriptvalue_cast<ArgType>(ctx->argument(0)))); \
} END_DECLARE_METHOD
#define DECLARE_POINTER_METATYPE(T) \
Q_DECLARE_METATYPE(T*) \
Q_DECLARE_METATYPE(QScript::Pointer<T>::wrapped_pointer_type)
namespace QScript
{
enum {
UserOwnership = 1
};
template <typename T>
class Pointer : public QSharedData
{
public:
typedef T* pointer_type;
typedef QExplicitlySharedDataPointer<Pointer<T> > wrapped_pointer_type;
~Pointer()
{
if (!(m_flags & UserOwnership))
delete m_value;
}
operator T*()
{
return m_value;
}
operator const T*() const
{
return m_value;
}
static wrapped_pointer_type create(T *value, uint flags = 0)
{
return wrapped_pointer_type(new Pointer(value, flags));
}
static QScriptValue toScriptValue(QScriptEngine *engine, T* const &source)
{
if (!source)
return engine->nullValue();
return engine->newVariant(qVariantFromValue(source));
}
static void fromScriptValue(const QScriptValue &value, T* &target)
{
if (value.isVariant()) {
QVariant var = value.toVariant();
if (qVariantCanConvert<T*>(var)) {
target = qvariant_cast<T*>(var);
} else if (qVariantCanConvert<wrapped_pointer_type>(var)) {
target = qvariant_cast<wrapped_pointer_type>(var)->operator T*();
} else {
// look in prototype chain
target = 0;
int type = qMetaTypeId<T*>();
int pointerType = qMetaTypeId<wrapped_pointer_type>();
QScriptValue proto = value.prototype();
while (proto.isObject() && proto.isVariant()) {
int protoType = proto.toVariant().userType();
if ((type == protoType) || (pointerType == protoType)) {
QByteArray name = QMetaType::typeName(var.userType());
if (name.startsWith("QScript::Pointer<")) {
target = (*reinterpret_cast<wrapped_pointer_type*>(var.data()))->operator T*();
break;
} else {
target = static_cast<T*>(var.data());
break;
}
}
proto = proto.prototype();
}
}
} else if (value.isQObject()) {
QObject *qobj = value.toQObject();
QByteArray typeName = QMetaType::typeName(qMetaTypeId<T*>());
target = reinterpret_cast<T*>(qobj->qt_metacast(typeName.left(typeName.size()-1)));
} else {
target = 0;
}
}
uint flags() const
{ return m_flags; }
void setFlags(uint flags)
{ m_flags = flags; }
void unsetFlags(uint flags)
{ m_flags &= ~flags; }
protected:
Pointer(T* value, uint flags)
: m_flags(flags), m_value(value)
{}
private:
uint m_flags;
T* m_value;
};
template <typename T>
int registerPointerMetaType(
QScriptEngine *eng,
const QScriptValue &prototype = QScriptValue(),
T * /* dummy */ = 0
)
{
QScriptValue (*mf)(QScriptEngine *, T* const &) = Pointer<T>::toScriptValue;
void (*df)(const QScriptValue &, T* &) = Pointer<T>::fromScriptValue;
const int id = qMetaTypeId<T*>();
qScriptRegisterMetaType_helper(
eng, id, reinterpret_cast<QScriptEngine::MarshalFunction>(mf),
reinterpret_cast<QScriptEngine::DemarshalFunction>(df),
prototype);
eng->setDefaultPrototype(qMetaTypeId<typename Pointer<T>::wrapped_pointer_type>(), prototype);
return id;
}
inline void maybeReleaseOwnership(const QScriptValue &value)
{
if (value.isVariant()) {
QVariant var = value.toVariant();
QByteArray name = QMetaType::typeName(var.userType());
if (name.startsWith("QScript::Pointer<"))
(*reinterpret_cast<Pointer<void*>::wrapped_pointer_type *>(var.data()))->setFlags(UserOwnership);
}
}
inline void maybeTakeOwnership(const QScriptValue &value)
{
if (value.isVariant()) {
QVariant var = value.toVariant();
QByteArray name = QMetaType::typeName(var.userType());
if (name.startsWith("QScript::Pointer<"))
(*reinterpret_cast<Pointer<void*>::wrapped_pointer_type *>(var.data()))->unsetFlags(UserOwnership);
}
}
template <class T>
inline QScriptValue wrapPointer(QScriptEngine *eng, T *ptr, uint flags = 0)
{
return eng->newVariant(qVariantFromValue(Pointer<T>::create(ptr, flags)));
}
} // namespace QScript
#ifdef QGRAPHICSITEM_H
namespace QScript {
template <class T>
inline QScriptValue wrapGVPointer(QScriptEngine *eng, T *item)
{
uint flags = item->parentItem() ? UserOwnership : 0;
return wrapPointer<T>(eng, item, flags);
}
} // namespace QScript
#endif // QGRAPHICSITEM_H
#endif // QTSCRIPTEXTENSIONS_GLOBAL_H

View File

@ -0,0 +1,77 @@
/*
* Copyright 2007 Richard J. Moore <rich@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 BIND_DATAENGINE_H
#define BIND_DATAENGINE_H
#include <QtScript/QtScript>
#include <KDebug>
#include <Plasma/DataEngine>
#include <Plasma/Service>
#include <Plasma/ServiceJob>
using namespace Plasma;
Q_DECLARE_METATYPE(DataEngine*)
Q_DECLARE_METATYPE(Service*)
Q_DECLARE_METATYPE(ServiceJob*)
Q_DECLARE_METATYPE(QVariant)
Q_DECLARE_METATYPE(DataEngine::Dict)
Q_DECLARE_METATYPE(DataEngine::Data)
template <class M>
QScriptValue qScriptValueFromMap(QScriptEngine *eng, const M &map)
{
kDebug() << "qScriptValueFromMap called";
QScriptValue obj = eng->newObject();
typename M::const_iterator begin = map.constBegin();
typename M::const_iterator end = map.constEnd();
typename M::const_iterator it;
for (it = begin; it != end; ++it)
obj.setProperty(it.key(), qScriptValueFromValue(eng, it.value()));
return obj;
}
template <class M>
void qScriptValueToMap(const QScriptValue &value, M &map)
{
QScriptValueIterator it(value);
while (it.hasNext()) {
it.next();
map[it.name()] = qscriptvalue_cast<typename M::mapped_type>(it.value());
}
}
template<typename T>
int qScriptRegisterMapMetaType(
QScriptEngine *engine,
const QScriptValue &prototype = QScriptValue()
#ifndef qdoc
, T * /* dummy */ = 0
#endif
)
{
return qScriptRegisterMetaType<T>(engine, qScriptValueFromMap,
qScriptValueToMap, prototype);
}
#endif // BIND_DATAENGINE_H

View File

@ -0,0 +1,150 @@
/*
* Copyright 2008 Richard J. Moore <rich@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 "javascriptrunner.h"
#include <QScriptEngine>
#include <QFile>
#include <Plasma/AbstractRunner>
#include <Plasma/QueryMatch>
typedef const Plasma::RunnerContext* ConstRunnerContextStar;
typedef const Plasma::QueryMatch* ConstSearchMatchStar;
Q_DECLARE_METATYPE(Plasma::QueryMatch*)
Q_DECLARE_METATYPE(Plasma::RunnerContext*)
Q_DECLARE_METATYPE(ConstRunnerContextStar)
Q_DECLARE_METATYPE(ConstSearchMatchStar)
JavaScriptRunner::JavaScriptRunner(QObject *parent, const QVariantList &args)
: RunnerScript(parent)
{
m_engine = new QScriptEngine(this);
importExtensions();
}
JavaScriptRunner::~JavaScriptRunner()
{
}
Plasma::AbstractRunner* JavaScriptRunner::runner() const
{
return RunnerScript::runner();
}
bool JavaScriptRunner::init()
{
setupObjects();
QFile file(mainScript());
if (!file.open(QIODevice::ReadOnly | QIODevice::Text) ) {
kWarning() << "Unable to load script file";
return false;
}
QString script = file.readAll();
kDebug() << "Script says" << script;
m_engine->evaluate(script);
if (m_engine->hasUncaughtException()) {
reportError();
return false;
}
return true;
}
void JavaScriptRunner::match(Plasma::RunnerContext *search)
{
QScriptValue fun = m_self.property("match");
if (!fun.isFunction()) {
kDebug() << "Script: match is not a function, " << fun.toString();
return;
}
QScriptValueList args;
args << m_engine->toScriptValue(search);
QScriptContext *ctx = m_engine->pushContext();
ctx->setActivationObject(m_self);
fun.call(m_self, args);
m_engine->popContext();
if (m_engine->hasUncaughtException()) {
reportError();
}
}
void JavaScriptRunner::exec(const Plasma::RunnerContext *search, const Plasma::QueryMatch *action)
{
QScriptValue fun = m_self.property("exec");
if (!fun.isFunction()) {
kDebug() << "Script: exec is not a function, " << fun.toString();
return;
}
QScriptValueList args;
args << m_engine->toScriptValue(search);
args << m_engine->toScriptValue(action);
QScriptContext *ctx = m_engine->pushContext();
ctx->setActivationObject(m_self);
fun.call(m_self, args);
m_engine->popContext();
if (m_engine->hasUncaughtException()) {
reportError();
}
}
void JavaScriptRunner::setupObjects()
{
QScriptValue global = m_engine->globalObject();
// Expose the runner
m_self = m_engine->newQObject(this);
m_self.setScope(global);
global.setProperty("runner", m_self);
}
void JavaScriptRunner::importExtensions()
{
QStringList extensions;
//extensions << "qt.core" << "qt.gui" << "qt.svg" << "qt.xml" << "org.kde.plasma";
//extensions << "qt.core" << "qt.gui" << "qt.xml";
foreach (const QString &ext, extensions) {
kDebug() << "importing " << ext << "...";
QScriptValue ret = m_engine->importExtension(ext);
if (ret.isError()) {
kDebug() << "failed to import extension" << ext << ":" << ret.toString();
}
}
kDebug() << "done importing extensions.";
}
void JavaScriptRunner::reportError()
{
kDebug() << "Error: " << m_engine->uncaughtException().toString()
<< " at line " << m_engine->uncaughtExceptionLineNumber() << endl;
kDebug() << m_engine->uncaughtExceptionBacktrace();
}
#include "javascriptrunner.moc"

View File

@ -0,0 +1,61 @@
// -*- c++ -*-
/*
* Copyright 2008 Richard J. Moore <rich@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 RUNNERSCRIPTQSCRIPT_H
#define RUNNERSCRIPTQSCRIPT_H
#include <QScriptValue>
#include <Plasma/RunnerScript>
class QScriptEngine;
class JavaScriptRunner : public Plasma::RunnerScript
{
Q_OBJECT
public:
JavaScriptRunner(QObject *parent, const QVariantList &args);
~JavaScriptRunner();
bool init();
/** Reimplemented to add Q_INVOKABLE. */
Q_INVOKABLE Plasma::AbstractRunner* runner() const;
/** Reimplemented to forward to script. */
void match(Plasma::RunnerContext *search);
/** Reimplemented to forward to script. */
void exec(const Plasma::RunnerContext *search, const Plasma::QueryMatch *action);
protected:
void setupObjects();
void importExtensions();
void reportError();
private:
QScriptEngine *m_engine;
QScriptValue m_self;
};
K_EXPORT_PLASMA_RUNNERSCRIPTENGINE(qscriptrunner, JavaScriptRunner)
#endif // RUNNERSCRIPTQSCRIPT_H

View File

@ -0,0 +1,122 @@
[Desktop Entry]
Name=JavaScript Widget
Name[ar]=ودجة جافا سكربت
Name[be@latin]=Widžet JavaScript
Name[bg]=Джаджа JavaScript
Name[ca]=Estri del JavaScript
Name[ca@valencia]=Estri del JavaScript
Name[csb]=Interfejs JavaScript
Name[da]=JavaScript-widget
Name[de]=JavaScript-Programm
Name[el]=Συστατικό JavaScript
Name[eo]=Ĝavaskripta fenestraĵo
Name[es]=Elemento gráfico javascript
Name[et]=JavaScripti vidin
Name[eu]=JavaScript trepeta
Name[fi]=JavaScript-Plasmoid
Name[fr]=Plasmoïde JavaScript
Name[fy]=JavaSkript Widget
Name[ga]=Giuirléid JavaScript
Name[gl]=Widget de JavaScript
Name[gu]=િ િ
Name[hi]=ि ि
Name[hne]=ि ि
Name[hu]=JavaScript-objektum
Name[is]=JavaScript græja
Name[it]=Oggetto JavaScript
Name[ja]=JavaScript
Name[kk]=JavaScript интерфейс бөлшегі
Name[km]= JavaScript
Name[kn]= ಿಿ ಿ (ಿ)
Name[ko]=
Name[ku]=Amîra JavaScriptê
Name[lt]=JavaScript valdiklis
Name[lv]=JavaScript sīkrīks
Name[ml]=ി ി
Name[mr]=ि ि
Name[nb]=JavaScript-skjermelement
Name[nds]=JavaScript-Finster
Name[nl]=JavaScript-widget
Name[nn]=JavaScript-element
Name[or]=JavaScript ି
Name[pa]=-ਿ ਿ
Name[pl]=Element interfejsu w JavaScript
Name[pt]=Elemento de JavaScript
Name[pt_BR]=Widget JavaScript
Name[ro]=Miniaplicație JavaScript
Name[ru]=Виджет на языке JavaScript
Name[si]=Python
Name[sl]=Gradnik v JavaScriptu
Name[sr]=јаваскриптни виџет
Name[sr@latin]=javascript vidžet
Name[sv]=Grafisk Javascript-komponent
Name[te]=ి ి
Name[tg]=Видҷети JavaScript
Name[th]=
Name[tr]=JavaScript Programcığı
Name[uk]=Віджет JavaScript
Name[x-test]=xxJavaScript Widgetxx
Name[zh_CN]=JavaScript
Name[zh_TW]=JavaScript
Comment=Native Plasma widget written in JavaScript
Comment[ar]=ودجة بلازما أصلية كتبت بجافا سكربت
Comment[be@latin]=Widžet systemy Plasma, napisany ŭ movie JavaScript
Comment[bg]=Оригинална джаджа за Plasma, написана с JavaScript
Comment[ca]=Estri nadiu del Plasma escrit en JavaScript
Comment[ca@valencia]=Estri nadiu del Plasma escrit en JavaScript
Comment[cs]=Nativní Plasma widget napsaný v JavaScriptu
Comment[da]=Native Plasma-widget skrevet i JavaScript
Comment[de]=Echtes Plasma-Programm, geschrieben in JavaScript
Comment[el]=Εγγενές συστατικό Plasma γραμμένο σε JavaScript
Comment[eo]=Indiĝena Plasma-fenestraĵo programita per Ĝavoskripto
Comment[es]=Elemento gráfico nativo de Plasma escrito en JavaScript
Comment[et]=JavaScriptis kirjutatud Plasma vidin
Comment[fi]=Natiivi, JavaScript-pohjainen Plasmoid
Comment[fr]=Plasmoïde natif Plasma écrit en JavaScript
Comment[fy]=Plasma widget skreaun yn JavaSkript
Comment[ga]=Giuirléid dhúchasach Plasma, scríofa i JavaScript
Comment[gl]=Widget nativo de Plasma escrito en JavaScript
Comment[gu]=િ િ
Comment[hi]=ि ि ि ि
Comment[hne]=ि ि ि ि
Comment[hu]=Plasma-elem Javasciptben elkészítve
Comment[is]=Upprunabundin Plasma græja skrifuð í JavaScript
Comment[it]=Oggetto nativo di Plasma scritto in JavaScript
Comment[ja]=JavaScript Plasma
Comment[kk]=JavaScript-те жазылған Plasma интерфейс бөлшегі
Comment[km]= JavaScript
Comment[kn]= ಿ ಿ ಿ ಿ (ಿ)
Comment[ko]= Plasma
Comment[lt]=Nuosavas Plasma valdiklis parašytas JavaScript kalba
Comment[lv]=Plasma sīkrīks, rakstīts JavaScript
Comment[ml]=ിി ിിി ി
Comment[mr]=ि ि ि
Comment[nb]=Plasmaelement for dette systemet, skrevet i JavaScript
Comment[nds]=En orginaal Plasmaelement, schreven in JavaScript
Comment[nl]=Plasma-widget geschreven in JavaScript
Comment[nn]=Plasma-element skriven i JavaScript
Comment[or]=JavaScript ିି ି
Comment[pa]=-ਿ ਿ ਿ ਿ ਿ
Comment[pl]=Element interfejsu Plazmy napisany w JavaScript
Comment[pt]=Elemento nativo do Plasma feito em JavaScript
Comment[pt_BR]=Widget do Plasma nativo escrito em JavaScript
Comment[ro]=Miniaplicație Plasma scrisă în JavaScript
Comment[ru]=Виджет Plasma, написанный на языке JavaScript
Comment[sk]=Natívny plasma widget napísaný v JavaScripte
Comment[sl]=Pravi gradnik za Plasmo, ki je napisan v JavaScriptu
Comment[sr]=Самосвојни плазма виџет написан у јаваскрипту
Comment[sr@latin]=Samosvojni plasma vidžet napisan u JavaScriptu
Comment[sv]=Inbyggd grafisk Plasma-komponent skriven i Javascript
Comment[te]=ి ి ి ి
Comment[th]=
Comment[tr]=JavaScript ile yazılmış gerçek Plasma Programcığı
Comment[uk]=Віджет Плазми, написаний на JavaScript
Comment[x-test]=xxNative Plasma widget written in JavaScriptxx
Comment[zh_CN]=使 JavaScript Plasma
Comment[zh_TW]= JavaScript Plasma
X-KDE-ServiceTypes=Plasma/ScriptEngine
Type=Service
Icon=text-x-script
X-KDE-Library=plasma_appletscript_simple_javascript
X-Plasma-API=javascript
X-Plasma-ComponentTypes=Applet

View File

@ -0,0 +1,123 @@
[Desktop Entry]
Name=JavaScript Runner
Name[ar]=مشغل جافا سكربت
Name[be@latin]=Uklučeńnie JavaScript
Name[bg]=Изпълнение на JavaScript
Name[ca]=Executador de JavaScript
Name[ca@valencia]=Executador de JavaScript
Name[cs]=Spouštěč JavaScriptu
Name[csb]=Mòtór JavaScript
Name[da]=JavaScript-runner
Name[de]=JavaScript-Ausführung
Name[el]=Εκτελεστής JavaScript
Name[eo]=Ĝavaskripta ruligilo
Name[es]=Motor de javascript
Name[et]=JavaScripti käivitaja
Name[eu]=JavaScript abiarazlea
Name[fr]=Lanceur JavaScript
Name[fy]=JavaSkript rinner
Name[ga]=Feidhmitheoir JavaScript
Name[gl]=Executor de JavaScript
Name[gu]=િ
Name[hi]=ि
Name[hne]=ि
Name[hu]=JavaScript-indító
Name[is]=JavaScript keyrari
Name[it]=Esecutore JavaScript
Name[kk]=JavaScript жеккіші
Name[km]= JavaScript
Name[kn]= ಿಿ (ಿ)
Name[ko]=
Name[ku]=Xebatkara JavaScriptê
Name[lt]=JavaScript bėgtukas
Name[lv]=JavaScript darbinātājs
Name[ml]=ി
Name[mr]=ि
Name[nb]=JavaScript-kjører
Name[nds]=JavaScript-Dreger
Name[nl]=JavaScript-runner
Name[nn]=JavaScript-køyrar
Name[or]=JavaScript
Name[pa]=-ਿ
Name[pl]=Silnik JavaScript
Name[pt]=Execução de JavaScript
Name[pt_BR]=Mecanismo JavaScript
Name[ro]=Executor JavaScript
Name[si]=Python
Name[sk]=JavaScript bežec
Name[sl]=Zaganjalnik javascripta
Name[sr]=јаваскриптни извођач
Name[sr@latin]=javascript izvođač
Name[sv]=Kör Javascript
Name[te]=ి ి
Name[tg]=Иҷрогари JavaScript
Name[th]=
Name[tr]=JavaScript Çalıştırıcı
Name[uk]=Механізм запуску JavaScript
Name[x-test]=xxJavaScript Runnerxx
Name[zh_CN]=JavaScript
Name[zh_TW]=JavaScript
Comment=JavaScript Runner
Comment[ar]=مشغل جافا سكربت
Comment[be@latin]=Uklučeńnie JavaScript.
Comment[bg]=Изпълнение на JavaScript
Comment[ca]=Executador de JavaScript
Comment[ca@valencia]=Executador de JavaScript
Comment[cs]=Spouštěč JavaScriptu
Comment[csb]=Zrëszôcz JavaScript
Comment[da]=JavaScript-runner
Comment[de]=JavaScript-Ausführung
Comment[el]=Εκτελεστής JavaScript
Comment[eo]=Ĝavaskripta ruligilo
Comment[es]=Motor de javascript
Comment[et]=JavaScripti käivitaja
Comment[eu]=JavaScript abiarazlea
Comment[fr]=Lanceur JavaScript
Comment[fy]=JavaSkript rinner
Comment[ga]=Feidhmitheoir JavaScript
Comment[gl]=Executor de JavaScript
Comment[gu]=િ
Comment[hi]=ि
Comment[hne]=ि
Comment[hu]=JavaScript-indító
Comment[is]=JavaScript keyrari
Comment[it]=Esecutore JavaScript
Comment[kk]=JavaScript жеккіші
Comment[km]= JavaScript
Comment[kn]= ಿಿ (ಿ)
Comment[ko]=
Comment[ku]=Xebatkara JavaScriptê
Comment[lt]=JavaScript bėgtukas
Comment[lv]=JavaScript darbinātājs
Comment[ml]=ി
Comment[mr]=ि
Comment[nb]=JavaScript-kjører
Comment[nds]=JavaScript-Dreger
Comment[nl]=JavaScript-runner
Comment[nn]=JavaScript-køyrar
Comment[or]=JavaScript
Comment[pa]=-ਿ
Comment[pl]=Silnik JavaScript
Comment[pt]=Execução de JavaScript
Comment[pt_BR]=Mecanismo JavaScript
Comment[ro]=Executor JavaScript
Comment[ru]=Модуль запуска, написанный на языке JavaScript
Comment[sk]=JavaScript bežec
Comment[sl]=Zaganjalnik javascripta
Comment[sr]=Јаваскриптни извођач
Comment[sr@latin]=Javascript izvođač
Comment[sv]=Kör Javascript
Comment[te]=ి ి
Comment[tg]=Иҷрогари JavaScript
Comment[th]=
Comment[tr]=JavaScript Çalıştırıcı
Comment[uk]=Механізм запуску JavaScript
Comment[x-test]=xxJavaScript Runnerxx
Comment[zh_CN]=JavaScript
Comment[zh_TW]=JavaScript
X-KDE-ServiceTypes=Plasma/ScriptEngine
Type=Service
Icon=text-x-script
X-KDE-Library=plasma_runnerscript_javascript
X-Plasma-API=javascript
X-Plasma-ComponentTypes=Runner

View File

@ -0,0 +1,413 @@
/*
* Copyright 2007 Richard J. Moore <rich@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 <QtScript/QScriptValue>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptContext>
#include <QtGui/QFont>
#include "../backportglobal.h"
Q_DECLARE_METATYPE(QFont*)
static QScriptValue ctor(QScriptContext *ctx, QScriptEngine *eng)
{
if (ctx->argumentCount() == 0)
return qScriptValueFromValue(eng, QFont());
QString family = ctx->argument(0).toString();
if (ctx->argumentCount() == 1) {
QFont *other = qscriptvalue_cast<QFont*>(ctx->argument(0));
if (other)
return qScriptValueFromValue(eng, QFont(*other));
return qScriptValueFromValue(eng, QFont(family));
}
int pointSize = ctx->argument(1).toInt32();
if (ctx->argumentCount() == 2)
return qScriptValueFromValue(eng, QFont(family, pointSize));
int weight = ctx->argument(2).toInt32();
if (ctx->argumentCount() == 3)
return qScriptValueFromValue(eng, QFont(family, pointSize, weight));
bool italic = ctx->argument(3).toBoolean();
return qScriptValueFromValue(eng, QFont(family, pointSize, weight, italic));
}
static QScriptValue bold(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, bold);
return QScriptValue(eng, self->bold());
}
static QScriptValue defaultFamily(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, defaultFamily);
return QScriptValue(eng, self->defaultFamily());
}
static QScriptValue exactMatch(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, exactMatch);
return QScriptValue(eng, self->exactMatch());
}
static QScriptValue family(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, family);
return QScriptValue(eng, self->family());
}
static QScriptValue fixedPitch(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, fixedPitch);
return QScriptValue(eng, self->fixedPitch());
}
static QScriptValue fromString(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, fromString);
return QScriptValue(eng, self->fromString(ctx->argument(0).toString()));
}
static QScriptValue handle(QScriptContext *ctx, QScriptEngine *)
{
return ctx->throwError("QFont.prototype.handle is not implemented");
}
static QScriptValue isCopyOf(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, isCopyOf);
QFont *other = qscriptvalue_cast<QFont*>(ctx->argument(0));
if (!other) {
return ctx->throwError(QScriptContext::TypeError,
"QFont.prototype.isCopyOf: argument is not a Font");
}
return QScriptValue(eng, self->isCopyOf(*other));
}
static QScriptValue italic(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, italic);
return QScriptValue(eng, self->italic());
}
static QScriptValue kerning(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, kerning);
return QScriptValue(eng, self->kerning());
}
static QScriptValue key(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, key);
return QScriptValue(eng, self->key());
}
static QScriptValue lastResortFamily(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, lastResortFamily);
return QScriptValue(eng, self->lastResortFamily());
}
static QScriptValue lastResortFont(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, lastResortFont);
return QScriptValue(eng, self->lastResortFont());
}
static QScriptValue overline(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, overline);
return QScriptValue(eng, self->overline());
}
static QScriptValue pixelSize(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, pixelSize);
return QScriptValue(eng, self->pixelSize());
}
static QScriptValue pointSize(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, pointSize);
return QScriptValue(eng, self->pointSize());
}
static QScriptValue pointSizeF(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, pointSizeF);
return QScriptValue(eng, self->pointSizeF());
}
static QScriptValue rawMode(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, rawMode);
return QScriptValue(eng, self->rawMode());
}
static QScriptValue rawName(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, rawName);
return QScriptValue(eng, self->rawName());
}
static QScriptValue resolve(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, resolve);
QFont *other = qscriptvalue_cast<QFont*>(ctx->argument(0));
if (!other) {
return ctx->throwError(QScriptContext::TypeError,
"QFont.prototype.isCopyOf: argument is not a Font");
}
return qScriptValueFromValue(eng, self->resolve(*other));
}
static QScriptValue setBold(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setBold);
QScriptValue arg = ctx->argument(0);
self->setBold(arg.toBoolean());
return arg;
}
static QScriptValue setFamily(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setFamily);
QScriptValue arg = ctx->argument(0);
self->setFamily(arg.toString());
return arg;
}
static QScriptValue setFixedPitch(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setFixedPitch);
QScriptValue arg = ctx->argument(0);
self->setFixedPitch(arg.toBoolean());
return arg;
}
static QScriptValue setItalic(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setItalic);
QScriptValue arg = ctx->argument(0);
self->setItalic(arg.toBoolean());
return arg;
}
static QScriptValue setKerning(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setKerning);
QScriptValue arg = ctx->argument(0);
self->setKerning(arg.toBoolean());
return arg;
}
static QScriptValue setOverline(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setOverline);
QScriptValue arg = ctx->argument(0);
self->setOverline(arg.toBoolean());
return arg;
}
static QScriptValue setPixelSize(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setPixelSize);
QScriptValue arg = ctx->argument(0);
self->setPixelSize(arg.toInt32());
return arg;
}
static QScriptValue setPointSize(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setPointSize);
QScriptValue arg = ctx->argument(0);
self->setPointSize(arg.toInt32());
return arg;
}
static QScriptValue setPointSizeF(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setPointSizeF);
QScriptValue arg = ctx->argument(0);
self->setPointSizeF(arg.toNumber());
return arg;
}
static QScriptValue setRawMode(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setRawMode);
QScriptValue arg = ctx->argument(0);
self->setRawMode(arg.toBoolean());
return arg;
}
static QScriptValue setRawName(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setRawName);
QScriptValue arg = ctx->argument(0);
self->setRawName(arg.toString());
return arg;
}
static QScriptValue setStretch(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setStretch);
QScriptValue arg = ctx->argument(0);
self->setStretch(arg.toInt32());
return arg;
}
static QScriptValue setStrikeOut(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setStrikeOut);
QScriptValue arg = ctx->argument(0);
self->setStrikeOut(arg.toBoolean());
return arg;
}
static QScriptValue setStyle(QScriptContext *ctx, QScriptEngine *)
{
return ctx->throwError("QFont.setStyle");
}
static QScriptValue setStyleHint(QScriptContext *ctx, QScriptEngine *)
{
return ctx->throwError("QFont.setStyleHint");
}
static QScriptValue setStyleStrategy(QScriptContext *ctx, QScriptEngine *)
{
return ctx->throwError("QFont.setStyleStrategy");
}
static QScriptValue setUnderline(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setUnderline);
QScriptValue arg = ctx->argument(0);
self->setUnderline(arg.toBoolean());
return arg;
}
static QScriptValue setWeight(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QFont, setWeight);
QScriptValue arg = ctx->argument(0);
self->setWeight(arg.toInt32());
return arg;
}
static QScriptValue stretch(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, stretch);
return QScriptValue(eng, self->stretch());
}
static QScriptValue strikeOut(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, strikeOut);
return QScriptValue(eng, self->strikeOut());
}
static QScriptValue style(QScriptContext *ctx, QScriptEngine *)
{
return ctx->throwError("QFont.prototype.style is not implemented");
}
static QScriptValue styleHint(QScriptContext *ctx, QScriptEngine *)
{
return ctx->throwError("QFont.prototype.styleHint is not implemented");
}
static QScriptValue styleStrategy(QScriptContext *ctx, QScriptEngine *)
{
return ctx->throwError("QFont.prototype.styleStrategy is not implemented");
}
static QScriptValue toString(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, toString);
return QScriptValue(eng, self->toString());
}
static QScriptValue underline(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, underline);
return QScriptValue(eng, self->underline());
}
static QScriptValue weight(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QFont, weight);
return QScriptValue(eng, self->weight());
}
QScriptValue constructFontClass(QScriptEngine *eng)
{
QScriptValue proto = qScriptValueFromValue(eng, QFont());
QScriptValue::PropertyFlags getter = QScriptValue::PropertyGetter;
QScriptValue::PropertyFlags setter = QScriptValue::PropertySetter;
proto.setProperty("bold", eng->newFunction(bold), getter);
proto.setProperty("defaultFamily", eng->newFunction(defaultFamily));
proto.setProperty("exactMatch", eng->newFunction(exactMatch));
proto.setProperty("family", eng->newFunction(family), getter);
proto.setProperty("fixedPitch", eng->newFunction(fixedPitch), getter);
proto.setProperty("fromString", eng->newFunction(fromString));
proto.setProperty("handle", eng->newFunction(handle));
proto.setProperty("isCopyOf", eng->newFunction(isCopyOf));
proto.setProperty("italic", eng->newFunction(italic), getter);
proto.setProperty("kerning", eng->newFunction(kerning), getter);
proto.setProperty("key", eng->newFunction(key), getter);
proto.setProperty("lastResortFamily", eng->newFunction(lastResortFamily));
proto.setProperty("lastResortFont", eng->newFunction(lastResortFont));
proto.setProperty("overline", eng->newFunction(overline), getter);
proto.setProperty("pixelSize", eng->newFunction(pixelSize), getter);
proto.setProperty("pointSize", eng->newFunction(pointSize), getter);
proto.setProperty("pointSizeF", eng->newFunction(pointSizeF), getter);
proto.setProperty("rawMode", eng->newFunction(rawMode), getter);
proto.setProperty("rawName", eng->newFunction(rawName), getter);
proto.setProperty("resolve", eng->newFunction(resolve));
proto.setProperty("bold", eng->newFunction(setBold), setter);
proto.setProperty("bamily", eng->newFunction(setFamily), setter);
proto.setProperty("fixedPitch", eng->newFunction(setFixedPitch), setter);
proto.setProperty("italic", eng->newFunction(setItalic), setter);
proto.setProperty("kerning", eng->newFunction(setKerning), setter);
proto.setProperty("overline", eng->newFunction(setOverline), setter);
proto.setProperty("pixelSize", eng->newFunction(setPixelSize), setter);
proto.setProperty("pointSize", eng->newFunction(setPointSize), setter);
proto.setProperty("pointSizeF", eng->newFunction(setPointSizeF), setter);
proto.setProperty("rawMode", eng->newFunction(setRawMode), setter);
proto.setProperty("rawName", eng->newFunction(setRawName), setter);
proto.setProperty("stretch", eng->newFunction(setStretch), setter);
proto.setProperty("strikeOut", eng->newFunction(setStrikeOut), setter);
proto.setProperty("setStyle", eng->newFunction(setStyle));
proto.setProperty("setStyleHint", eng->newFunction(setStyleHint));
proto.setProperty("setStyleStrategy", eng->newFunction(setStyleStrategy));
proto.setProperty("underline", eng->newFunction(setUnderline), setter);
proto.setProperty("weight", eng->newFunction(setWeight), setter);
proto.setProperty("stretch", eng->newFunction(stretch), getter);
proto.setProperty("strikeOut", eng->newFunction(strikeOut), getter);
proto.setProperty("style", eng->newFunction(style));
proto.setProperty("styleHint", eng->newFunction(styleHint));
proto.setProperty("styleStrategy", eng->newFunction(styleStrategy));
proto.setProperty("toString", eng->newFunction(toString));
proto.setProperty("underline", eng->newFunction(underline), getter);
proto.setProperty("weight", eng->newFunction(weight), getter);
eng->setDefaultPrototype(qMetaTypeId<QFont>(), proto);
eng->setDefaultPrototype(qMetaTypeId<QFont*>(), proto);
return eng->newFunction(ctor, proto);
}

View File

@ -0,0 +1,412 @@
/*
* Copyright 2007 Richard J. Moore <rich@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 <QtScript/QScriptValue>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptContext>
#include <QtGui/QCursor>
#include <QtGui/QGraphicsItem>
#include <QtGui/QGraphicsScene>
#include "../backportglobal.h"
Q_DECLARE_METATYPE(QScript::Pointer<QGraphicsItem>::wrapped_pointer_type)
Q_DECLARE_METATYPE(QList<QGraphicsItem*>)
Q_DECLARE_METATYPE(QPainterPath)
#ifndef QT_NO_CURSOR
Q_DECLARE_METATYPE(QCursor)
#endif
Q_DECLARE_METATYPE(QGraphicsItemGroup*)
Q_DECLARE_METATYPE(QPainter*)
Q_DECLARE_METATYPE(QStyleOptionGraphicsItem*)
Q_DECLARE_METATYPE(QGraphicsPathItem*)
Q_DECLARE_METATYPE(QGraphicsRectItem*)
Q_DECLARE_METATYPE(QGraphicsEllipseItem*)
Q_DECLARE_METATYPE(QGraphicsPolygonItem*)
Q_DECLARE_METATYPE(QGraphicsLineItem*)
Q_DECLARE_METATYPE(QGraphicsPixmapItem*)
Q_DECLARE_METATYPE(QGraphicsTextItem*)
Q_DECLARE_METATYPE(QGraphicsSimpleTextItem*)
DECLARE_BOOLEAN_GET_SET_METHODS(QGraphicsItem, acceptDrops, setAcceptDrops)
DECLARE_BOOLEAN_GET_SET_METHODS(QGraphicsItem, acceptsHoverEvents, setAcceptsHoverEvents)
DECLARE_GET_METHOD(QGraphicsItem, boundingRect)
DECLARE_GET_METHOD(QGraphicsItem, children)
DECLARE_GET_METHOD(QGraphicsItem, childrenBoundingRect)
#ifndef QT_NO_CURSOR
DECLARE_GET_SET_METHODS(QGraphicsItem, QCursor, cursor, setCursor)
DECLARE_BOOLEAN_GET_METHOD(QGraphicsItem, hasCursor)
#endif
DECLARE_GET_SET_METHODS(QGraphicsItem, QGraphicsItemGroup*, group, setGroup)
DECLARE_BOOLEAN_GET_SET_METHODS(QGraphicsItem, handlesChildEvents, setHandlesChildEvents)
DECLARE_BOOLEAN_GET_METHOD(QGraphicsItem, hasFocus)
DECLARE_BOOLEAN_GET_SET_METHODS(QGraphicsItem, isEnabled, setEnabled)
DECLARE_BOOLEAN_GET_SET_METHODS(QGraphicsItem, isSelected, setSelected)
DECLARE_BOOLEAN_GET_SET_METHODS(QGraphicsItem, isVisible, setVisible)
DECLARE_GET_METHOD(QGraphicsItem, opaqueArea)
DECLARE_GET_METHOD(QGraphicsItem, pos)
DECLARE_QOBJECT_GET_METHOD(QGraphicsItem, scene)
DECLARE_GET_METHOD(QGraphicsItem, sceneBoundingRect)
DECLARE_GET_METHOD(QGraphicsItem, scenePos)
DECLARE_GET_METHOD(QGraphicsItem, sceneTransform)
DECLARE_GET_METHOD(QGraphicsItem, shape)
#ifndef QT_NO_TOOLTIP
DECLARE_STRING_GET_SET_METHODS(QGraphicsItem, toolTip, setToolTip)
#endif
DECLARE_GET_METHOD(QGraphicsItem, topLevelItem)
DECLARE_GET_SET_METHODS(QGraphicsItem, QTransform, transform, setTransform)
DECLARE_NUMBER_GET_METHOD(QGraphicsItem, type)
DECLARE_NUMBER_GET_METHOD(QGraphicsItem, x)
DECLARE_NUMBER_GET_METHOD(QGraphicsItem, y)
DECLARE_NUMBER_GET_SET_METHODS(QGraphicsItem, zValue, setZValue)
DECLARE_BOOLEAN_1ARG_METHOD(QGraphicsItem, QPointF, contains)
DECLARE_VOID_METHOD(QGraphicsItem, clearFocus)
DECLARE_VOID_METHOD(QGraphicsItem, hide)
DECLARE_BOOLEAN_1ARG_METHOD(QGraphicsItem, QGraphicsItem*, isAncestorOf)
DECLARE_BOOLEAN_1ARG_METHOD(QGraphicsItem, QGraphicsItem*, isObscuredBy)
DECLARE_VOID_NUMBER_NUMBER_METHOD(QGraphicsItem, moveBy)
DECLARE_VOID_METHOD(QGraphicsItem, resetTransform)
#ifndef QT_NO_CURSOR
DECLARE_VOID_METHOD(QGraphicsItem, unsetCursor)
#endif
DECLARE_VOID_METHOD(QGraphicsItem, show)
DECLARE_VOID_NUMBER_NUMBER_METHOD(QGraphicsItem, translate)
DECLARE_VOID_NUMBER_NUMBER_METHOD(QGraphicsItem, scale)
DECLARE_VOID_NUMBER_NUMBER_METHOD(QGraphicsItem, shear)
DECLARE_VOID_1ARG_METHOD(QGraphicsItem, QGraphicsItem*, installSceneEventFilter)
DECLARE_VOID_1ARG_METHOD(QGraphicsItem, QGraphicsItem*, removeSceneEventFilter)
DECLARE_VOID_NUMBER_METHOD(QGraphicsItem, rotate)
/////////////////////////////////////////////////////////////
static QScriptValue ctor(QScriptContext *ctx, QScriptEngine *)
{
return ctx->throwError("QGraphicsItem cannot be instantiated");
}
BEGIN_DECLARE_METHOD(QGraphicsItem, acceptedMouseButtons) {
return QScriptValue(eng, static_cast<int>(self->acceptedMouseButtons()));
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, advance) {
self->advance(ctx->argument(0).toInt32());
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, collidesWithItem) {
QGraphicsItem *other = qscriptvalue_cast<QGraphicsItem*>(ctx->argument(0));
if (!other) {
return ctx->throwError(QScriptContext::TypeError,
"QGraphicsItem.prototype.collidesWithItem: argument is not a GraphicsItem");
}
if (ctx->argument(1).isUndefined())
return QScriptValue(eng, self->collidesWithItem(other));
else
return QScriptValue(eng, self->collidesWithItem(other, static_cast<Qt::ItemSelectionMode>(ctx->argument(1).toInt32())));
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, collidesWithPath) {
QPainterPath path = qscriptvalue_cast<QPainterPath>(ctx->argument(0));
if (ctx->argument(1).isUndefined())
return QScriptValue(eng, self->collidesWithPath(path));
else
return QScriptValue(eng, self->collidesWithPath(path, static_cast<Qt::ItemSelectionMode>(ctx->argument(1).toInt32())));
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, collidingItems) {
if (ctx->argument(0).isUndefined())
return qScriptValueFromValue(eng, self->collidingItems());
else
return qScriptValueFromValue(eng, self->collidingItems(static_cast<Qt::ItemSelectionMode>(ctx->argument(0).toInt32())));
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, data) {
return eng->newVariant(self->data(ctx->argument(0).toInt32()));
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, ensureVisible) {
Q_UNUSED(eng);
return ctx->throwError("QGraphicsItem.prototype.ensureVisible is not implemented");
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, flags) {
return QScriptValue(eng, static_cast<int>(self->flags()));
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, isObscured) {
if (ctx->argumentCount() == 0) {
return QScriptValue(eng, self->isObscured());
} else if (ctx->argumentCount() > 1) {
return QScriptValue(eng, self->isObscured(ctx->argument(0).toInt32(),
ctx->argument(1).toInt32(),
ctx->argument(2).toInt32(),
ctx->argument(3).toInt32()));
} else {
return QScriptValue(eng, self->isObscured(qscriptvalue_cast<QRectF>(ctx->argument(0))));
}
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, mapFromItem) {
Q_UNUSED(eng);
return ctx->throwError("QGraphicsItem.prototype.mapFromItem is not implemented");
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, mapFromParent) {
Q_UNUSED(eng);
return ctx->throwError("QGraphicsItem.prototype.mapFromParent is not implemented");
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, mapFromScene) {
Q_UNUSED(eng);
return ctx->throwError("QGraphicsItem.prototype.mapFromScene is not implemented");
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, mapToItem) {
Q_UNUSED(eng);
return ctx->throwError("QGraphicsItem.prototype.mapToItem is not implemented");
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, mapToParent) {
Q_UNUSED(eng);
return ctx->throwError("QGraphicsItem.prototype.mapToParent is not implemented");
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, mapToScene) {
Q_UNUSED(eng);
return ctx->throwError("QGraphicsItem.prototype.mapToScene is not implemented");
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, paint) {
self->paint(qscriptvalue_cast<QPainter*>(ctx->argument(0)),
qscriptvalue_cast<QStyleOptionGraphicsItem*>(ctx->argument(1)),
qscriptvalue_cast<QWidget*>(ctx->argument(2)));
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, parentItem) {
QGraphicsItem *parent = self->parentItem();
if (!parent)
return eng->nullValue();
QScriptValue ret = qScriptValueFromValue(eng, parent);
QScriptValue proto;
switch (parent->type()) {
case 2:
proto = eng->defaultPrototype(qMetaTypeId<QGraphicsPathItem*>());
break;
case 3:
proto = eng->defaultPrototype(qMetaTypeId<QGraphicsRectItem*>());
break;
case 4:
proto = eng->defaultPrototype(qMetaTypeId<QGraphicsEllipseItem*>());
break;
case 5:
proto = eng->defaultPrototype(qMetaTypeId<QGraphicsPolygonItem*>());
break;
case 6:
proto = eng->defaultPrototype(qMetaTypeId<QGraphicsLineItem*>());
break;
case 7:
proto = eng->defaultPrototype(qMetaTypeId<QGraphicsPixmapItem*>());
break;
case 8:
proto = eng->defaultPrototype(qMetaTypeId<QGraphicsTextItem*>());
break;
case 9:
proto = eng->defaultPrototype(qMetaTypeId<QGraphicsSimpleTextItem*>());
break;
case 10:
proto = eng->defaultPrototype(qMetaTypeId<QGraphicsItemGroup*>());
break;
}
if (proto.isValid())
ret.setPrototype(proto);
return ret;
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, setAcceptedMouseButtons) {
self->setAcceptedMouseButtons(static_cast<Qt::MouseButtons>(ctx->argument(0).toInt32()));
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, setData) {
self->setData(ctx->argument(0).toInt32(), ctx->argument(1).toVariant());
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, setFlag) {
QGraphicsItem::GraphicsItemFlag flag = static_cast<QGraphicsItem::GraphicsItemFlag>(ctx->argument(0).toInt32());
if (ctx->argument(1).isUndefined())
self->setFlag(flag);
else
self->setFlag(flag, ctx->argument(1).toBoolean());
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, setFlags) {
self->setFlags(static_cast<QGraphicsItem::GraphicsItemFlags>(ctx->argument(0).toInt32()));
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, setFocus) {
if (ctx->argument(0).isUndefined())
self->setFocus();
else
self->setFocus(static_cast<Qt::FocusReason>(ctx->argument(0).toInt32()));
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, setParentItem) {
QScriptValue arg = ctx->argument(0);
QGraphicsItem *item = qscriptvalue_cast<QGraphicsItem*>(arg);
self->setParentItem(item);
if (item)
QScript::maybeReleaseOwnership(ctx->thisObject());
else if (!self->scene())
QScript::maybeTakeOwnership(ctx->thisObject());
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, setPos) {
if (ctx->argumentCount() > 1)
self->setPos(ctx->argument(0).toNumber(), ctx->argument(1).toNumber());
else
self->setPos(qscriptvalue_cast<QPointF>(ctx->argument(0)));
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, update) {
if (ctx->argumentCount() > 1) {
self->update(ctx->argument(0).toNumber(),
ctx->argument(1).toNumber(),
ctx->argument(2).toNumber(),
ctx->argument(3).toNumber());
} else {
self->update(qscriptvalue_cast<QRectF>(ctx->argument(0)));
}
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, toString) {
return QScriptValue(eng, "QGraphicsItem");
} END_DECLARE_METHOD
/////////////////////////////////////////////////////////////
class PrototypeGraphicsItem : public QGraphicsItem
{
public:
PrototypeGraphicsItem()
{ }
QRectF boundingRect() const
{ return QRectF(); }
void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *)
{ }
};
QScriptValue constructGraphicsItemClass(QScriptEngine *eng)
{
QScriptValue proto = QScript::wrapGVPointer<QGraphicsItem>(eng, new PrototypeGraphicsItem());
ADD_GET_SET_METHODS(proto, acceptDrops, setAcceptDrops);
ADD_GET_SET_METHODS(proto, acceptsHoverEvents, setAcceptsHoverEvents);
ADD_GET_METHOD(proto, boundingRect);
ADD_GET_METHOD(proto, children);
ADD_GET_METHOD(proto, childrenBoundingRect);
#ifndef QT_NO_CURSOR
ADD_GET_SET_METHODS(proto, cursor, setCursor);
ADD_GET_METHOD(proto, hasCursor);
#endif
ADD_GET_SET_METHODS(proto, group, setGroup);
ADD_GET_SET_METHODS(proto, handlesChildEvents, setHandlesChildEvents);
ADD_GET_METHOD(proto, hasFocus);
ADD_GET_SET_METHODS(proto, isEnabled, setEnabled);
ADD_GET_SET_METHODS(proto, isSelected, setSelected);
ADD_GET_SET_METHODS(proto, isVisible, setVisible);
ADD_GET_METHOD(proto, opaqueArea);
ADD_GET_METHOD(proto, pos);
ADD_GET_METHOD(proto, scene);
ADD_GET_METHOD(proto, sceneBoundingRect);
ADD_GET_METHOD(proto, scenePos);
ADD_GET_METHOD(proto, sceneTransform);
ADD_GET_METHOD(proto, shape);
#ifndef QT_NO_TOOLTIP
ADD_GET_SET_METHODS(proto, toolTip, setToolTip);
#endif
ADD_GET_METHOD(proto, topLevelItem);
ADD_GET_SET_METHODS(proto, transform, setTransform);
ADD_GET_METHOD(proto, type);
ADD_GET_METHOD(proto, x);
ADD_GET_METHOD(proto, y);
ADD_GET_SET_METHODS(proto, zValue, setZValue);
ADD_METHOD(proto, acceptedMouseButtons);
ADD_METHOD(proto, advance);
ADD_METHOD(proto, clearFocus);
ADD_METHOD(proto, collidesWithItem);
ADD_METHOD(proto, collidesWithPath);
ADD_METHOD(proto, collidingItems);
ADD_METHOD(proto, contains);
ADD_METHOD(proto, data);
ADD_METHOD(proto, ensureVisible);
ADD_METHOD(proto, flags);
ADD_METHOD(proto, hide);
ADD_METHOD(proto, installSceneEventFilter);
ADD_METHOD(proto, isAncestorOf);
ADD_METHOD(proto, isObscured);
ADD_METHOD(proto, isObscuredBy);
ADD_METHOD(proto, mapFromItem);
ADD_METHOD(proto, mapFromParent);
ADD_METHOD(proto, mapFromScene);
ADD_METHOD(proto, mapToItem);
ADD_METHOD(proto, mapToParent);
ADD_METHOD(proto, mapToScene);
ADD_METHOD(proto, moveBy);
ADD_METHOD(proto, paint);
ADD_METHOD(proto, parentItem);
ADD_METHOD(proto, removeSceneEventFilter);
ADD_METHOD(proto, resetTransform);
ADD_METHOD(proto, rotate);
ADD_METHOD(proto, scale);
ADD_METHOD(proto, setAcceptedMouseButtons);
ADD_METHOD(proto, setData);
ADD_METHOD(proto, setFlag);
ADD_METHOD(proto, setFlags);
ADD_METHOD(proto, setFocus);
ADD_METHOD(proto, setParentItem);
ADD_METHOD(proto, setPos);
ADD_METHOD(proto, shear);
ADD_METHOD(proto, show);
ADD_METHOD(proto, toString);
ADD_METHOD(proto, translate);
#ifndef QT_NO_CURSOR
ADD_METHOD(proto, unsetCursor);
#endif
ADD_METHOD(proto, update);
QScript::registerPointerMetaType<QGraphicsItem>(eng, proto);
QScriptValue ctorFun = eng->newFunction(ctor, proto);
ADD_ENUM_VALUE(ctorFun, QGraphicsItem, ItemIsMovable);
ADD_ENUM_VALUE(ctorFun, QGraphicsItem, ItemIsSelectable);
ADD_ENUM_VALUE(ctorFun, QGraphicsItem, ItemIsFocusable);
ADD_ENUM_VALUE(ctorFun, QGraphicsItem, ItemClipsToShape);
ADD_ENUM_VALUE(ctorFun, QGraphicsItem, ItemClipsChildrenToShape);
ADD_ENUM_VALUE(ctorFun, QGraphicsItem, ItemIgnoresTransformations);
return ctorFun;
}

View File

@ -0,0 +1,185 @@
/*
* Copyright 2007 Richard J. Moore <rich@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 <QtScript/QScriptValue>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptContext>
#include <QtGui/QGraphicsWidget>
#include <QtGui/QGraphicsGridLayout>
#include <QtGui/QGraphicsLinearLayout>
#include <Plasma/Applet>
#include "../backportglobal.h"
#include "../appletinterface.h"
Q_DECLARE_METATYPE(QScript::Pointer<QGraphicsItem>::wrapped_pointer_type)
Q_DECLARE_METATYPE(QGraphicsWidget*)
Q_DECLARE_METATYPE(QGraphicsGridLayout*)
Q_DECLARE_METATYPE(QGraphicsLayoutItem*)
DECLARE_POINTER_METATYPE(QGraphicsLinearLayout)
DECLARE_VOID_NUMBER_METHOD(QGraphicsLinearLayout, removeAt)
DECLARE_VOID_NUMBER_METHOD(QGraphicsLinearLayout, addStretch)
DECLARE_VOID_NUMBER_NUMBER_METHOD(QGraphicsLinearLayout, insertStretch)
DECLARE_VOID_NUMBER_NUMBER_METHOD(QGraphicsLinearLayout, setItemSpacing)
DECLARE_VOID_QUAD_NUMBER_METHOD(QGraphicsLinearLayout, setContentsMargins)
DECLARE_NUMBER_GET_SET_METHODS(QGraphicsLinearLayout, spacing, setSpacing)
/////////////////////////////////////////////////////////////
QGraphicsLayoutItem *layoutItem(QScriptContext *ctx, int index = 0)
{
QGraphicsLayoutItem *item = qscriptvalue_cast<QGraphicsWidget*>(ctx->argument(index));
if (!item) {
item = qscriptvalue_cast<QGraphicsLinearLayout*>(ctx->argument(index));
}
if (!item) {
item = qscriptvalue_cast<QGraphicsGridLayout*>(ctx->argument(index));
}
QObject *appletObject = ctx->argument(index).toQObject();
if (appletObject) {
AppletInterface *interface = qobject_cast<AppletInterface*>(appletObject);
if (interface) {
item = interface->applet();
}
}
return item;
}
static QScriptValue ctor(QScriptContext *ctx, QScriptEngine *eng)
{
if (ctx->argumentCount() == 0) {
return ctx->throwError(i18n("LinearLayout requires a parent"));
}
QGraphicsLayoutItem *parent = layoutItem(ctx);
if (!parent) {
return ctx->throwError(i18n("The parent must be a QGraphicsLayoutItem"));
}
return qScriptValueFromValue(eng, new QGraphicsLinearLayout(parent));
}
BEGIN_DECLARE_METHOD(QGraphicsLinearLayout, orientation) {
return QScriptValue(eng, static_cast<int>(self->orientation()));
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsLinearLayout, setOrientation) {
self->setOrientation(static_cast<Qt::Orientation>(ctx->argument(0).toInt32()));
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsLinearLayout, setAlignment) {
QGraphicsLayoutItem *item = layoutItem(ctx);
if (!item) {
return eng->undefinedValue();
}
self->setAlignment(item, static_cast<Qt::Alignment>(ctx->argument(1).toInt32()));
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsLinearLayout, insertItem) {
QGraphicsLayoutItem *item = layoutItem(ctx, 1);
if (!item) {
return eng->undefinedValue();
}
self->insertItem(ctx->argument(0).toInt32(), item);
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsLinearLayout, removeItem) {
QGraphicsLayoutItem *item = layoutItem(ctx);
if (!item) {
return eng->undefinedValue();
}
self->removeItem(item);
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsLinearLayout, setStretchFactor) {
QGraphicsLayoutItem *item = ctx->argument(0).toVariant().value<QGraphicsLayoutItem*>();
if (!item) {
return eng->undefinedValue();
}
self->setStretchFactor(item, static_cast<Qt::Orientation>(ctx->argument(1).toInt32()));
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsLinearLayout, addItem) {
QGraphicsLayoutItem *item = layoutItem(ctx);
if (!item) {
return ctx->throwError(QScriptContext::TypeError,
"QGraphicsLinearLayout.prototype.addItem: argument is not a GraphicsLayoutItem");
}
self->addItem(item);
return eng->undefinedValue();
} END_DECLARE_METHOD
BEGIN_DECLARE_METHOD(QGraphicsItem, toString) {
return QScriptValue(eng, "QGraphicsLinearLayout");
} END_DECLARE_METHOD
/////////////////////////////////////////////////////////////
class PrototypeLinearLayout : public QGraphicsLinearLayout
{
public:
PrototypeLinearLayout()
{ }
};
QScriptValue constructLinearLayoutClass(QScriptEngine *eng)
{
// QScriptValue proto = QScript::wrapGVPointer<QGraphicsLinearLayout>(eng, new QGraphicsLinearLayout(), );
QScriptValue proto = QScript::wrapPointer<QGraphicsLinearLayout>(eng, new QGraphicsLinearLayout(), QScript::UserOwnership);
ADD_GET_SET_METHODS(proto, spacing, setSpacing);
ADD_GET_SET_METHODS(proto, orientation, setOrientation);
ADD_METHOD(proto, removeAt);
ADD_METHOD(proto, addStretch);
ADD_METHOD(proto, setStretchFactor);
ADD_METHOD(proto, setAlignment);
ADD_METHOD(proto, insertStretch);
ADD_METHOD(proto, setItemSpacing);
ADD_METHOD(proto, setContentsMargins);
ADD_METHOD(proto, addItem);
ADD_METHOD(proto, removeItem);
ADD_METHOD(proto, insertItem);
ADD_METHOD(proto, toString);
QScript::registerPointerMetaType<QGraphicsLinearLayout>(eng, proto);
QScriptValue ctorFun = eng->newFunction(ctor, proto);
//ADD_ENUM_VALUE(ctorFun, QGraphicsItem, ItemIsMovable);
return ctorFun;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,97 @@
/*
* Copyright 2007 Richard J. Moore <rich@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 <QtScript/QScriptValue>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptContext>
#include <QtCore/QPoint>
#include "../backportglobal.h"
Q_DECLARE_METATYPE(QPoint*)
Q_DECLARE_METATYPE(QPoint)
static QScriptValue ctor(QScriptContext *ctx, QScriptEngine *eng)
{
if (ctx->argumentCount() == 2)
{
int x = ctx->argument(0).toInt32();
int y = ctx->argument(1).toInt32();
return qScriptValueFromValue(eng, QPoint(x, y));
}
return qScriptValueFromValue(eng, QPoint());
}
static QScriptValue isNull(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QPoint, isNull);
return QScriptValue(eng, self->isNull());
}
static QScriptValue manhattanLength(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QPoint, manhattanLength);
return QScriptValue(eng, self->manhattanLength());
}
static QScriptValue x(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QPoint, x);
return QScriptValue(eng, self->x());
}
static QScriptValue y(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QPoint, y);
return QScriptValue(eng, self->y());
}
static QScriptValue setX(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QPoint, setX);
int x = ctx->argument(0).toInt32();
self->setX(x);
return QScriptValue();
}
static QScriptValue setY(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QPoint, setY);
int y = ctx->argument(0).toInt32();
self->setY(y);
return QScriptValue();
}
QScriptValue constructQPointClass(QScriptEngine *eng)
{
QScriptValue proto = qScriptValueFromValue(eng, QPoint());
QScriptValue::PropertyFlags getter = QScriptValue::PropertyGetter;
QScriptValue::PropertyFlags setter = QScriptValue::PropertySetter;
proto.setProperty("isNull", eng->newFunction(isNull));
proto.setProperty("manhattanLength", eng->newFunction(manhattanLength));
proto.setProperty("x", eng->newFunction(x));
proto.setProperty("y", eng->newFunction(y));
proto.setProperty("setX", eng->newFunction(setX));
proto.setProperty("setY", eng->newFunction(setY));
eng->setDefaultPrototype(qMetaTypeId<QPoint>(), proto);
eng->setDefaultPrototype(qMetaTypeId<QPoint*>(), proto);
return eng->newFunction(ctor, proto);
}

View File

@ -0,0 +1,349 @@
/*
* Copyright 2007 Richard J. Moore <rich@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 <QtScript/QScriptValue>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptContext>
#include <QtCore/QRectF>
#include "../backportglobal.h"
Q_DECLARE_METATYPE(QRectF*)
Q_DECLARE_METATYPE(QRectF)
static QScriptValue ctor(QScriptContext *ctx, QScriptEngine *eng)
{
if (ctx->argumentCount() == 4)
{
qreal x = ctx->argument(0).toNumber();
qreal y = ctx->argument(1).toNumber();
qreal width = ctx->argument(2).toNumber();
qreal height = ctx->argument(3).toNumber();
return qScriptValueFromValue(eng, QRectF(x, y, width, height));
}
return qScriptValueFromValue(eng, QRectF());
}
static QScriptValue adjust(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, adjust);
qreal dx1 = ctx->argument(0).toNumber();
qreal dy1 = ctx->argument(1).toNumber();
qreal dx2 = ctx->argument(2).toNumber();
qreal dy2 = ctx->argument(3).toNumber();
self->adjust(dx1, dy1, dx2, dy2);
return QScriptValue();
}
static QScriptValue adjusted(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QRectF, adjusted);
qreal dx1 = ctx->argument(0).toNumber();
qreal dy1 = ctx->argument(1).toNumber();
qreal dx2 = ctx->argument(2).toNumber();
qreal dy2 = ctx->argument(3).toNumber();
QRectF tmp = self->adjusted(dx1, dy1, dx2, dy2);
return qScriptValueFromValue(eng, tmp);
}
static QScriptValue bottom(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QRectF, bottom);
return QScriptValue(eng, self->bottom());
}
static QScriptValue top(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QRectF, top);
return QScriptValue(eng, self->top());
}
static QScriptValue contains(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QRectF, contains);
qreal x = ctx->argument(0).toNumber();
qreal y = ctx->argument(1).toNumber();
return QScriptValue(eng, self->contains(x, y));
}
static QScriptValue height(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QRectF, height);
return QScriptValue(eng, self->height());
}
static QScriptValue isEmpty(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QRectF, isEmpty);
return QScriptValue(eng, self->isEmpty());
}
static QScriptValue isNull(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QRectF, isNull);
return QScriptValue(eng, self->isNull());
}
static QScriptValue isValid(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QRectF, isValid);
return QScriptValue(eng, self->isValid());
}
static QScriptValue left(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QRectF, left);
return QScriptValue(eng, self->left());
}
static QScriptValue moveBottom(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, moveBottom);
qreal bottom = ctx->argument(0).toNumber();
self->moveBottom(bottom);
return QScriptValue();
}
static QScriptValue moveLeft(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, moveLeft);
qreal left = ctx->argument(0).toNumber();
self->moveBottom(left);
return QScriptValue();
}
static QScriptValue moveRight(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, moveRight);
qreal right = ctx->argument(0).toNumber();
self->moveBottom(right);
return QScriptValue();
}
static QScriptValue moveTo(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, moveTo);
qreal x = ctx->argument(0).toNumber();
qreal y = ctx->argument(1).toNumber();
self->moveTo(x, y);
return QScriptValue();
}
static QScriptValue moveTop(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, moveTop);
qreal top = ctx->argument(0).toNumber();
self->moveTop(top);
return QScriptValue();
}
static QScriptValue right(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QRectF, right);
return QScriptValue(eng, self->right());
}
static QScriptValue setBottom(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, setBottom);
qreal bottom = ctx->argument(0).toNumber();
self->setBottom(bottom);
return QScriptValue();
}
static QScriptValue setCoords(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, setCoords);
qreal x1 = ctx->argument(0).toNumber();
qreal y1 = ctx->argument(1).toNumber();
qreal x2 = ctx->argument(2).toNumber();
qreal y2 = ctx->argument(3).toNumber();
self->setCoords(x1, y1, x2, y2);
return QScriptValue();
}
static QScriptValue setHeight(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, setHeight);
qreal height = ctx->argument(0).toNumber();
self->setHeight(height);
return QScriptValue();
}
static QScriptValue setLeft(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, setLeft);
qreal left = ctx->argument(0).toNumber();
self->setLeft(left);
return QScriptValue();
}
static QScriptValue setRect(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, setRect);
qreal x = ctx->argument(0).toNumber();
qreal y = ctx->argument(1).toNumber();
qreal width = ctx->argument(2).toNumber();
qreal height = ctx->argument(3).toNumber();
self->setRect(x, y, width, height);
return QScriptValue();
}
static QScriptValue setRight(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, setRight);
qreal right = ctx->argument(0).toNumber();
self->setRight(right);
return QScriptValue();
}
static QScriptValue setTop(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, setTop);
qreal top = ctx->argument(0).toNumber();
self->setTop(top);
return QScriptValue();
}
static QScriptValue setWidth(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, setWidth);
qreal width = ctx->argument(0).toNumber();
self->setWidth(width);
return QScriptValue();
}
static QScriptValue setX(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, setX);
qreal x = ctx->argument(0).toNumber();
self->setX(x);
return QScriptValue();
}
static QScriptValue setY(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, setY);
qreal y = ctx->argument(0).toNumber();
self->setY(y);
return QScriptValue();
}
static QScriptValue translate(QScriptContext *ctx, QScriptEngine *)
{
DECLARE_SELF(QRectF, translate);
qreal dx = ctx->argument(0).toNumber();
qreal dy = ctx->argument(1).toNumber();
self->translate(dx, dy);
return QScriptValue();
}
static QScriptValue width(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QRectF, width);
return QScriptValue(eng, self->width());
}
static QScriptValue x(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QRectF, x);
return QScriptValue(eng, self->x());
}
static QScriptValue y(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QRectF, y);
return QScriptValue(eng, self->y());
}
/* Not Implemented Yet */
// QPointF bottomLeft () const
// QPointF bottomRight () const
// QPointF center () const
// bool contains ( const QPointF & point ) const
// bool contains ( const QRectF & rectangle ) const
// void getCoords ( qreal * x1, qreal * y1, qreal * x2, qreal * y2 ) const
// void getRect ( qreal * x, qreal * y, qreal * width, qreal * height ) const
// QRectF intersected ( const QRectF & rectangle ) const
// bool intersects ( const QRectF & rectangle ) const
// void moveBottomLeft ( const QPointF & position )
// void moveBottomRight ( const QPointF & position )
// void moveCenter ( const QPointF & position )
// void moveTo ( const QPointF & position )
// void moveTopLeft ( const QPointF & position )
// void moveTopRight ( const QPointF & position )
// QRectF normalized () const
// void setBottomLeft ( const QPointF & position )
// void setBottomRight ( const QPointF & position )
// void setSize ( const QSizeF & size )
// void setTopLeft ( const QPointF & position )
// void setTopRight ( const QPointF & position )
// QSizeF size () const
// QRect toAlignedRect () const
// QRect toRect () const
// QPointF topLeft () const
// QPointF topRight () const
// void translate ( const QPointF & offset )
// QRectF translated ( qreal dx, qreal dy ) const
// QRectF translated ( const QPointF & offset ) const
// QRectF united ( const QRectF & rectangle ) const
QScriptValue constructQRectFClass(QScriptEngine *eng)
{
QScriptValue proto = qScriptValueFromValue(eng, QRectF());
QScriptValue::PropertyFlags getter = QScriptValue::PropertyGetter;
QScriptValue::PropertyFlags setter = QScriptValue::PropertySetter;
proto.setProperty("adjust", eng->newFunction(adjust));
proto.setProperty("bottom", eng->newFunction(bottom));
proto.setProperty("contains", eng->newFunction(contains));
proto.setProperty("height", eng->newFunction(height));
proto.setProperty("isEmpty", eng->newFunction(isEmpty));
proto.setProperty("isNull", eng->newFunction(isNull));
proto.setProperty("isValid", eng->newFunction(isValid));
proto.setProperty("left", eng->newFunction(left));
proto.setProperty("moveBottom", eng->newFunction(moveBottom));
proto.setProperty("moveLeft", eng->newFunction(moveLeft));
proto.setProperty("moveRight", eng->newFunction(moveRight));
proto.setProperty("moveTo", eng->newFunction(moveTo));
proto.setProperty("moveTop", eng->newFunction(moveTop));
proto.setProperty("right", eng->newFunction(right));
proto.setProperty("setBottom", eng->newFunction(setBottom));
proto.setProperty("setCoords", eng->newFunction(setCoords));
proto.setProperty("setHeight", eng->newFunction(setHeight));
proto.setProperty("setLeft", eng->newFunction(setLeft));
proto.setProperty("setRect", eng->newFunction(setRect));
proto.setProperty("setRight", eng->newFunction(setRight));
proto.setProperty("setTop", eng->newFunction(setTop));
proto.setProperty("setWidth", eng->newFunction(setWidth));
proto.setProperty("setX", eng->newFunction(setX));
proto.setProperty("setY", eng->newFunction(setY));
proto.setProperty("top", eng->newFunction(top));
proto.setProperty("translate", eng->newFunction(translate));
proto.setProperty("width", eng->newFunction(width));
proto.setProperty("x", eng->newFunction(x));
proto.setProperty("y", eng->newFunction(y));
eng->setDefaultPrototype(qMetaTypeId<QRectF>(), proto);
eng->setDefaultPrototype(qMetaTypeId<QRectF*>(), proto);
return eng->newFunction(ctor, proto);
}

View File

@ -0,0 +1,63 @@
/*
* Copyright 2007 Richard J. Moore <rich@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 <QtScript/QScriptValue>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptContext>
#include <QtCore/QSizeF>
#include "../backportglobal.h"
Q_DECLARE_METATYPE(QSizeF*)
Q_DECLARE_METATYPE(QSizeF)
static QScriptValue ctor(QScriptContext *ctx, QScriptEngine *eng)
{
if (ctx->argumentCount() == 2)
{
qreal width = ctx->argument(1).toNumber();
qreal height = ctx->argument(1).toNumber();
return qScriptValueFromValue(eng, QSizeF(width, height));
}
return qScriptValueFromValue(eng, QSizeF());
}
static QScriptValue width(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QSizeF, width);
return QScriptValue(eng, self->width());
}
static QScriptValue height(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QSizeF, height);
return QScriptValue(eng, self->height());
}
QScriptValue constructQSizeFClass(QScriptEngine *eng)
{
QScriptValue proto = qScriptValueFromValue(eng, QSizeF());
QScriptValue::PropertyFlags getter = QScriptValue::PropertyGetter;
QScriptValue::PropertyFlags setter = QScriptValue::PropertySetter;
proto.setProperty("width", eng->newFunction(width));
proto.setProperty("height", eng->newFunction(height));
return eng->newFunction(ctor, proto);
}

View File

@ -0,0 +1,52 @@
/*
* Copyright 2007 Richard J. Moore <rich@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 <QtScript/QScriptValue>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptContext>
#include <QtScript/QScriptable>
#include <QtCore/QTimer>
#include "../backportglobal.h"
Q_DECLARE_METATYPE(QTimer*)
static QScriptValue newTimer(QScriptEngine *eng, QTimer *timer)
{
return eng->newQObject(timer, QScriptEngine::AutoOwnership);
}
static QScriptValue ctor(QScriptContext *ctx, QScriptEngine *eng)
{
return newTimer(eng, new QTimer(qscriptvalue_cast<QObject*>(ctx->argument(0))));
}
static QScriptValue toString(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(QTimer, toString);
return QScriptValue(eng, QString::fromLatin1("QTimer(interval=%0)")
.arg(self->interval()));
}
QScriptValue constructTimerClass(QScriptEngine *eng)
{
QScriptValue proto = newTimer(eng, new QTimer());
ADD_METHOD(proto, toString);
eng->setDefaultPrototype(qMetaTypeId<QTimer*>(), proto);
return eng->newFunction(ctor, proto);
}

View File

@ -0,0 +1,55 @@
/*
* Copyright 2007 Richard J. Moore <rich@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 <QtScript/QScriptValue>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptContext>
#include <KUrl>
#include "../backportglobal.h"
Q_DECLARE_METATYPE(KUrl*)
static QScriptValue ctor(QScriptContext *ctx, QScriptEngine *eng)
{
if (ctx->argumentCount() == 1)
{
QString url = ctx->argument(0).toString();
return qScriptValueFromValue(eng, KUrl(url));
}
return qScriptValueFromValue(eng, KUrl());
}
static QScriptValue toString(QScriptContext *ctx, QScriptEngine *eng)
{
DECLARE_SELF(KUrl, toString);
return QScriptValue(eng, self->prettyUrl());
}
QScriptValue constructKUrlClass(QScriptEngine *eng)
{
QScriptValue proto = qScriptValueFromValue(eng, KUrl());
QScriptValue::PropertyFlags getter = QScriptValue::PropertyGetter;
QScriptValue::PropertyFlags setter = QScriptValue::PropertySetter;
proto.setProperty("toString", eng->newFunction(toString), getter);
eng->setDefaultPrototype(qMetaTypeId<KUrl>(), proto);
return eng->newFunction(ctor, proto);
}

View File

@ -0,0 +1,859 @@
/*
* Copyright 2007-2008 Richard J. Moore <rich@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 "simplejavascriptapplet.h"
#include <QScriptEngine>
#include <QFile>
#include <QUiLoader>
#include <QGraphicsLayout>
#include <QWidget>
#include <KDebug>
#include <KLocale>
#include <KStandardDirs>
#include <KConfigGroup>
#include <Plasma/Applet>
#include <Plasma/Svg>
#include <Plasma/FrameSvg>
#include <Plasma/Package>
#include <Plasma/VideoWidget>
#include "appletinterface.h"
using namespace Plasma;
#include "bind_dataengine.h"
Q_DECLARE_METATYPE(QPainter*)
Q_DECLARE_METATYPE(QStyleOptionGraphicsItem*)
Q_DECLARE_METATYPE(SimpleJavaScriptApplet*)
Q_DECLARE_METATYPE(AppletInterface*)
Q_DECLARE_METATYPE(Applet*)
Q_DECLARE_METATYPE(QGraphicsWidget*)
Q_DECLARE_METATYPE(QGraphicsLayout*)
Q_DECLARE_METATYPE(KConfigGroup)
Q_SCRIPT_DECLARE_QMETAOBJECT(AppletInterface, SimpleJavaScriptApplet*)
QScriptValue constructPainterClass(QScriptEngine *engine);
QScriptValue constructGraphicsItemClass(QScriptEngine *engine);
QScriptValue constructLinearLayoutClass(QScriptEngine *engine);
QScriptValue constructKUrlClass(QScriptEngine *engine);
QScriptValue constructTimerClass(QScriptEngine *engine);
QScriptValue constructFontClass(QScriptEngine *engine);
QScriptValue constructQRectFClass(QScriptEngine *engine);
QScriptValue constructQPointClass(QScriptEngine *engine);
QScriptValue constructQSizeFClass(QScriptEngine *engine);
//typedef VideoWidget::Control Control;
Q_DECLARE_FLAGS(Controls, VideoWidget::Control)
Q_DECLARE_METATYPE(Controls)
class DummyService : public Service
{
public:
ServiceJob *createJob(const QString &operation, QMap<QString, QVariant> &parameters)
{
Q_UNUSED(operation)
Q_UNUSED(parameters)
return 0;
}
};
/*
* Workaround the fact that QtScripts handling of variants seems a bit broken.
*/
QScriptValue variantToScriptValue(QScriptEngine *engine, QVariant var)
{
if (var.isNull()) {
return engine->nullValue();
}
switch(var.type())
{
case QVariant::Invalid:
return engine->nullValue();
case QVariant::Bool:
return QScriptValue(engine, var.toBool());
case QVariant::Date:
return engine->newDate(var.toDateTime());
case QVariant::DateTime:
return engine->newDate(var.toDateTime());
case QVariant::Double:
return QScriptValue(engine, var.toDouble());
case QVariant::Int:
case QVariant::LongLong:
return QScriptValue(engine, var.toInt());
case QVariant::String:
return QScriptValue(engine, var.toString());
case QVariant::Time: {
QDateTime t(QDate::currentDate(), var.toTime());
return engine->newDate(t);
}
case QVariant::UInt:
return QScriptValue(engine, var.toUInt());
default:
if (var.typeName() == QLatin1String("KUrl")) {
return QScriptValue(engine, var.value<KUrl>().prettyUrl());
} else if (var.typeName() == QLatin1String("QColor")) {
return QScriptValue(engine, var.value<QColor>().name());
} else if (var.typeName() == QLatin1String("QUrl")) {
return QScriptValue(engine, var.value<QUrl>().toString());
}
break;
}
return qScriptValueFromValue(engine, var);
}
QScriptValue qScriptValueFromControls(QScriptEngine *engine, const Controls &controls)
{
return QScriptValue(engine, controls);
}
void controlsFromScriptValue(const QScriptValue& obj, Controls &controls)
{
int flagValue = obj.toInteger();
//FIXME: it has to be a less ugly way to do that :)
if (flagValue&VideoWidget::Play) {
controls |= VideoWidget::Play;
}
if (flagValue&VideoWidget::Pause) {
controls |= VideoWidget::Pause;
}
if (flagValue&VideoWidget::Stop) {
controls |= VideoWidget::Stop;
}
if (flagValue&VideoWidget::PlayPause) {
controls |= VideoWidget::PlayPause;
}
if (flagValue&VideoWidget::Progress) {
controls |= VideoWidget::Progress;
}
if (flagValue&VideoWidget::Volume) {
controls |= VideoWidget::Volume;
}
if (flagValue&VideoWidget::OpenFile) {
controls |= VideoWidget::OpenFile;
}
}
QScriptValue qScriptValueFromData(QScriptEngine *engine, const DataEngine::Data &data)
{
DataEngine::Data::const_iterator begin = data.begin();
DataEngine::Data::const_iterator end = data.end();
DataEngine::Data::const_iterator it;
QScriptValue obj = engine->newObject();
for (it = begin; it != end; ++it) {
//kDebug() << "setting" << it.key() << "to" << it.value();
QString prop = it.key();
prop.replace(' ', '_');
obj.setProperty(prop, variantToScriptValue(engine, it.value()));
}
return obj;
}
QScriptValue qScriptValueFromKConfigGroup(QScriptEngine *engine, const KConfigGroup &config)
{
QScriptValue obj = engine->newObject();
if (!config.isValid()) {
return obj;
}
QMap<QString, QString> entryMap = config.entryMap();
QMap<QString, QString>::const_iterator it = entryMap.constBegin();
QMap<QString, QString>::const_iterator begin = it;
QMap<QString, QString>::const_iterator end = entryMap.constEnd();
//setting the group name
obj.setProperty("__name", QScriptValue(engine, config.name()));
//setting the key/value pairs
for (it = begin; it != end; ++it) {
//kDebug() << "setting" << it.key() << "to" << it.value();
QString prop = it.key();
prop.replace(' ', '_');
obj.setProperty(prop, variantToScriptValue(engine, it.value()));
}
return obj;
}
void kConfigGroupFromScriptValue(const QScriptValue& obj, KConfigGroup &config)
{
KConfigSkeleton *skel = new KConfigSkeleton();
config = KConfigGroup(skel->config(), obj.property("__name").toString());
QScriptValueIterator it(obj);
while (it.hasNext()) {
it.next();
//kDebug() << it.name() << "is" << it.value().toString();
if (it.name() != "__name") {
config.writeEntry(it.name(), it.value().toString());
}
}
}
void registerEnums(QScriptEngine *engine, QScriptValue &scriptValue, const QMetaObject &meta)
{
//manually create enum values. ugh
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)));
}
}
}
KSharedPtr<UiLoader> SimpleJavaScriptApplet::s_widgetLoader;
SimpleJavaScriptApplet::SimpleJavaScriptApplet(QObject *parent, const QVariantList &args)
: Plasma::AppletScript(parent)
{
Q_UNUSED(args)
// kDebug() << "Script applet launched, args" << applet()->startupArguments();
m_engine = new QScriptEngine(this);
importExtensions();
}
SimpleJavaScriptApplet::~SimpleJavaScriptApplet()
{
if (s_widgetLoader.count() == 1) {
s_widgetLoader.clear();
}
}
void SimpleJavaScriptApplet::reportError()
{
kDebug() << "Error: " << m_engine->uncaughtException().toString()
<< " at line " << m_engine->uncaughtExceptionLineNumber() << endl;
kDebug() << m_engine->uncaughtExceptionBacktrace();
}
void SimpleJavaScriptApplet::configChanged()
{
QScriptValue fun = m_self.property("configChanged");
if (!fun.isFunction()) {
kDebug() << "Script: plasmoid.configChanged is not a function, " << fun.toString();
return;
}
QScriptContext *ctx = m_engine->pushContext();
ctx->setActivationObject(m_self);
//kDebug() << "calling plasmoid";
fun.call(m_self);
m_engine->popContext();
if (m_engine->hasUncaughtException()) {
reportError();
}
}
void SimpleJavaScriptApplet::dataUpdated(const QString &name, const DataEngine::Data &data)
{
QScriptValue fun = m_self.property("dataUpdate");
if (!fun.isFunction()) {
kDebug() << "Script: dataUpdate is not a function, " << fun.toString();
return;
}
QScriptValueList args;
args << m_engine->toScriptValue(name) << m_engine->toScriptValue(data);
QScriptContext *ctx = m_engine->pushContext();
ctx->setActivationObject(m_self);
fun.call(m_self, args);
m_engine->popContext();
if (m_engine->hasUncaughtException()) {
reportError();
}
}
void SimpleJavaScriptApplet::executeAction(const QString &name)
{
callFunction("action_" + name);
/*
QScriptValue fun = m_self.property("action_" + name);
if (fun.isFunction()) {
QScriptContext *ctx = m_engine->pushContext();
ctx->setActivationObject(m_self);
fun.call(m_self);
m_engine->popContext();
if (m_engine->hasUncaughtException()) {
reportError();
}
}*/
}
void SimpleJavaScriptApplet::paintInterface(QPainter *p, const QStyleOptionGraphicsItem *option, const QRect &contentsRect)
{
Q_UNUSED(option)
Q_UNUSED(contentsRect)
//kDebug() << "paintInterface() (c++)";
QScriptValue fun = m_self.property("paintInterface");
if (!fun.isFunction()) {
//kDebug() << "Script: paintInterface is not a function, " << fun.toString();
AppletScript::paintInterface(p, option, contentsRect);
return;
}
QScriptValueList args;
args << m_engine->toScriptValue(p);
args << m_engine->toScriptValue(const_cast<QStyleOptionGraphicsItem*>(option));
args << m_engine->toScriptValue(contentsRect);
QScriptContext *ctx = m_engine->pushContext();
ctx->setActivationObject(m_self);
fun.call(m_self, args);
m_engine->popContext();
if (m_engine->hasUncaughtException()) {
reportError();
}
}
QList<QAction*> SimpleJavaScriptApplet::contextualActions()
{
return m_interface->contextualActions();
}
void SimpleJavaScriptApplet::callFunction(const QString &functionName, const QScriptValueList &args)
{
QScriptValue fun = m_self.property(functionName);
if (fun.isFunction()) {
QScriptContext *ctx = m_engine->pushContext();
ctx->setActivationObject(m_self);
fun.call(m_self, args);
m_engine->popContext();
if (m_engine->hasUncaughtException()) {
reportError();
}
}
}
void SimpleJavaScriptApplet::constraintsEvent(Plasma::Constraints constraints)
{
QString functionName;
if (constraints & Plasma::FormFactorConstraint) {
callFunction("formFactorChanged");
}
if (constraints & Plasma::LocationConstraint) {
callFunction("locationChanged");
}
if (constraints & Plasma::ContextConstraint) {
callFunction("contextChanged");
}
}
bool SimpleJavaScriptApplet::init()
{
setupObjects();
kDebug() << "ScriptName:" << applet()->name();
kDebug() << "ScriptCategory:" << applet()->category();
QFile file(mainScript());
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
kWarning() << "Unable to load script file";
return false;
}
QString script = file.readAll();
//kDebug() << "Script says" << script;
m_engine->evaluate(script);
if (m_engine->hasUncaughtException()) {
reportError();
return false;
}
return true;
}
void SimpleJavaScriptApplet::importExtensions()
{
return; // no extension, so do bother wasting cycles
/*
QStringList extensions;
//extensions << "qt.core" << "qt.gui" << "qt.svg" << "qt.xml" << "qt.plasma";
//extensions << "qt.core" << "qt.gui" << "qt.xml";
foreach (const QString &ext, extensions) {
kDebug() << "importing " << ext << "...";
QScriptValue ret = m_engine->importExtension(ext);
if (ret.isError()) {
kDebug() << "failed to import extension" << ext << ":" << ret.toString();
}
}
kDebug() << "done importing extensions.";
*/
}
void SimpleJavaScriptApplet::setupObjects()
{
QScriptValue global = m_engine->globalObject();
// Bindings for data engine
m_engine->setDefaultPrototype(qMetaTypeId<DataEngine*>(), m_engine->newQObject(new DataEngine()));
m_engine->setDefaultPrototype(qMetaTypeId<Service*>(), m_engine->newQObject(new DummyService()));
m_engine->setDefaultPrototype(qMetaTypeId<ServiceJob*>(), m_engine->newQObject(new ServiceJob(QString(), QString(), QMap<QString, QVariant>())));
global.setProperty("i18n", m_engine->newFunction(SimpleJavaScriptApplet::jsi18n));
global.setProperty("i18nc", m_engine->newFunction(SimpleJavaScriptApplet::jsi18nc));
global.setProperty("i18np", m_engine->newFunction(SimpleJavaScriptApplet::jsi18np));
global.setProperty("i18ncp", m_engine->newFunction(SimpleJavaScriptApplet::jsi18ncp));
global.setProperty("dataEngine", m_engine->newFunction(SimpleJavaScriptApplet::dataEngine));
global.setProperty("service", m_engine->newFunction(SimpleJavaScriptApplet::service));
qScriptRegisterMetaType<DataEngine::Data>(m_engine, qScriptValueFromData, 0, QScriptValue());
qScriptRegisterMetaType<KConfigGroup>(m_engine, qScriptValueFromKConfigGroup, kConfigGroupFromScriptValue, QScriptValue());
// Expose applet interface
m_interface = new AppletInterface(this);
m_self = m_engine->newQObject(m_interface);
m_self.setScope(global);
global.setProperty("plasmoid", m_self);
QScriptValue args = m_engine->newArray();
int i = 0;
foreach (const QVariant &arg, applet()->startupArguments()) {
args.setProperty(i, variantToScriptValue(arg));
++i;
}
global.setProperty("startupArguments", args);
registerEnums(m_engine, global, AppletInterface::staticMetaObject);
// Add a global loadui method for ui files
QScriptValue fun = m_engine->newFunction(SimpleJavaScriptApplet::loadui);
global.setProperty("loadui", fun);
fun = m_engine->newFunction(SimpleJavaScriptApplet::print);
global.setProperty("print", fun);
// Work around bug in 4.3.0
qMetaTypeId<QVariant>();
// Add constructors
global.setProperty("PlasmaSvg", m_engine->newFunction(SimpleJavaScriptApplet::newPlasmaSvg));
global.setProperty("PlasmaFrameSvg", m_engine->newFunction(SimpleJavaScriptApplet::newPlasmaFrameSvg));
// Add stuff from 4.4
global.setProperty("QPainter", constructPainterClass(m_engine));
global.setProperty("QGraphicsItem", constructGraphicsItemClass(m_engine));
global.setProperty("QTimer", constructTimerClass(m_engine));
global.setProperty("QFont", constructFontClass(m_engine));
global.setProperty("QRectF", constructQRectFClass(m_engine));
global.setProperty("QSizeF", constructQSizeFClass(m_engine));
global.setProperty("QPoint", constructQPointClass(m_engine));
global.setProperty("LinearLayout", constructLinearLayoutClass(m_engine));
global.setProperty("Url", constructKUrlClass(m_engine));
installWidgets(m_engine);
}
QString SimpleJavaScriptApplet::findDataResource(const QString &filename)
{
QString path("plasma-script/%1");
return KGlobal::dirs()->findResource("data", path.arg(filename));
}
void SimpleJavaScriptApplet::debug(const QString &msg)
{
kDebug() << msg;
}
#if 0
QScriptValue SimpleJavaScriptApplet::dataEngine(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1)
return context->throwError("dataEngine takes one argument");
QString dataEngine = context->argument(0).toString();
Script *self = engine->fromScriptValue<Script*>(context->thisObject());
DataEngine *data = self->dataEngine(dataEngine);
return engine->newQObject(data);
}
#endif
QScriptValue SimpleJavaScriptApplet::jsi18n(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() < 1) {
return context->throwError(i18n("i18n() takes at least one argument"));
}
KLocalizedString message = ki18n(context->argument(0).toString().toUtf8());
int numArgs = context->argumentCount();
for (int i = 1; i < numArgs; ++i) {
message.subs(context->argument(i).toString());
}
return engine->newVariant(message.toString());
}
QScriptValue SimpleJavaScriptApplet::jsi18nc(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() < 2) {
return context->throwError(i18n("i18nc() takes at least two arguments"));
}
KLocalizedString message = ki18nc(context->argument(0).toString().toUtf8(),
context->argument(1).toString().toUtf8());
int numArgs = context->argumentCount();
for (int i = 2; i < numArgs; ++i) {
message.subs(context->argument(i).toString());
}
return engine->newVariant(message.toString());
}
QScriptValue SimpleJavaScriptApplet::jsi18np(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() < 2) {
return context->throwError(i18n("i18np() takes at least two arguments"));
}
KLocalizedString message = ki18np(context->argument(0).toString().toUtf8(),
context->argument(1).toString().toUtf8());
int numArgs = context->argumentCount();
for (int i = 2; i < numArgs; ++i) {
message.subs(context->argument(i).toString());
}
return engine->newVariant(message.toString());
}
QScriptValue SimpleJavaScriptApplet::jsi18ncp(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() < 3) {
return context->throwError(i18n("i18ncp() takes at least three arguments"));
}
KLocalizedString message = ki18ncp(context->argument(0).toString().toUtf8(),
context->argument(1).toString().toUtf8(),
context->argument(2).toString().toUtf8());
int numArgs = context->argumentCount();
for (int i = 3; i < numArgs; ++i) {
message.subs(context->argument(i).toString());
}
return engine->newVariant(message.toString());
}
QScriptValue SimpleJavaScriptApplet::dataEngine(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) {
return context->throwError(i18n("dataEngine() takes one argument"));
}
QString dataEngine = context->argument(0).toString();
QScriptValue appletValue = engine->globalObject().property("plasmoid");
//kDebug() << "appletValue is " << appletValue.toString();
QObject *appletObject = appletValue.toQObject();
if (!appletObject) {
return context->throwError(i18n("Could not extract the AppletObject"));
}
AppletInterface *interface = qobject_cast<AppletInterface*>(appletObject);
if (!interface) {
return context->throwError(i18n("Could not extract the Applet"));
}
DataEngine *data = interface->dataEngine(dataEngine);
return engine->newQObject(data);
}
QScriptValue SimpleJavaScriptApplet::service(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 2) {
return context->throwError(i18n("service() takes two arguments"));
}
QString dataEngine = context->argument(0).toString();
QScriptValue appletValue = engine->globalObject().property("plasmoid");
//kDebug() << "appletValue is " << appletValue.toString();
QObject *appletObject = appletValue.toQObject();
if (!appletObject) {
return context->throwError(i18n("Could not extract the AppletObject"));
}
AppletInterface *interface = qobject_cast<AppletInterface*>(appletObject);
if (!interface) {
return context->throwError(i18n("Could not extract the Applet"));
}
DataEngine *data = interface->dataEngine(dataEngine);
QString source = context->argument(1).toString();
Service *service = data->serviceForSource(source);
//kDebug( )<< "lets try to get" << source << "from" << dataEngine;
return engine->newQObject(service);
}
QScriptValue SimpleJavaScriptApplet::loadui(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) {
return context->throwError(i18n("loadui() takes one argument"));
}
QString filename = context->argument(0).toString();
QFile f(filename);
if (!f.open(QIODevice::ReadOnly)) {
return context->throwError(i18n("Unable to open '%1'",filename));
}
QUiLoader loader;
QWidget *w = loader.load(&f);
f.close();
return engine->newQObject(w);
}
QString SimpleJavaScriptApplet::findSvg(QScriptEngine *engine, const QString &file)
{
QScriptValue appletValue = engine->globalObject().property("plasmoid");
//kDebug() << "appletValue is " << appletValue.toString();
QObject *appletObject = appletValue.toQObject();
if (!appletObject) {
return file;
}
AppletInterface *interface = qobject_cast<AppletInterface*>(appletObject);
if (!interface) {
return file;
}
QString path = interface->package()->filePath("images", file + ".svg");
if (path.isEmpty()) {
path = interface->package()->filePath("images", file + ".svgz");
if (path.isEmpty()) {
return file;
}
}
return path;
}
QScriptValue SimpleJavaScriptApplet::newPlasmaSvg(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() == 0) {
return context->throwError(i18n("Constructor takes at least 1 argument"));
}
QString filename = context->argument(0).toString();
QObject *parent = 0;
if (context->argumentCount() == 2) {
parent = qscriptvalue_cast<QObject *>(context->argument(1));
}
bool parentedToApplet = false;
if (!parent) {
QScriptValue appletValue = engine->globalObject().property("plasmoid");
//kDebug() << "appletValue is " << appletValue.toString();
QObject *appletObject = appletValue.toQObject();
if (appletObject) {
AppletInterface *interface = qobject_cast<AppletInterface*>(appletObject);
if (interface) {
parentedToApplet = true;
parent = interface->applet();
}
}
}
Svg *svg = new Svg(parent);
svg->setImagePath(parentedToApplet ? filename : findSvg(engine, filename));
return engine->newQObject(svg);
}
QScriptValue SimpleJavaScriptApplet::newPlasmaFrameSvg(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() == 0) {
return context->throwError(i18n("Constructor takes at least 1 argument"));
}
QString filename = context->argument(0).toString();
QObject *parent = 0;
if (context->argumentCount() == 2) {
parent = qscriptvalue_cast<QObject *>(context->argument(1));
}
bool parentedToApplet = false;
if (!parent) {
QScriptValue appletValue = engine->globalObject().property("plasmoid");
//kDebug() << "appletValue is " << appletValue.toString();
QObject *appletObject = appletValue.toQObject();
if (appletObject) {
AppletInterface *interface = qobject_cast<AppletInterface*>(appletObject);
if (interface) {
parentedToApplet = true;
parent = interface->applet();
}
}
}
FrameSvg *frameSvg = new FrameSvg(parent);
frameSvg->setImagePath(parentedToApplet ? filename : findSvg(engine, filename));
return engine->newQObject(frameSvg);
}
void SimpleJavaScriptApplet::installWidgets(QScriptEngine *engine)
{
QScriptValue globalObject = engine->globalObject();
if (!s_widgetLoader) {
s_widgetLoader = new UiLoader;
}
foreach (const QString &widget, s_widgetLoader->availableWidgets()) {
QScriptValue fun = engine->newFunction(createWidget);
QScriptValue name = engine->toScriptValue(widget);
fun.setProperty(QString("functionName"), name,
QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
fun.setProperty(QString("prototype"), createPrototype(engine, name.toString()));
globalObject.setProperty(widget, fun);
}
}
QScriptValue SimpleJavaScriptApplet::createWidget(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() > 1) {
return context->throwError(i18n("CreateWidget takes one argument"));
}
QGraphicsWidget *parent = 0;
if (context->argumentCount()) {
parent = qscriptvalue_cast<QGraphicsWidget*>(context->argument(0));
if (!parent) {
return context->throwError(i18n("The parent must be a QGraphicsWidget"));
}
}
if (!parent) {
QScriptValue appletValue = engine->globalObject().property("plasmoid");
//kDebug() << "appletValue is " << appletValue.toString();
QObject *appletObject = appletValue.toQObject();
if (!appletObject) {
return context->throwError(i18n("Could not extract the AppletObject"));
}
AppletInterface *interface = qobject_cast<AppletInterface*>(appletObject);
if (!interface) {
return context->throwError(i18n("Could not extract the Applet"));
}
parent = interface->applet();
}
QString self = context->callee().property("functionName").toString();
if (!s_widgetLoader) {
s_widgetLoader = new UiLoader;
}
QGraphicsWidget *w = s_widgetLoader->createWidget(self, parent);
if (!w) {
return QScriptValue();
}
QScriptValue fun = engine->newQObject(w);
fun.setPrototype(context->callee().property("prototype"));
//register enums will be accessed for instance as frame.Sunken for Frame shadow...
registerEnums(engine, fun, *w->metaObject());
//FIXME: still don't have a better approach than try to cast for every widget that could have flags..
if (qobject_cast<VideoWidget *>(w)) {
qScriptRegisterMetaType<Controls>(engine, qScriptValueFromControls, controlsFromScriptValue, QScriptValue());
}
return fun;
}
QScriptValue SimpleJavaScriptApplet::notSupported(QScriptContext *context, QScriptEngine *engine)
{
Q_UNUSED(engine)
QString message = context->callee().property("message").toString();
return context->throwError(i18n("This operation was not supported, %1", message) );
}
QScriptValue SimpleJavaScriptApplet::print(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() != 1) {
return context->throwError(i18n("print() takes one argument"));
}
kDebug() << context->argument(0).toString();
return engine->undefinedValue();
}
QScriptValue SimpleJavaScriptApplet::createPrototype(QScriptEngine *engine, const QString &name)
{
Q_UNUSED(name)
QScriptValue proto = engine->newObject();
// Hook for adding extra properties/methods
return proto;
}
QScriptValue SimpleJavaScriptApplet::variantToScriptValue(QVariant var)
{
return ::variantToScriptValue(m_engine, var);
}
K_EXPORT_PLASMA_APPLETSCRIPTENGINE(qscriptapplet, SimpleJavaScriptApplet)
#include "simplejavascriptapplet.moc"

View File

@ -0,0 +1,92 @@
/*
* Copyright 2007 Richard J. Moore <rich@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 SCRIPT_H
#define SCRIPT_H
#include <QScriptValue>
#include <Plasma/AppletScript>
#include <Plasma/DataEngine>
#include "uiloader.h"
class QScriptEngine;
class QScriptContext;
class AppletInterface;
class SimpleJavaScriptApplet : public Plasma::AppletScript
{
Q_OBJECT
public:
SimpleJavaScriptApplet( QObject *parent, const QVariantList &args );
~SimpleJavaScriptApplet();
bool init();
void reportError();
void paintInterface(QPainter *painter, const QStyleOptionGraphicsItem *option, const QRect &contentsRect);
QList<QAction*> contextualActions();
void constraintsEvent(Plasma::Constraints constraints);
Q_INVOKABLE QString findDataResource( const QString &filename );
Q_INVOKABLE void debug( const QString &msg );
QScriptValue variantToScriptValue(QVariant var);
public slots:
void dataUpdated( const QString &name, const Plasma::DataEngine::Data &data );
void configChanged();
void executeAction(const QString &name);
private:
void importExtensions();
void setupObjects();
void callFunction(const QString &functionName, const QScriptValueList &args = QScriptValueList());
static QString findSvg(QScriptEngine *engine, const QString &file);
static QScriptValue jsi18n(QScriptContext *context, QScriptEngine *engine);
static QScriptValue jsi18nc(QScriptContext *context, QScriptEngine *engine);
static QScriptValue jsi18np(QScriptContext *context, QScriptEngine *engine);
static QScriptValue jsi18ncp(QScriptContext *context, QScriptEngine *engine);
static QScriptValue dataEngine(QScriptContext *context, QScriptEngine *engine);
static QScriptValue service(QScriptContext *context, QScriptEngine *engine);
static QScriptValue loadui(QScriptContext *context, QScriptEngine *engine);
static QScriptValue newPlasmaSvg(QScriptContext *context, QScriptEngine *engine);
static QScriptValue newPlasmaFrameSvg(QScriptContext *context, QScriptEngine *engine);
void installWidgets( QScriptEngine *engine );
static QScriptValue createWidget(QScriptContext *context, QScriptEngine *engine);
static QScriptValue notSupported(QScriptContext *context, QScriptEngine *engine);
static QScriptValue print(QScriptContext *context, QScriptEngine *engine);
static QScriptValue createPrototype( QScriptEngine *engine, const QString &name );
private:
static KSharedPtr<UiLoader> s_widgetLoader;
QScriptEngine *m_engine;
QScriptValue m_self;
QVariantList m_args;
AppletInterface *m_interface;
friend class AppletInterface;
};
#endif // SCRIPT_H

View File

@ -0,0 +1,7 @@
print(plasmoid.readConfig("Test"));
plasmoid.activeConfig = "secondary";
print(plasmoid.activeConfig);
print(plasmoid.readConfig("Test"));
plasmoid.writeConfig("Test", "You should see this!");
print(plasmoid.readConfig("Test"));

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.kde.org/standards/kcfg/1.0
http://www.kde.org/standards/kcfg/1.0/kcfg.xsd" >
<kcfgfile name=""/>
<group name="General">
<entry name="Test" type="String">
<label>A test label</label>
<default>Hello hello!</default>
</entry>
</group>
</kcfg>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.kde.org/standards/kcfg/1.0
http://www.kde.org/standards/kcfg/1.0/kcfg.xsd" >
<kcfgfile name=""/>
<group name="General">
<entry name="Test" type="String">
<label>A test label</label>
<default>This is in the secondary config XML</default>
</entry>
</group>
</kcfg>

View File

@ -0,0 +1,63 @@
[Desktop Entry]
Name=javascript-config-test
Name[cs]=Test nastavení JavaScript
Name[es]=test-de-config-javascript
Name[gu]=િ--
Name[is]=JavaScript stillingaprófun
Name[lt]=javascript-config-testas
Name[nds]=JavaScript-Instellen-Test
Name[sv]=Javascript-inställningstest
Name[tr]=javascript-yapılandırma-testi
Name[x-test]=xxjavascript-config-testxx
Name[zh_CN]=JavaScript-
Comment=Javascript config object test widget
Comment[ca]=Eina de proves de configuració d'objectes de Javascript
Comment[ca@valencia]=Eina de proves de configuració d'objectes de Javascript
Comment[cs]=Widget pro testování Javascriptu
Comment[da]=Widget til test af Javascript config-objekt
Comment[de]=Javascript-Einrichtungsobjekt Testelement
Comment[el]=Γραφικό συστατικό ελέγχου αντικειμένου ρυθμίσεων Javascript
Comment[es]=widget de prueba de configuración objeto de javascript
Comment[et]=JavaScripti seadistuse objekti testi vidin
Comment[fr]=Plasmoïde de test de configuration Javascript
Comment[ga]=Giuirléid tástála cumraíochta JavaScript
Comment[gl]=Widget de proba da configuración do obxecto en Javascript
Comment[gu]=િ િ
Comment[is]=Javascript græja til stillingaprófana
Comment[it]=Oggetto di prova per la gestione della configurazione in Javascript
Comment[km]= Javascript config
Comment[ko]= config
Comment[lt]=Javascript configūravimo objekto bandomasis valdiklis
Comment[lv]=Javascript configurācijas objekta testa logdaļa
Comment[nb]=Javascript config objekt testelement
Comment[nds]=JavaScript-Instellenobjekt-Testelement
Comment[nl]=Widget voor javascript-config-test
Comment[pa]=ਿ ਿ
Comment[pl]=Testowy element do konfiguracji obiektu Javascript
Comment[pt]=Elemento de teste de objectos de configuração em JavaScript
Comment[pt_BR]=Widget de teste de objetos de configuração em Javascript
Comment[ru]=Тестовый виджет с возможностью настройки, написанный на языке JavaScript
Comment[sl]=Preizkusni gradnik nastavitvenega objekta za Javascript
Comment[sr]=Виџет за пробу јаваскриптног објекта поставе
Comment[sr@latin]=Vidžet za probu javascript objekta postave
Comment[sv]=Grafisk testkomponent för Javascript-inställningsobjekt
Comment[te]=ి ి ి
Comment[tr]=Javascript yapılandırma nesnesi deneme parçacığı
Comment[uk]=Віджет перевірки налаштувань обєктів Javascript
Comment[x-test]=xxJavascript config object test widgetxx
Comment[zh_CN]=JavaScript
Comment[zh_TW]=Javascript
Icon=configure
Type=Service
X-KDE-ServiceTypes=Plasma/Applet
X-Plasma-MainScript=code/main.js
X-KDE-PluginInfo-Author=Aaron Seigo
X-KDE-PluginInfo-Email=aseigo@kde.org
X-KDE-PluginInfo-Name=javascript-config-test
X-KDE-PluginInfo-Version=0.0
X-KDE-PluginInfo-Website=http://plasma.kde.org/
X-KDE-PluginInfo-Category=Utilities
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true
X-Plasma-API=javascript

View File

@ -0,0 +1,12 @@
plasmoid.dataUpdate = function(a, b)
{
label.text = "It is " + b.Time.toString() + " in " + a;
}
layout = new LinearLayout(plasmoid);
label = new Label();
layout.addItem(label);
print(dataEngine("time").query("UTC").Time.toString());
plasmoid.dataEngine("time").connectSource("UTC", plasmoid, 500);

View File

@ -0,0 +1,72 @@
[Desktop Entry]
Name=script-digital-clock
Name[cs]=Skript pro digitální hodiny
Name[es]=script-Reloj-digital
Name[gu]=િ-િ-િ
Name[is]=Stafræn klukkuskrifta
Name[km]=
Name[lt]=scenarijus-skaitmeninis-laikrodis
Name[mai]=ि िि
Name[mk]=Едноставен дигитален часовник
Name[nds]=Skript-Digitaalklock
Name[nl]=script-digitale-klok
Name[pt_BR]=script-relógio-digital
Name[ro]=script-ceas-digital
Name[sv]=Skript med digitalklocka
Name[tr]=betik-dijital-saat
Name[x-test]=xxscript-digital-clockxx
Name[zh_CN]=-
Comment=Javascript digital clock
Comment[ca]=Rellotge digital en Javascript
Comment[ca@valencia]=Rellotge digital en Javascript
Comment[cs]=Digitální hodiny v JavaScriptu
Comment[da]=Digitalt ur i Javascript
Comment[de]=Eine digitale Javascript-Uhr
Comment[el]=Ψηφιακό ρολόι Javascript
Comment[es]=Reloj javascript digital
Comment[et]=Javascripti digikell
Comment[fr]=Horloge numérique JavaScript
Comment[ga]=Clog digiteach JavaScript
Comment[gl]=Reloxo dixital escrito en JavaScript
Comment[gu]=િ િ િ
Comment[is]=JavaScript stafræn klukka
Comment[it]=Orologio digitale JavaScript
Comment[ja]=JavaScript
Comment[kk]=JavaScript цифрлық сағат
Comment[km]= Javascript
Comment[ko]=
Comment[lt]=JavaScript skaitmeninis laikrodis
Comment[lv]=Javascript digitālais pulkstenis
Comment[nb]=Javascript digital klokke
Comment[nds]=JavaScript-Digitaalklock
Comment[nl]=Digitale klok geschreven in Javascript
Comment[or]=Javascript ି ି
Comment[pa]=-ਿ ਿ
Comment[pl]=Zegar cyfrowy w Javascript
Comment[pt]=Relógio digital em JavaScript
Comment[pt_BR]=Relógio digital em JavaScript
Comment[ro]=Un ceas digital Javascript
Comment[ru]=Цифровые часы, написанные на языке JavaScript
Comment[sl]=Digitalna ura v Javascriptu
Comment[sr]=Јаваскриптни дигитални сат
Comment[sr@latin]=Javascript digitalni sat
Comment[sv]=Javascript-digitalklocka
Comment[tr]=Javascript dijital saat
Comment[uk]=Цифровий годинник на JavaScript
Comment[x-test]=xxJavascript digital clockxx
Comment[zh_CN]=JavaScript
Comment[zh_TW]=Javascript
Icon=configure
Type=Service
X-KDE-ServiceTypes=Plasma/Applet
X-Plasma-MainScript=code/main.js
X-KDE-PluginInfo-Author=Marco Martin
X-KDE-PluginInfo-Email=notmart@gmail.com
X-KDE-PluginInfo-Name=script-digital-clock
X-KDE-PluginInfo-Version=0.0
X-KDE-PluginInfo-Website=http://plasma.kde.org/
X-KDE-PluginInfo-Category=Utilities
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true
X-Plasma-API=javascript

View File

@ -0,0 +1,7 @@
layout = new LinearLayout(plasmoid);
video = new VideoWidget();
video.usedControls = video.DefaultControls;
layout.addItem(video);
video.url = startupArguments[0];
video.play();

View File

@ -0,0 +1,48 @@
[Desktop Entry]
Name=script-mediaplayer
Name[gu]=િ-િ
Name[nds]=Afspeler-Skript
Name[nl]=script-mediaspeler
Name[ro]=script-lectormultimedia
Name[sv]=script-mediaspelare
Name[tr]=betik-çokluortam oynatıcı
Name[x-test]=xxscript-mediaplayerxx
Comment=Javascript media player
Comment[de]=Javascript-Medienspieler
Comment[el]=Αναπαραγωγή πολυμέσων Javascript
Comment[et]=Javascripti meediamängija
Comment[fi]=Javascript-mediasoitin
Comment[ga]=Seinnteoir meán JavaScript
Comment[gl]=Reprodutor multimedia escrito en Javascript
Comment[gu]=િ િ
Comment[ja]=JavaScript
Comment[km]= Javascript
Comment[ko]=
Comment[nb]=Javascript mediaspiller
Comment[nds]=JavaScript-Afspeler
Comment[nl]=Javascript-mediaspeler
Comment[pt]=Leitor multimédia em JavaScript
Comment[pt_BR]=Leitor de mídias em JavaScript
Comment[ro]=Lector multimedia Javascript
Comment[sv]=Javascript-mediaspelare
Comment[tr]=Javascript çokluortam oynatıcı
Comment[uk]=Програвач на JavaScript
Comment[x-test]=xxJavascript media playerxx
Comment[zh_TW]=Javascript
Icon=applications-multimedia
Type=Service
X-KDE-ServiceTypes=Plasma/Applet
X-Plasma-DropMimeTypes=video/mpeg,video/quicktime,video/ogg,video/x-msvideo, audio/mpeg, audio/x-vorbis+ogg, audio/x-flac
X-Plasma-MainScript=code/main.js
X-KDE-PluginInfo-Author=Marco Martin
X-KDE-PluginInfo-Email=notmart@gmail.com
X-KDE-PluginInfo-Name=script-mediaplayer
X-KDE-PluginInfo-Version=0.0
X-KDE-PluginInfo-Website=http://plasma.kde.org/
X-KDE-PluginInfo-Category=Utilities
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true
X-Plasma-API=javascript

View File

@ -0,0 +1,60 @@
// set up the engine, player and controller
engine = dataEngine("nowplaying");
watchingPlayer = engine.sources[0];
controller = service("nowplaying", watchingPlayer);
// define a few functions
plasmoid.dataUpdate = function(a, b)
{
label.text = "Playing " + b.Title + " by " + b.Artist + ". time: " +
Math.floor(b.Position/60) + ":" + (parseInt(b.Position)%60);
progress.value = 100*b.Position/b.Length;
}
plasmoid.stop = function()
{
data = controller.operationDescription("stop");
print(controller.name());
for ( var i in data ) {
print(i + ' -> ' + data[i] );
}
controller.startOperationCall(controller.operationDescription("stop"));
print("stopping");
}
plasmoid.setProgress = function(progress)
{
operation = controller.operationDescription("seek");
operation.seconds = progress;
for ( var i in operation ) {
print(i + ' -> ' + operation[i] );
}
controller.startOperationCall(operation);
print("set progress to " + progress);
}
// Set up the UI
layout = new LinearLayout(plasmoid);
layout.setOrientation(QtVertical);
label = new Label();
layout.addItem(label);
stop = new PushButton();
stop.text = "Stop";
layout.addItem(stop);
progress = new Slider();
progress.orientation = QtHorizontal;
layout.addItem(progress);
// Glue things together
stop.clicked.connect(plasmoid.stop);
progress.sliderMoved.connect(plasmoid.setProgress);
controller.associateWidget(stop, "stop");
controller.associateWidget(progress, "progress");
engine.connectSource(watchingPlayer, plasmoid, 500);

View File

@ -0,0 +1,65 @@
[Desktop Entry]
Name=script-nowplaying
Name[cs]=Skript "Právě hraje"
Name[es]=script-ejecutando
Name[is]=spilanúna-skrifta
Name[lt]=scenarijus-dabar groja
Name[nds]=Warrt-jüst-afspeelt-Skript
Name[nl]=script-nu-aan-het-spelen
Name[ro]=script-înredare
Name[sv]=script-spelar-nu
Name[te]=-ి
Name[tr]=betik-şimdi dinlenen parça
Name[x-test]=xxscript-nowplayingxx
Name[zh_CN]=-
Comment=Javascript version current track playing
Comment[ca]=Versió en Javascript de la peça actual en reproducció
Comment[ca@valencia]=Versió en Javascript de la peça actual en reproducció
Comment[cs]=JavaScriptová verze skriptu "Právě hraje"
Comment[da]=Javascript-version af nuværende spor som afspilles
Comment[de]=Javascript-Version der Musiktitel-Anzeige
Comment[el]=Τρέχον κομμάτι αναπαραγωγής σε έκδοση Javascript
Comment[es]=versión javascript de la reproducción actual
Comment[et]=Esitatava pala JavaScripti versioon
Comment[fi]=Nyt soi -sovelman Javascript-versio
Comment[fr]=Morceau en cours de lecture - version Javascript
Comment[ga]=Amhrán á sheinm anois in JavaScript
Comment[gl]=Versión en Javascript da pista a reproducir
Comment[is]=Javascript útgáfa núverandi spilunar
Comment[it]=La traccia attualmente in riproduzione (versione Javascript)
Comment[ja]= JavaScript
Comment[km]= Javascript
Comment[ko]=
Comment[lt]=JavaScript versija dabar grojantis takelis
Comment[lv]=Pašlaik atskaņo javascript versija
Comment[nb]=Javascript versjon spor som spilles nå
Comment[nds]=JavaScript-Verschoon vun Opstunns afspeelt Stück
Comment[nl]=Javascript-versie van momenteel spelende track
Comment[pl]=Wersja "Teraz odtwarzany" w Javascript
Comment[pt]=Versão em JavaScript do 'Agora a tocar'
Comment[pt_BR]=Versão em Javascript da reprodução da trilha atual
Comment[ru]=Виджет «Сейчас проигрывается», написанный на языке JavaScript
Comment[sl]=Trenutno predvajana skladba v Javascriptu
Comment[sr]=Јаваскриптна верзија тренутне свирке
Comment[sr@latin]=Javascript verzija trenutne svirke
Comment[sv]=Javascript-version av nuvarande spår som spelas
Comment[te]= ి
Comment[tr]=Şimdi çalınan parça bilgisi betiğinin Javascript sürümü
Comment[uk]=Javascript-версія показу назви композиції, що відтворюється
Comment[x-test]=xxJavascript version current track playingxx
Comment[zh_CN]=Javascript
Comment[zh_TW]=Javascript
Icon=configure
Type=Service
X-KDE-ServiceTypes=Plasma/Applet
X-Plasma-MainScript=code/main.js
X-KDE-PluginInfo-Author=Marco Martin
X-KDE-PluginInfo-Email=notmart@gmail.com
X-KDE-PluginInfo-Name=script-nowplaying
X-KDE-PluginInfo-Version=0.0
X-KDE-PluginInfo-Website=http://plasma.kde.org/
X-KDE-PluginInfo-Category=Utilities
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true
X-Plasma-API=javascript

View File

@ -0,0 +1,14 @@
svg = new PlasmaSvg('tiger');
plasmoid.setAction("myAction", "Select Me!", "plasma");
plasmoid.action_myAction = function()
{
print("myAction triggered!");
plasmoid.removeAction("myAction");
}
plasmoid.paintInterface = function(painter)
{
svg.resize( plasmoid.size() );
svg.paint( painter, 0,0 );
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 94 KiB

View File

@ -0,0 +1,93 @@
[Desktop Entry]
Encoding=UTF-8
Name=Tiger
Name[ar]=النمر
Name[be@latin]=Tyhra
Name[bn]=
Name[el]=Τίγρης
Name[es]=Tigre
Name[fi]=Tiikeri
Name[fr]=Tigre
Name[gl]=Tigre
Name[gu]=
Name[he]=נמר
Name[hi]=
Name[hne]=
Name[it]=Tigre
Name[ja]=
Name[kk]=Жолбарыс
Name[km]=
Name[ku]=Piling
Name[lt]=Tigras
Name[lv]=Tīģeris
Name[mai]=
Name[ml]=
Name[nl]=Tijger
Name[or]=
Name[pa]=
Name[pl]=Tygrys
Name[pt]=Tigre
Name[pt_BR]=Tigre
Name[ro]=Tigru
Name[ru]=Тигр
Name[sr]=тигар
Name[sr@latin]=tigar
Name[tg]=Паланг
Name[th]=
Name[tr]=Kaplan
Name[uk]=Тигр
Name[x-test]=xxTigerxx
Name[zh_CN]=
Name[zh_TW]=
Comment=A Script Adaptor
Comment[ca]=Un adaptador de scripts
Comment[ca@valencia]=Un adaptador de scripts
Comment[cs]=Zpracování skriptu
Comment[da]=En script-adaptor
Comment[de]=Eine Skript-Anpassung
Comment[el]=Ένας προσαρμογέας σεναρίου
Comment[es]=Un adaptador javascript
Comment[et]=Skriptiadapter
Comment[fr]=Un adaptateur de script
Comment[ga]=Cuibheoir Scripte
Comment[gl]=Un adaptador de script
Comment[gu]=િ
Comment[is]=Skriftumótari
Comment[it]=Script adattatore
Comment[km]=
Comment[ko]=
Comment[lt]=Scenarijų adaptatorius
Comment[lv]=Skriptu pielāgotājs
Comment[nb]=En skripttilpasser
Comment[nds]=En Skript-Topasser
Comment[nl]=Een scriptadaptor
Comment[or]=ି ି
Comment[pa]=ਿ
Comment[pl]=Adapter skryptów
Comment[pt]=Um Adaptador de Programas
Comment[pt_BR]=Um adaptador de script
Comment[ro]=Adaptor de scripturi
Comment[ru]=Адаптер скриптов
Comment[sl]=Skriptni prilagodilnik
Comment[sr]=Адаптор скрипти
Comment[sr@latin]=Adaptor skripti
Comment[sv]=En skriptanpassning
Comment[te]=ి
Comment[tr]=Bir Betik Uyarlayıcısı
Comment[uk]=Пристосування скриптів
Comment[x-test]=xxA Script Adaptorxx
Comment[zh_CN]=
Comment[zh_TW]=稿
Type=Service
ServiceTypes=Plasma/Applet
X-KDE-PluginInfo-Author=Richard Moore
X-KDE-PluginInfo-Email=panel-devel@kde.org
X-KDE-PluginInfo-Name=tiger
X-KDE-PluginInfo-Version=pre0.1
X-KDE-PluginInfo-Website=http://plasma.kde.org/
X-KDE-PluginInfo-Category=Examples
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true
X-Plasma-API=javascript

View File

@ -0,0 +1,122 @@
/*
* Copyright 2007 Richard J. Moore <rich@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 "uiloader.h"
#include <QGraphicsGridLayout>
#include <QGraphicsLinearLayout>
#include <QStringList>
#include <Plasma/BusyWidget>
#include <Plasma/CheckBox>
#include <Plasma/ComboBox>
#include <Plasma/FlashingLabel>
#include <Plasma/Frame>
#include <Plasma/GroupBox>
#include <Plasma/IconWidget>
#include <Plasma/Label>
#include <Plasma/LineEdit>
#include <Plasma/Meter>
#include <Plasma/PushButton>
#include <Plasma/RadioButton>
#include <Plasma/ScrollBar>
#include <Plasma/SignalPlotter>
#include <Plasma/Slider>
#include <Plasma/SpinBox>
#include <Plasma/SvgWidget>
#include <Plasma/TabBar>
#include <Plasma/TextEdit>
#include <Plasma/ToolButton>
#include <Plasma/TreeView>
#include <Plasma/WebView>
#include <Plasma/VideoWidget>
QGraphicsWidget *createBusyWidget(QGraphicsWidget *parent) { return new Plasma::BusyWidget(parent); }
QGraphicsWidget *createCheckBox(QGraphicsWidget *parent) { return new Plasma::CheckBox(parent); }
QGraphicsWidget *createComboBox(QGraphicsWidget *parent) { return new Plasma::ComboBox(parent); }
QGraphicsWidget *createFlashingLabel(QGraphicsWidget *parent) { return new Plasma::FlashingLabel(parent); }
QGraphicsWidget *createFrame(QGraphicsWidget *parent) { return new Plasma::Frame(parent); }
QGraphicsWidget *createGroupBox(QGraphicsWidget *parent) { return new Plasma::GroupBox(parent); }
QGraphicsWidget *createIconWidget(QGraphicsWidget *parent) { return new Plasma::IconWidget(parent); }
QGraphicsWidget *createLabel(QGraphicsWidget *parent) { return new Plasma::Label(parent); }
QGraphicsWidget *createLineEdit(QGraphicsWidget *parent) { return new Plasma::LineEdit(parent); }
QGraphicsWidget *createMeter(QGraphicsWidget *parent) { return new Plasma::Meter(parent); }
QGraphicsWidget *createPushButton(QGraphicsWidget *parent) { return new Plasma::PushButton(parent); }
QGraphicsWidget *createRadioButton(QGraphicsWidget *parent) { return new Plasma::RadioButton(parent); }
QGraphicsWidget *createScrollBar(QGraphicsWidget *parent) { return new Plasma::ScrollBar(parent); }
QGraphicsWidget *createSignalPlotter(QGraphicsWidget *parent) { return new Plasma::SignalPlotter(parent); }
QGraphicsWidget *createSlider(QGraphicsWidget *parent) { return new Plasma::Slider(parent); }
QGraphicsWidget *createSpinBox(QGraphicsWidget *parent) { return new Plasma::SpinBox(parent); }
QGraphicsWidget *createSvgWidget(QGraphicsWidget *parent) { return new Plasma::SvgWidget(parent); }
QGraphicsWidget *createTabBar(QGraphicsWidget *parent) { return new Plasma::TabBar(parent); }
QGraphicsWidget *createTextEdit(QGraphicsWidget *parent) { return new Plasma::TextEdit(parent); }
QGraphicsWidget *createToolButton(QGraphicsWidget *parent) { return new Plasma::ToolButton(parent); }
QGraphicsWidget *createTreeView(QGraphicsWidget *parent) { return new Plasma::TreeView(parent); }
QGraphicsWidget *createVideoWidget(QGraphicsWidget *parent) { return new Plasma::VideoWidget(parent); }
QGraphicsWidget *createWebView(QGraphicsWidget *parent) { return new Plasma::WebView(parent); }
UiLoader::UiLoader()
{
m_widgetCtors.insert("BusyWidget", createBusyWidget);
m_widgetCtors.insert("CheckBox", createCheckBox);
m_widgetCtors.insert("ComboBox", createComboBox);
m_widgetCtors.insert("FlashingLabel", createFlashingLabel);
m_widgetCtors.insert("Frame", createFrame);
m_widgetCtors.insert("GroupBox", createGroupBox);
m_widgetCtors.insert("IconWidget", createIconWidget);
m_widgetCtors.insert("Label", createLabel);
m_widgetCtors.insert("LineEdit", createLineEdit);
m_widgetCtors.insert("Meter", createMeter);
m_widgetCtors.insert("PushButton", createPushButton);
m_widgetCtors.insert("RadioButton", createRadioButton);
m_widgetCtors.insert("ScrollBar", createScrollBar);
m_widgetCtors.insert("SignalPlotter", createSignalPlotter);
m_widgetCtors.insert("Slider", createSlider);
m_widgetCtors.insert("SpinBox", createSpinBox);
m_widgetCtors.insert("SvgWidget", createSvgWidget);
m_widgetCtors.insert("TabBar", createTabBar);
m_widgetCtors.insert("TextEdit", createTextEdit);
m_widgetCtors.insert("ToolButton", createToolButton);
m_widgetCtors.insert("TreeView", createTreeView);
m_widgetCtors.insert("VideoWidget", createVideoWidget);
m_widgetCtors.insert("WebView", createWebView);
}
UiLoader::~UiLoader()
{
kDebug();
}
QStringList UiLoader::availableWidgets() const
{
return m_widgetCtors.keys();
}
QGraphicsWidget *UiLoader::createWidget(const QString &className, QGraphicsWidget *parent)
{
widgetCreator w = m_widgetCtors.value(className, 0);
if (w) {
return (w)(parent);
}
return 0;
}

View File

@ -0,0 +1,44 @@
/*
* Copyright 2007 Richard J. Moore <rich@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 PLASMA_UILOADER_H
#define PLASMA_UILOADER_H
#include <KSharedPtr>
#include <plasma/applet.h>
class QGraphicsWidget;
class UiLoader : public QSharedData
{
public:
UiLoader();
virtual ~UiLoader();
QStringList availableWidgets() const;
QGraphicsWidget *createWidget(const QString &className, QGraphicsWidget *parent = 0);
private:
typedef QGraphicsWidget *(*widgetCreator)(QGraphicsWidget*);
QHash<QString, widgetCreator> m_widgetCtors;
};
#endif // PLASMA_UILOADER_H