Merge branch 'libplasma2' into frameworks

Conflicts:
	plasma/CMakeLists.txt
	plasma/popupapplet.cpp
This commit is contained in:
Marco Martin 2011-08-12 11:45:49 +02:00
commit 33e9192346
159 changed files with 4355 additions and 5992 deletions

View File

@ -7,6 +7,8 @@ if(KDE_PLATFORM_FEATURE_BINARY_COMPATIBLE_FEATURE_REDUCTION)
set(PLASMA_NO_SOLID TRUE)
set(PLASMA_NO_KIO TRUE)
set(PLASMA_NO_PACKAGEKIT TRUE)
set(PLASMA_NO_PACKAGE_EXTRADATA TRUE)
endif(KDE_PLATFORM_FEATURE_BINARY_COMPATIBLE_FEATURE_REDUCTION)
if(NOT Q_WS_X11)
@ -60,24 +62,22 @@ if(QCA2_FOUND)
endif(QCA2_FOUND)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config-plasma.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-plasma.h)
#FIXME: gpgme++ is in kdepimlibs, must move somewhere else!
macro_optional_find_package(KdepimLibs 4.5.60)
macro_log_feature(KDEPIMLIBS_FOUND "kdepimlibs" "KDE PIM libraries" "http://www.kde.org" FALSE "" "Needed for building several Plasma DataEngines")
include_directories(${KDEPIMLIBS_INCLUDE_DIRS})
add_subdirectory(tests)
add_definitions(-DKDE_DEFAULT_DEBUG_AREA=1209)
########### next target ###############
set(plasmagik_SRCS
packagemetadata.cpp
packagestructure.cpp
package.cpp
)
#to make the Temporary solution to not link to libkdeclarative work, disable the exports of libkdeclarative
add_definitions(-DKDECLARATIVE_EXPORT=)
set(plasma_LIB_SRCS
${plasmagik_SRCS}
abstractrunner.cpp
${plasmagik_SRCS}
abstractdialogmanager.cpp
abstracttoolbox.cpp
dialog.cpp
animator.cpp
animations/animation.cpp
animations/animationscriptengine.cpp
@ -98,45 +98,40 @@ set(plasma_LIB_SRCS
animations/water.cpp
animations/widgetsnapshot.cpp
animations/zoom.cpp
applet.cpp
configloader.cpp
containment.cpp
containmentactions.cpp
containmentactionspluginsconfig.cpp
context.cpp
corona.cpp
datacontainer.cpp
dataengine.cpp
dataenginemanager.cpp
delegate.cpp
dialog.cpp
abstractdialogmanager.cpp
extenders/extender.cpp
extenders/extendergroup.cpp
extenders/extenderitem.cpp
pluginloader.cpp
package.cpp
packagestructure.cpp
paintutils.cpp
pluginloader.cpp
framesvg.cpp
plasma.cpp
applet.cpp
popupapplet.cpp
private/animablegraphicswebview.cpp
pluginloader.cpp
private/applethandle.cpp
private/associatedapplicationmanager.cpp
private/componentinstaller.cpp
private/datacontainer_p.cpp
private/dataenginebindings.cpp
private/dataengineconsumer.cpp
private/dataengineservice.cpp
private/denyallauthorization.cpp
private/effectwatcher.cpp
private/extenderapplet.cpp
private/extenderitemmimedata.cpp
private/focusindicator.cpp
private/getsource.cpp
private/nativetabbar.cpp
private/packages.cpp
private/pinpairingauthorization.cpp
private/pinpairingdialog.cpp
private/plasmoidservice.cpp
private/remotedataengine.cpp
private/remoteservice.cpp
@ -146,12 +141,11 @@ set(plasma_LIB_SRCS
private/storage.cpp
private/storagethread.cpp
private/style.cpp
private/trustedonlyauthorization.cpp
private/tooltip.cpp
private/wallpaperrenderthread.cpp
private/windowpreview.cpp
private/windowshadows.cpp
private/kineticscroll.cpp
private/declarative/declarativenetworkaccessmanagerfactory.cpp
private/effects/halopainter.cpp
private/effects/ripple.cpp
querymatch.cpp
@ -162,7 +156,12 @@ set(plasma_LIB_SRCS
remote/authorizationrule.cpp
remote/clientpinrequest.cpp
remote/credentials.cpp
remote/denyallauthorization.cpp
remote/pinpairingauthorization.cpp
remote/pinpairingdialog.cpp
remote/serviceaccessjob.cpp
remote/signing.cpp
remote/trustedonlyauthorization.cpp
runnercontext.cpp
runnermanager.cpp
runnersyntax.cpp
@ -181,33 +180,7 @@ set(plasma_LIB_SRCS
view.cpp
wallpaper.cpp
windoweffects.cpp
widgets/checkbox.cpp
widgets/combobox.cpp
widgets/declarativewidget.cpp
widgets/flashinglabel.cpp
widgets/frame.cpp
widgets/groupbox.cpp
widgets/iconwidget.cpp
widgets/itembackground.cpp
widgets/label.cpp
widgets/lineedit.cpp
widgets/meter.cpp
widgets/pushbutton.cpp
widgets/radiobutton.cpp
widgets/scrollbar.cpp
widgets/signalplotter.cpp
widgets/slider.cpp
widgets/spinbox.cpp
widgets/toolbutton.cpp
widgets/busywidget.cpp
widgets/scrollwidget.cpp
widgets/separator.cpp
widgets/svgwidget.cpp
widgets/tabbar.cpp
widgets/textbrowser.cpp
widgets/treeview.cpp
widgets/textedit.cpp
widgets/webview.cpp
#Temporary QtJolie branch
private/qtjolie-branch/qtjolie/abstractadaptor.cpp
@ -223,28 +196,50 @@ set(plasma_LIB_SRCS
private/qtjolie-branch/qtjolie/server.cpp
private/qtjolie-branch/qtjolie/serverthread.cpp
#Temporary solution to not link to libkdeclarative
${CMAKE_SOURCE_DIR}/experimental/libkdeclarative/kdeclarative.cpp
${CMAKE_SOURCE_DIR}/experimental/libkdeclarative/private/engineaccess.cpp
${CMAKE_SOURCE_DIR}/experimental/libkdeclarative/private/kiconprovider.cpp
${CMAKE_SOURCE_DIR}/experimental/libkdeclarative/bindings/qscriptnonguibookkeeping.cpp
${CMAKE_SOURCE_DIR}/experimental/libkdeclarative/bindings/i18n.cpp
${CMAKE_SOURCE_DIR}/experimental/libkdeclarative/bindings/icon.cpp
${CMAKE_SOURCE_DIR}/experimental/libkdeclarative/bindings/url.cpp
widgets/pushbutton.cpp
widgets/busywidget.cpp
widgets/iconwidget.cpp
widgets/label.cpp
widgets/scrollbar.cpp
widgets/scrollwidget.cpp
widgets/svgwidget.cpp
widgets/textbrowser.cpp
widgets/textedit.cpp
)
if(NOT KDE_NO_DEPRECATED)
set(plasma_LIB_SRCS
${plasma_LIB_SRCS}
deprecated/animationdriver.cpp
deprecated/animator.cpp
)
endif(NOT KDE_NO_DEPRECATED)
set (plasmaqgv_LIB_SRCS
private/animablegraphicswebview.cpp
private/dataenginebindings.cpp
private/declarative/declarativenetworkaccessmanagerfactory.cpp
private/focusindicator.cpp
private/nativetabbar.cpp
private/style.cpp
widgets/checkbox.cpp
widgets/combobox.cpp
widgets/declarativewidget.cpp
widgets/flashinglabel.cpp
widgets/frame.cpp
widgets/groupbox.cpp
widgets/itembackground.cpp
widgets/lineedit.cpp
widgets/meter.cpp
widgets/radiobutton.cpp
widgets/signalplotter.cpp
widgets/slider.cpp
widgets/spinbox.cpp
widgets/toolbutton.cpp
widgets/separator.cpp
widgets/tabbar.cpp
widgets/treeview.cpp
widgets/webview.cpp
)
kde4_add_kcfg_files(plasma_LIB_SRCS data/kconfigxt/libplasma-theme-global.kcfgc)
kde4_add_ui_files(plasma_LIB_SRCS
private/pinpairing.ui
remote/pinpairing.ui
private/publish.ui)
#NEPOMUK_GENERATE_FROM_ONTOLOGY(
# nwc.nrl
@ -254,27 +249,29 @@ kde4_add_ui_files(plasma_LIB_SRCS
# TEST_INCLUDES
#)
if (QT_QTOPENGL_FOUND)
message(STATUS "Adding support for OpenGL applets to libplasma")
set(plasma_LIB_SRCS
${plasma_LIB_SRCS}
glapplet.cpp)
endif(QT_QTOPENGL_FOUND)
if (PHONON_FOUND)
message(STATUS "Adding support for Phonon to libplasma")
include_directories(${KDE4_PHONON_INCLUDES})
set(plasma_LIB_SRCS
${plasma_LIB_SRCS}
set(plasmaqgv_LIB_SRCS
${plasmaqgv_LIB_SRCS}
widgets/videowidget.cpp)
endif(PHONON_FOUND)
kde4_add_library(plasma ${LIBRARY_TYPE} ${plasma_LIB_SRCS})
#add kdeclarative after the 4.7 release
kde4_add_library(plasmaqgv ${LIBRARY_TYPE} ${plasmaqgv_LIB_SRCS})
target_link_libraries(plasma ${QT_QTUITOOLS_LIBRARY} ${QT_QTWEBKIT_LIBRARY}
${QT_QTSCRIPT_LIBRARY} ${QT_QTNETWORK_LIBRARY} ${QT_QTXML_LIBRARY} ${QT_QTSQL_LIBRARY} ${QT_QTDECLARATIVE_LIBRARY}
${KDE4_KDEUI_LIBS} kdnssd threadweaver ${PLASMA_EXTRA_LIBS} karchive)
${KDE4_KDEUI_LIBS} kdnssd threadweaver kdeclarative ${PLASMA_EXTRA_LIBS})
#FIXME gpgme++ is in kdepimlibs, neeeds to be elsewhere
target_link_libraries(plasma ${KDEPIMLIBS_GPGMEPP_LIBS})
target_link_libraries(plasmaqgv plasma ${QT_QTUITOOLS_LIBRARY} ${QT_QTWEBKIT_LIBRARY}
${QT_QTSCRIPT_LIBRARY} ${QT_QTNETWORK_LIBRARY} ${QT_QTDECLARATIVE_LIBRARY}
${KDE4_KDEUI_LIBS} kdeclarative ${PLASMA_EXTRA_LIBS})
if(QCA2_FOUND)
target_link_libraries(plasma ${QCA2_LIBRARIES})
@ -285,38 +282,31 @@ if(X11_FOUND)
endif(X11_FOUND)
if(PHONON_FOUND)
target_link_libraries(plasma ${KDE4_PHONON_LIBS})
target_link_libraries(plasmaqgv ${KDE4_PHONON_LIBS})
endif(PHONON_FOUND)
if(DL_LIBRARY)
target_link_libraries(plasma ${DL_LIBRARY})
endif(DL_LIBRARY)
if(QT_QTOPENGL_FOUND)
target_link_libraries(plasma ${QT_QTOPENGL_LIBRARY})
endif(QT_QTOPENGL_FOUND)
target_link_libraries(plasma LINK_INTERFACE_LIBRARIES kdeui kdecore ${QT_QTGUI_LIBRARY})
#do NOT use GENERIC versioning -- the plasma team will take care of versioning
set_target_properties(plasma PROPERTIES
VERSION 3.0.0
SOVERSION 3
VERSION 4.0.0
SOVERSION 4
)
set_target_properties(plasmaqgv PROPERTIES
VERSION 1.0.0
SOVERSION 1
)
install(TARGETS plasma EXPORT kdelibsLibraryTargets ${INSTALL_TARGETS_DEFAULT_ARGS})
install(TARGETS plasmaqgv EXPORT kdelibsLibraryTargets ${INSTALL_TARGETS_DEFAULT_ARGS})
########### install files ###############
set(plasmagik_HEADERS
packagemetadata.h
packagestructure.h
package.h
)
install(FILES ${plasmagik_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/plasma/ COMPONENT Devel)
set(plasma_LIB_INCLUDES
abstractdialogmanager.h
abstractrunner.h
@ -328,7 +318,6 @@ set(plasma_LIB_INCLUDES
containment.h
containmentactions.h
containmentactionspluginsconfig.h
context.h
corona.h
datacontainer.h
dataengine.h
@ -342,6 +331,8 @@ set(plasma_LIB_INCLUDES
paintutils.h
windoweffects.h
framesvg.h
package.h
packagestructure.h
plasma.h
plasma_export.h
popupapplet.h
@ -367,19 +358,6 @@ set(plasma_LIB_INCLUDES
view.h
wallpaper.h)
if(NOT KDE_NO_DEPRECATED)
set(plasma_LIB_INCLUDES
${plasma_LIB_INCLUDES}
animationdriver.h
)
endif(NOT KDE_NO_DEPRECATED)
if(QT_QTOPENGL_FOUND)
set(plasma_LIB_INCLUDES
${plasma_LIB_INCLUDES}
glapplet.h)
endif(QT_QTOPENGL_FOUND)
install(FILES
${plasma_LIB_INCLUDES}

View File

@ -39,7 +39,7 @@ Other important classes are:
- Plasma::Dialog: displays a themed application dialog
- Plasma::Extender: provides detachable sections to Plasma::Applet
- Plasma::GLApplet: provides an OpenGL-rendered Plasma::Applet
- Plasma::PackageStructure: provides descriptions of packages containing plugins
- Plasma::Package: provides descriptions of packages containing plugins
for libplasma
- Plasma::PopupApplet: provides a simple way of implementing a Plasma::Applet
consisting of an icon that shows a popup when clicked

4
README
View File

@ -6,8 +6,8 @@ and its components. This includes applet and extension definitions and loading,
common GUI elements, data and service interaction, search system, etc.
Domain specific sets of functionality, e.g. for network awareness or sensors,
are not found here but as DataEngine, Service, Applet, PackageStructure, etc
plugins.
are not found here but as DataEngine, Service, Applet, Package, Wallpaper,
ContainmentActions, Containment and other plugins.
Commit Guidelines:
* If your patch is not an obvious or trivial bug fix, have it peer reviewed

View File

@ -33,10 +33,10 @@
#include <kservicetypetrader.h>
#include <kstandarddirs.h>
#include <plasma/package.h>
#include <plasma/querymatch.h>
#include "package.h"
#include "pluginloader.h"
#include "private/abstractrunner_p.h"
#include "querymatch.h"
#include "runnercontext.h"
#include "scripting/runnerscript.h"
@ -142,7 +142,9 @@ void AbstractRunner::performMatch(Plasma::RunnerContext &localContext)
if (!slowed && runtime > reasonableRunTime) {
// we punish runners that return too slowly, even if they don't bring
// back matches
#ifndef NDEBUG
kDebug() << id() << "runner is too slow, putting it on the back burner.";
#endif
d->fastRuns = 0;
setSpeed(SlowSpeed);
}
@ -153,7 +155,9 @@ void AbstractRunner::performMatch(Plasma::RunnerContext &localContext)
if (d->fastRuns > 2) {
// we reward slowed runners who bring back matches fast enough
// 3 times in a row
#ifndef NDEBUG
kDebug() << id() << "runner is faster than we thought, kicking it up a notch";
#endif
setSpeed(NormalSpeed);
}
}
@ -203,7 +207,7 @@ void AbstractRunner::clearActions()
d->actions.clear();
}
QMimeData * AbstractRunner::mimeDataForMatch(const QueryMatch *match)
QMimeData *AbstractRunner::mimeDataForMatch(const QueryMatch &match)
{
Q_UNUSED(match)
return 0;
@ -267,11 +271,6 @@ void AbstractRunner::setIgnoredTypes(RunnerContext::Types types)
d->blackListed = types;
}
KService::List AbstractRunner::serviceQuery(const QString &serviceType, const QString &constraint) const
{
return KServiceTypeTrader::self()->query(serviceType, constraint);
}
QMutex* AbstractRunner::bigLock()
{
return s_bigLock;
@ -297,10 +296,6 @@ QString AbstractRunner::name() const
return d->runnerDescription.name();
}
if (d->package) {
return d->package->metadata().name();
}
return objectName();
}
@ -310,10 +305,6 @@ QIcon AbstractRunner::icon() const
return KIcon(d->runnerDescription.icon());
}
if (d->package) {
return KIcon(d->package->metadata().icon());
}
return QIcon();
}
@ -323,10 +314,6 @@ QString AbstractRunner::id() const
return d->runnerDescription.pluginName();
}
if (d->package) {
return d->package->metadata().pluginName();
}
return objectName();
}
@ -336,16 +323,12 @@ QString AbstractRunner::description() const
return d->runnerDescription.property("Comment").toString();
}
if (d->package) {
return d->package->metadata().description();
}
return objectName();
}
const Package* AbstractRunner::package() const
Package AbstractRunner::package() const
{
return d->package;
return d->package ? *d->package : Package();
}
@ -410,7 +393,9 @@ void AbstractRunnerPrivate::init(const KService::Ptr service)
const QString path = KStandardDirs::locate("data", "plasma/runners/" + runnerDescription.pluginName() + '/');
prepScripting(path, api);
if (!script) {
#ifndef NDEBUG
kDebug() << "Could not create a(n)" << api << "ScriptEngine for the" << runnerDescription.name() << "Runner.";
#endif
}
}
}
@ -418,30 +403,32 @@ void AbstractRunnerPrivate::init(const KService::Ptr service)
void AbstractRunnerPrivate::init(const QString &path)
{
prepScripting(path);
runnerDescription = KPluginInfo(path + "/metadata.desktop");
const QString api = runnerDescription.property("X-Plasma-API").toString();
prepScripting(path, api);
}
void AbstractRunnerPrivate::prepScripting(const QString &path, QString api)
void AbstractRunnerPrivate::prepScripting(const QString &path, const QString &api)
{
if (script) {
return;
}
delete package;
PackageStructure::Ptr structure = Plasma::packageStructure(api, Plasma::RunnerComponent);
structure->setPath(path);
package = new Package(path, structure);
if (!package->isValid()) {
kDebug() << "Invalid Runner package at" << path;
delete package;
package = 0;
if (api.isEmpty()) {
return;
}
if (api.isEmpty()) {
api = package->metadata().implementationApi();
package = new Package(PluginLoader::self()->loadPackage("Plasma/Runner", api));
package->setPath(path);
if (!package->isValid()) {
#ifndef NDEBUG
kDebug() << "Invalid Runner package at" << path;
#endif
return;
}
script = Plasma::loadScriptEngine(api, runner);
@ -459,16 +446,15 @@ void AbstractRunnerPrivate::setupScriptSupport()
return;
}
#ifndef NDEBUG
kDebug() << "setting up script support, package is in" << package->path()
<< "which is a" << package->structure()->type() << "package"
<< ", main script is" << package->filePath("mainscript");
#endif
QString translationsPath = package->filePath("translations");
const QString translationsPath = package->filePath("translations");
if (!translationsPath.isEmpty()) {
//FIXME: we should _probably_ use a KComponentData to segregate the applets
// from each other; but I want to get the basics working first :)
KGlobal::dirs()->addResourceDir("locale", translationsPath);
KGlobal::locale()->insertCatalog(package->metadata().pluginName());
KGlobal::locale()->insertCatalog(runnerDescription.pluginName());
}
}

View File

@ -222,9 +222,9 @@ class PLASMA_EXPORT AbstractRunner : public QObject
* Note that the returned pointer is only valid for the lifetime of
* the runner.
*
* @return the Package object, or 0 if none
* @return the Package object, which may be invalid
**/
const Package *package() const;
Package package() const;
/**
* Signal runner to reload its configuration.
@ -331,21 +331,6 @@ class PLASMA_EXPORT AbstractRunner : public QObject
*/
void setPriority(Priority newPriority);
/**
* @deprecated
* A blocking method to do queries of installed Services which can provide
* a measure of safety for runners running their own threads. This should
* be used instead of calling KServiceTypeTrader::query(..) directly.
*
* @param serviceType a service type like "Plasma/Applet" or "KFilePlugin"
* @param constraint a constraint to limit the choices returned.
* @see KServiceTypeTrader::query(const QString&, const QString&)
*
* @return a list of services that satisfy the query.
*/
KService::List serviceQuery(const QString &serviceType,
const QString &constraint = QString()) const;
/**
* A given match can have more than action that can be performed on it.
* For example, a song match returned by a music player runner can be queued,
@ -459,20 +444,19 @@ class PLASMA_EXPORT AbstractRunner : public QObject
*/
Q_INVOKABLE DataEngine *dataEngine(const QString &name) const;
protected Q_SLOTS:
/**
* Reimplement this slot to run any initialization routines on first load.
* By default, it calls reloadConfiguration(); for scripted Runners this
* method also sets up the ScriptEngine.
*/
void init();
virtual void init();
/**
* Reimplement this slot if you want your runner
* to support serialization and drag and drop
* @since 4.5
*/
QMimeData * mimeDataForMatch(const Plasma::QueryMatch *match);
virtual QMimeData *mimeDataForMatch(const Plasma::QueryMatch &match);
private:
friend class RunnerScript;

View File

@ -79,8 +79,7 @@ public:
*
* @since 4.6
*/
static KPluginInfo::List listToolBoxInfo(const QString
&parentApp = QString());
static KPluginInfo::List listToolBoxInfo(const QString &parentApp = QString());
/**
* create a toolbox tool from the given action
@ -103,28 +102,26 @@ public:
*/
virtual void setShowing(const bool show) = 0;
public Q_SLOTS:
//FIXME for KDE5: those should become virtuals
/**
* Restore the ToolBox settings
* It has to be reimplemented in toolboxes that need it
* @since 4.6
*/
void restore(const KConfigGroup &group);
virtual void restore(const KConfigGroup &group);
/**
* Save the ToolBox settings
* It has to be reimplemented in toolboxes that need it
* @since 4.6
*/
void save(const KConfigGroup &group);
virtual void save(const KConfigGroup &group);
/**
* Inform the ToolBox it has to reposition itlself
* It has to be reimplemented in toolboxes that need it
* @since 4.6
*/
void reposition();
virtual void reposition();
Q_SIGNALS:
/**

View File

@ -1,85 +0,0 @@
/*
* Copyright 2007 Aaron Seigo <aseigo@kde.org>
* Copyright 2007 Alexis Ménard <darktears31@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef PLASMA_ANIMATIONDRIVER_H
#define PLASMA_ANIMATIONDRIVER_H
#include <QtCore/QObject>
#include <QtGui/QRegion>
#include <QtGui/QPixmap>
#include <kgenericfactory.h>
#include <plasma/version.h>
#include <plasma/animator.h>
class QGraphicsItem;
namespace Plasma
{
class AnimationDriverPrivate;
class PLASMA_EXPORT_DEPRECATED AnimationDriver : public QObject
{
Q_OBJECT
public:
explicit AnimationDriver(QObject *parent = 0);
~AnimationDriver();
// Parameter definitions
virtual int animationFps(Plasma::Animator::Animation) const;
virtual int movementAnimationFps(Plasma::Animator::Movement) const;
virtual int elementAnimationFps(Plasma::Animator::Animation) const;
virtual int animationDuration(Plasma::Animator::Animation) const;
virtual int movementAnimationDuration(Plasma::Animator::Movement) const;
virtual int elementAnimationDuration(Plasma::Animator::Animation) const;
virtual Animator::CurveShape animationCurve(Plasma::Animator::Animation) const;
virtual Animator::CurveShape movementAnimationCurve(Plasma::Animator::Movement) const;
virtual Animator::CurveShape elementAnimationCurve(Plasma::Animator::Animation) const;
// Element animations
virtual QPixmap elementAppear(qreal progress, const QPixmap &pixmap);
virtual QPixmap elementDisappear(qreal progress, const QPixmap &pixmap);
// Item animations
virtual void itemAppear(qreal progress, QGraphicsItem *item);
virtual void itemDisappear(qreal progress, QGraphicsItem *item);
virtual void itemActivated(qreal progress, QGraphicsItem *item);
// Item movements
virtual void itemSlideIn(qreal progress, QGraphicsItem *item,
const QPoint &start, const QPoint &destination);
virtual void itemSlideOut(qreal progress, QGraphicsItem *item,
const QPoint &start, const QPoint &destination);
private:
AnimationDriverPrivate *const d;
};
} // Plasma namespace
#define K_EXPORT_PLASMA_ANIMATOR(libname, classname) \
K_PLUGIN_FACTORY(factory, registerPlugin<classname>();) \
K_EXPORT_PLUGIN(factory("plasma_animator_" #libname)) \
K_EXPORT_PLUGIN_VERSION(PLASMA_VERSION)
#endif // multiple inclusion guard

View File

@ -178,7 +178,9 @@ QScriptEngine *globalEngine()
global.setProperty("AnimationGroup", inst->newFunction(AnimationScriptEngine::animationGroup));
global.setProperty("ParallelAnimationGroup", inst->newFunction(AnimationScriptEngine::parallelAnimationGroup));
global.setProperty("QEasingCurve", constructEasingCurveClass(inst));
#ifndef NDEBUG
kDebug() << "........... first js animation, creating the engine!";
#endif
}
return inst;

View File

@ -76,7 +76,9 @@ void JavascriptAnimation::updateState(QAbstractAnimation::State newState, QAbstr
if (!m_method.isFunction()) {
//Define the class and create an instance
m_instance = AnimationScriptEngine::animation(m_name).construct();
#ifndef NDEBUG
kDebug() << "trying for" << m_name << m_instance.isFunction();
#endif
//Get the method of the object
m_method = m_instance.property(QString("updateCurrentTime"));
@ -101,7 +103,9 @@ void JavascriptAnimation::updateState(QAbstractAnimation::State newState, QAbstr
#ifdef PLASMA_JSANIM_FPS
m_fps = 0;
} else if (oldState == Running && newState == Stopped) {
#ifndef NDEBUG
kDebug() << ".........." << m_name << " fps: " << m_fps * 1000/duration();
#endif
#endif
}
}

View File

@ -167,7 +167,6 @@ void PixmapTransition::updateState(QAbstractAnimation::State newState, QAbstract
void PixmapTransition::updateEffectiveTime(int currentTime)
{
Q_UNUSED(currentTime)
m_dirty = true;
QGraphicsWidget *w = targetWidget();
if (w) {

View File

@ -74,7 +74,6 @@ void RotationAnimation::updateState(QAbstractAnimation::State newState, QAbstrac
{
Q_UNUSED(newState)
Q_UNUSED(oldState)
QGraphicsWidget *m_object = targetWidget();
if (!m_object) {

View File

@ -42,6 +42,12 @@ namespace Plasma
QHash<Animator::Animation, Animator::Animation> AnimatorPrivate::s_stockAnimMappings;
QHash<Animator::Animation, QString> AnimatorPrivate::s_loadableAnimMappings;
Animator::Animator(QObject *parent)
: QObject(parent),
d(0)
{
}
void AnimatorPrivate::mapAnimation(Animator::Animation from, Animator::Animation to)
{
if (from == to) {
@ -174,7 +180,9 @@ QEasingCurve Animator::create(Animator::CurveShape type)
break;
default:
#ifndef NDEBUG
kDebug() << "Unsupported easing curve type.";
#endif
break;
}

View File

@ -48,10 +48,8 @@ class PLASMA_EXPORT Animator : public QObject
Q_OBJECT
Q_ENUMS(Animation)
Q_ENUMS(CurveShape)
Q_ENUMS(Movement)
public:
enum Animation {
AppearAnimation = 0, /*<< Animate the appearance of an element */
DisappearAnimation, /*<< Animate the disappearance of an element */
@ -78,19 +76,7 @@ public:
PendularCurve
};
enum Movement {
SlideInMovement = 0,
SlideOutMovement,
FastSlideInMovement,
FastSlideOutMovement
};
/**
* Singleton accessor
**/
#ifndef KDE_NO_DEPRECATED
static KDE_DEPRECATED Animator *self();
#endif
explicit Animator(QObject *parent = 0);
/**
* Factory to build new animation objects. To control their behavior,
@ -112,168 +98,7 @@ public:
*/
static QEasingCurve create(Animator::CurveShape type);
/**
* Starts a standard animation on a QGraphicsItem.
*
* @param item the item to animate in some fashion
* @param anim the type of animation to perform
* @return the id of the animation
* @deprecated use new Animator API with Qt Kinetic
**/
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED Q_INVOKABLE int animateItem(QGraphicsItem *item,Animation anim);
#endif
/**
* Stops an item animation before the animation is complete.
* Note that it is not necessary to call
* this on normal completion of the animation.
*
* @param id the id of the animation as returned by animateItem
* @deprecated use new Animator API with Qt Kinetic
*/
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED Q_INVOKABLE void stopItemAnimation(int id);
#endif
/**
* Starts a standard animation on a QGraphicsItem.
*
* @param item the item to animate in some fashion
* @param anim the type of animation to perform
* @return the id of the animation
* @deprecated use new Animator API with Qt Kinetic
**/
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED Q_INVOKABLE int moveItem(QGraphicsItem *item, Movement movement, const QPoint &destination);
#endif
/**
* Stops an item movement before the animation is complete.
* Note that it is not necessary to call
* this on normal completion of the animation.
*
* @param id the id of the animation as returned by moveItem
* @deprecated use new Animator API with Qt Kinetic
*/
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED Q_INVOKABLE void stopItemMovement(int id);
#endif
/**
* Starts a custom animation, preventing the need to create a timeline
* with its own timer tick.
*
* @param frames the number of frames this animation should persist for
* @param duration the length, in milliseconds, the animation will take
* @param curve the curve applied to the frame rate
* @param receive the object that will handle the actual animation
* @param method the method name of slot to be invoked on each update.
* It must take a qreal. So if the slot is animate(qreal),
* pass in "animate" as the method parameter.
* It has an optional integer paramenter that takes an
* integer that reapresents the animation id, useful if
* you want to manage multiple animations with a sigle slot
*
* @return an id that can be used to identify this animation.
* @deprecated use new Animator API with Qt Kinetic
*/
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED Q_INVOKABLE int customAnimation(int frames, int duration,
Animator::CurveShape curve, QObject *receiver, const char *method);
#endif
/**
* Stops a custom animation. Note that it is not necessary to call
* this on object destruction, as custom animations associated with
* a given QObject are cleaned up automatically on QObject destruction.
*
* @param id the id of the animation as returned by customAnimation
* @deprecated use new Animator API with Qt Kinetic
*/
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED Q_INVOKABLE void stopCustomAnimation(int id);
#endif
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED Q_INVOKABLE int animateElement(QGraphicsItem *obj, Animation);
#endif
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED Q_INVOKABLE void stopElementAnimation(int id);
#endif
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED Q_INVOKABLE void setInitialPixmap(int id, const QPixmap &pixmap);
#endif
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED Q_INVOKABLE QPixmap currentPixmap(int id);
#endif
/**
* Can be used to query if there are other animations happening. This way
* heavy operations can be delayed until all animations are finished.
* @return true if there are animations going on.
* @since 4.1
* @deprecated use new Animator API with Qt Kinetic
*/
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED Q_INVOKABLE bool isAnimating() const;
#endif
/**
* Register a widget as a scrolling widget.
* This function is deprecated:
* use a ScrollWidget, with setWidget() as your widget instead.
*
* @param widget the widget that offers a scrolling behaviour
* @since 4.4
*/
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED void registerScrollingManager(QGraphicsWidget *widget);
#endif
/**
* unregister the scrolling manager of a certain widget
* This function is deprecated: use ScrollWidget instead.
*
* @param widget the widget we don't want no longer animated
* @since 4.4
*/
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED void unregisterScrollingManager(QGraphicsWidget *widget);
#endif
Q_SIGNALS:
void animationFinished(QGraphicsItem *item, Plasma::Animator::Animation anim);
void movementFinished(QGraphicsItem *item);
void elementAnimationFinished(int id);
void customAnimationFinished(int id);
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED void scrollStateChanged(QGraphicsWidget *widget, QAbstractAnimation::State newState,
QAbstractAnimation::State oldState);
#endif
#ifndef KDE_NO_DEPRECATED
protected:
void timerEvent(QTimerEvent *event);
#endif
private:
#ifndef KDE_NO_DEPRECATED
friend class AnimatorSingleton;
explicit Animator(QObject * parent = 0);
~Animator();
Q_PRIVATE_SLOT(d, void animatedItemDestroyed(QObject*))
Q_PRIVATE_SLOT(d, void movingItemDestroyed(QObject*))
Q_PRIVATE_SLOT(d, void animatedElementDestroyed(QObject*))
Q_PRIVATE_SLOT(d, void customAnimReceiverDestroyed(QObject*))
Q_PRIVATE_SLOT(d, void scrollStateChanged(QAbstractAnimation::State,
QAbstractAnimation::State))
#else
Animator();
#endif
friend class AnimatorPrivate;
AnimatorPrivate * const d;
};

View File

@ -70,7 +70,6 @@
#endif
#include "abstracttoolbox.h"
#include "authorizationmanager.h"
#include "authorizationrule.h"
#include "configloader.h"
#include "containment.h"
@ -88,6 +87,8 @@
#include "private/applethandle_p.h"
#include "private/extenderitem_p.h"
#include "private/framesvg_p.h"
#include "remote/authorizationmanager.h"
#include "remote/authorizationmanager_p.h"
#include "theme.h"
#include "view.h"
#include "widgets/iconwidget.h"
@ -101,7 +102,6 @@
#include "pluginloader.h"
#include "private/associatedapplicationmanager_p.h"
#include "private/authorizationmanager_p.h"
#include "private/containment_p.h"
#include "private/extenderapplet_p.h"
#include "private/package_p.h"
@ -223,15 +223,6 @@ Applet::~Applet()
delete d;
}
PackageStructure::Ptr Applet::packageStructure()
{
if (!AppletPrivate::packageStructure) {
AppletPrivate::packageStructure = new PlasmoidPackage();
}
return AppletPrivate::packageStructure;
}
void Applet::init()
{
setFlag(ItemIsMovable, true);
@ -273,8 +264,6 @@ void Applet::save(KConfigGroup &g) const
return;
}
//FIXME: for containments, we need to have some special values here w/regards to
// screen affinity (e.g. "bottom of screen 0")
//kDebug() << pluginName() << "geometry is" << geometry()
// << "pos is" << pos() << "bounding rect is" << boundingRect();
if (transform() == QTransform()) {
@ -329,8 +318,12 @@ void Applet::restore(KConfigGroup &group)
if (!shortcutText.isEmpty()) {
setGlobalShortcut(KShortcut(shortcutText));
/*
#ifndef NDEBUG
kDebug() << "got global shortcut for" << name() << "of" << QKeySequence(shortcutText);
#endif
#ifndef NDEBUG
kDebug() << "set to" << d->activationAction->objectName()
#endif
<< d->activationAction->globalShortcut().primary();
*/
}
@ -387,7 +380,7 @@ void Applet::setFailedToLaunch(bool failed, const QString &reason)
setLayout(0);
if (failed) {
setBackgroundHints(d->backgroundHints|StandardBackground);
setBackgroundHints(StandardBackground);
QGraphicsLinearLayout *failureLayout = new QGraphicsLinearLayout(this);
failureLayout->setContentsMargins(0, 0, 0, 0);
@ -671,18 +664,16 @@ ConfigLoader *Applet::configScheme() const
DataEngine *Applet::dataEngine(const QString &name) const
{
if (!d->remoteLocation.isEmpty()) {
return d->remoteDataEngine(KUrl(d->remoteLocation), name);
} else if (!package() || package()->metadata().remoteLocation().isEmpty()) {
if (d->remoteLocation.isEmpty()) {
return d->dataEngine(name);
} else {
return d->remoteDataEngine(KUrl(package()->metadata().remoteLocation()), name);
return d->remoteDataEngine(d->remoteLocation, name);
}
}
const Package *Applet::package() const
Package Applet::package() const
{
return d->package;
return d->package ? *d->package : Package();
}
QGraphicsView *Applet::view() const
@ -922,12 +913,12 @@ void Applet::setImmutability(const ImmutabilityType immutable)
updateConstraints(ImmutableConstraint);
}
Applet::BackgroundHints Applet::backgroundHints() const
BackgroundHints Applet::backgroundHints() const
{
return d->backgroundHints;
}
void Applet::setBackgroundHints(const BackgroundHints hints)
void Applet::setBackgroundHints(const Plasma::BackgroundHints hints)
{
if (d->backgroundHints == hints) {
return;
@ -983,17 +974,6 @@ bool Applet::hasFailedToLaunch() const
return d->failed;
}
void Applet::paintWindowFrame(QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(painter)
Q_UNUSED(option)
Q_UNUSED(widget)
//Here come the code for the window frame
//kDebug() << windowFrameGeometry();
//painter->drawRoundedRect(windowFrameGeometry(), 5, 5);
}
bool Applet::configurationRequired() const
{
return d->needsConfig;
@ -1611,13 +1591,6 @@ Location Applet::location() const
return c ? c->d->location : Plasma::Desktop;
}
Context *Applet::context() const
{
Containment *c = containment();
Q_ASSERT(c);
return c->d->context();
}
Plasma::AspectRatioMode Applet::aspectRatioMode() const
{
return d->aspectRatioMode;
@ -1669,46 +1642,39 @@ bool Applet::hasConfigurationInterface() const
void Applet::publish(AnnouncementMethods methods, const QString &resourceName)
{
if (d->package) {
d->package->d->publish(methods);
} else if (d->appletDescription.isValid()) {
if (!d->service) {
d->service = new PlasmoidService(this);
}
kDebug() << "publishing package under name " << resourceName;
PackageMetadata pm;
pm.setName(d->appletDescription.name());
pm.setDescription(d->appletDescription.comment());
pm.setIcon(d->appletDescription.icon());
d->service->d->publish(methods, resourceName, pm);
const QString resName = resourceName.isEmpty() ? i18nc("%1 is the name of a plasmoid, %2 the name of the machine that plasmoid is published on",
"%1 on %2", name(), QHostInfo::localHostName())
: resourceName;
#ifndef NDEBUG
kDebug() << "publishing package under name " << resName;
#endif
if (d->package && d->package->isValid()) {
d->service->d->publish(methods, resName, d->package->metadata());
} else if (!d->package && d->appletDescription.isValid()) {
d->service->d->publish(methods, resName, d->appletDescription);
} else {
delete d->service;
d->service = 0;
#ifndef NDEBUG
kDebug() << "Can not publish invalid applets.";
#endif
}
}
void Applet::unpublish()
{
if (d->package) {
d->package->d->unpublish();
} else {
if (d->service) {
d->service->d->unpublish();
}
}
}
bool Applet::isPublished() const
{
if (d->package) {
return d->package->d->isPublished();
} else {
if (d->service) {
return d->service->d->isPublished();
} else {
return false;
}
}
return d->service && d->service->d->isPublished();
}
void Applet::setHasConfigurationInterface(bool hasInterface)
@ -1761,11 +1727,6 @@ KActionCollection* AppletPrivate::defaultActions(QObject *parent)
return actions;
}
bool Applet::eventFilter(QObject *o, QEvent *e)
{
return QObject::eventFilter(o, e);
}
bool Applet::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
{
if (watched == this) {
@ -2247,14 +2208,14 @@ QString AppletPrivate::parentAppConstraint(const QString &parentApp)
KPluginInfo::List Applet::listAppletInfo(const QString &category, const QString &parentApp)
{
return PluginLoader::pluginLoader()->listAppletInfo(category, parentApp);
return PluginLoader::self()->listAppletInfo(category, parentApp);
}
KPluginInfo::List Applet::listAppletInfoForMimetype(const QString &mimetype)
KPluginInfo::List Applet::listAppletInfoForMimeType(const QString &mimeType)
{
QString constraint = AppletPrivate::parentAppConstraint();
constraint.append(QString(" and '%1' in [X-Plasma-DropMimeTypes]").arg(mimetype));
//kDebug() << "listAppletInfoForMimetype with" << mimetype << constraint;
constraint.append(QString(" and '%1' in [X-Plasma-DropMimeTypes]").arg(mimeType));
//kDebug() << "listAppletInfoForMimetype with" << mimeType << constraint;
KService::List offers = KServiceTypeTrader::self()->query("Plasma/Applet", constraint);
AppletPrivate::filterOffers(offers);
return KPluginInfo::fromServices(offers);
@ -2275,7 +2236,9 @@ KPluginInfo::List Applet::listAppletInfoForUrl(const QUrl &url)
QRegExp rx(glob);
rx.setPatternSyntax(QRegExp::Wildcard);
if (rx.exactMatch(url.toString())) {
#ifndef NDEBUG
kDebug() << info.name() << "matches" << glob << url;
#endif
filtered << info;
}
}
@ -2309,8 +2272,10 @@ QStringList Applet::listCategories(const QString &parentApp, bool visibleOnly)
//kDebug() << " and we have " << appletCategory;
if (!appletCategory.isEmpty() && !known.contains(appletCategory.toLower())) {
#ifndef NDEBUG
kDebug() << "Unknown category: " << applet->name() << "says it is in the"
<< appletCategory << "category which is unknown to us";
#endif
appletCategory.clear();
}
@ -2341,7 +2306,7 @@ Applet *Applet::loadPlasmoid(const QString &path, uint appletId, const QVariantL
{
if (QFile::exists(path + "/metadata.desktop")) {
KService service(path + "/metadata.desktop");
const QStringList& types = service.serviceTypes();
const QStringList &types = service.serviceTypes();
if (types.contains("Plasma/Containment")) {
return new Containment(path, appletId, args);
@ -2355,20 +2320,6 @@ Applet *Applet::loadPlasmoid(const QString &path, uint appletId, const QVariantL
return 0;
}
Applet *Applet::load(const QString &appletName, uint appletId, const QVariantList &args)
{
return PluginLoader::pluginLoader()->loadApplet(appletName, appletId, args);
}
Applet *Applet::load(const KPluginInfo &info, uint appletId, const QVariantList &args)
{
if (!info.isValid()) {
return 0;
}
return load(info.pluginName(), appletId, args);
}
QVariant Applet::itemChange(GraphicsItemChange change, const QVariant &value)
{
QVariant ret = QGraphicsWidget::itemChange(change, value);
@ -2591,8 +2542,8 @@ AppletPrivate::AppletPrivate(KService::Ptr service, const KPluginInfo *info, int
: appletId(uniqueID),
q(applet),
service(0),
preferredBackgroundHints(Applet::StandardBackground),
backgroundHints(Applet::NoBackground),
preferredBackgroundHints(StandardBackground),
backgroundHints(NoBackground),
aspectRatioMode(Plasma::KeepAspectRatio),
immutability(Mutable),
appletDescription(info ? *info : KPluginInfo(service)),
@ -2659,7 +2610,7 @@ void AppletPrivate::init(const QString &packagePath)
//set a default size before any saved settings are read
QSize size(200, 200);
q->setBackgroundHints(Applet::DefaultBackground);
q->setBackgroundHints(DefaultBackground);
q->setHasConfigurationInterface(true); //FIXME why not default it to true in the constructor?
QAction *closeApplet = actions->action("remove");
@ -2674,9 +2625,11 @@ void AppletPrivate::init(const QString &packagePath)
QObject::connect(q, SIGNAL(activate()), q, SLOT(setFocus()));
if (!appletDescription.isValid()) {
#ifndef NDEBUG
kDebug() << "Check your constructor! "
<< "You probably want to be passing in a Service::Ptr "
<< "or a QVariantList with a valid storageid as arg[0].";
#endif
q->resize(size);
return;
}
@ -2691,11 +2644,18 @@ void AppletPrivate::init(const QString &packagePath)
QString api = appletDescription.property("X-Plasma-API").toString();
// we have a scripted plasmoid
if (!api.isEmpty()) {
if (api.isEmpty()) {
q->setFailedToLaunch(true, i18n("The %2 widget did not define which ScriptEngine to use.", appletDescription.name()));
return;
}
package = new Package(PluginLoader::self()->loadPackage("Plasma/Applet", api));
// find where the Package is
QString path = packagePath;
if (path.isEmpty()) {
QString subPath = q->packageStructure()->defaultPackageRoot() + '/' + appletDescription.pluginName() + '/';
QString subPath = package->defaultPackageRoot() + appletDescription.pluginName() + '/';
path = KStandardDirs::locate("data", subPath + "metadata.desktop");
if (path.isEmpty()) {
path = KStandardDirs::locate("data", subPath);
@ -2707,19 +2667,28 @@ void AppletPrivate::init(const QString &packagePath)
}
if (path.isEmpty()) {
q->setFailedToLaunch(
true,
delete package;
package = 0;
q->setFailedToLaunch(true,
i18nc("Package file, name of the widget",
"Could not locate the %1 package required for the %2 widget.",
appletDescription.pluginName(), appletDescription.name()));
} else {
return;
}
package->setPath(path);
if (!package->isValid()) {
delete package;
package = 0;
q->setFailedToLaunch(true, i18nc("Package file, name of the widget",
"Could not open the %1 package required for the %2 widget.",
appletDescription.pluginName(), appletDescription.name()));
return;
}
// create the package and see if we have something real
//kDebug() << "trying for" << path;
PackageStructure::Ptr structure = Plasma::packageStructure(api, Plasma::AppletComponent);
structure->setPath(path);
package = new Package(path, structure);
if (package->isValid()) {
// now we try and set up the script engine.
// it will be parented to this applet and so will get
// deleted when the applet does
@ -2733,15 +2702,6 @@ void AppletPrivate::init(const QString &packagePath)
"Could not create a %1 ScriptEngine for the %2 widget.",
api, appletDescription.name()));
}
} else {
q->setFailedToLaunch(true, i18nc("Package file, name of the widget",
"Could not open the %1 package required for the %2 widget.",
appletDescription.pluginName(), appletDescription.name()));
delete package;
package = 0;
}
}
}
}
// put all setup routines for script here. at this point we can assume that
@ -2752,19 +2712,18 @@ void AppletPrivate::setupScriptSupport()
return;
}
#ifndef NDEBUG
kDebug() << "setting up script support, package is in" << package->path()
<< "which is a" << package->structure()->type() << "package"
<< ", main script is" << package->filePath("mainscript");
#endif
QString translationsPath = package->filePath("translations");
const QString translationsPath = package->filePath("translations");
if (!translationsPath.isEmpty()) {
//FIXME: we should _probably_ use a KComponentData to segregate the applets
// from each other; but I want to get the basics working first :)
KGlobal::dirs()->addResourceDir("locale", translationsPath);
KGlobal::locale()->insertCatalog(package->metadata().pluginName());
KGlobal::locale()->insertCatalog(appletDescription.pluginName());
}
QString xmlPath = package->filePath("mainconfigxml");
const QString xmlPath = package->filePath("mainconfigxml");
if (!xmlPath.isEmpty()) {
QFile file(xmlPath);
KConfigGroup config = q->config();
@ -2874,9 +2833,11 @@ KConfigGroup *AppletPrivate::mainConfigGroup()
if (newGroup) {
//see if we have a default configuration in our package
const QString defaultConfigFile = q->package()->filePath("defaultconfig");
const QString defaultConfigFile = package->filePath("defaultconfig");
if (!defaultConfigFile.isEmpty()) {
kDebug() << "copying default config: " << q->package()->filePath("defaultconfig");
#ifndef NDEBUG
kDebug() << "copying default config: " << package->filePath("defaultconfig");
#endif
KConfigGroup defaultConfig(KSharedConfig::openConfig(defaultConfigFile)->group("Configuration"));
defaultConfig.copyTo(mainConfig);
}
@ -2950,7 +2911,6 @@ void ContainmentPrivate::checkRemoveAction()
uint AppletPrivate::s_maxAppletId = 0;
int AppletPrivate::s_maxZValue = 0;
int AppletPrivate::s_minZValue = 0;
PackageStructure::Ptr AppletPrivate::packageStructure(0);
QSet<QString> AppletPrivate::s_customCategories;
AppletOverlayWidget::AppletOverlayWidget(QGraphicsWidget *parent)
@ -3003,7 +2963,7 @@ void AppletOverlayWidget::paint(QPainter *painter,
QPainterPath backgroundShape;
if (!applet || applet->backgroundHints() & Applet::StandardBackground) {
if (!applet || applet->backgroundHints() == StandardBackground) {
//FIXME: a resize here is nasty, but perhaps still better than an eventfilter just for that..
if (parentWidget()->contentsRect().size() != size()) {
resize(parentWidget()->contentsRect().size());
@ -3017,14 +2977,6 @@ void AppletOverlayWidget::paint(QPainter *painter,
painter->fillPath(backgroundShape, wash);
}
#if QT_VERSION >= 0x040700
// in QGraphicsWidget now; preserve BC by implementing it as a protected method
void Applet::geometryChanged()
{
emit QGraphicsWidget::geometryChanged();
}
#endif
} // Plasma namespace
#include "applet.moc"

View File

@ -32,7 +32,6 @@
#include <kshortcut.h>
#include <plasma/configloader.h>
#include <plasma/packagestructure.h>
#include <plasma/plasma.h>
#include <plasma/animator.h>
#include <plasma/version.h>
@ -49,7 +48,6 @@ namespace Plasma
class AppletPrivate;
class Containment;
class Context;
class DataEngine;
class Extender;
class ExtenderItem;
@ -83,41 +81,20 @@ class PLASMA_EXPORT Applet : public QGraphicsWidget
Q_PROPERTY(QString category READ category)
Q_PROPERTY(ImmutabilityType immutability READ immutability WRITE setImmutability)
Q_PROPERTY(bool hasFailedToLaunch READ hasFailedToLaunch WRITE setFailedToLaunch)
Q_PROPERTY(bool isBusy READ isBusy WRITE setBusy) //KDE5: remove
Q_PROPERTY(bool busy READ isBusy WRITE setBusy)
Q_PROPERTY(bool configurationRequired READ configurationRequired WRITE setConfigurationRequired)
Q_PROPERTY(QRectF geometry READ geometry WRITE setGeometry)
Q_PROPERTY(bool shouldConserveResources READ shouldConserveResources)
Q_PROPERTY(uint id READ id)
Q_PROPERTY(bool userConfiguring READ isUserConfiguring)
Q_PROPERTY(BackgroundHints backgroundHints READ backgroundHints WRITE setBackgroundHints)
Q_ENUMS(BackgroundHints)
Q_PROPERTY(bool userConfiguring READ isUserConfiguring)
public:
typedef QList<Applet*> List;
typedef QHash<QString, Applet*> Dict;
/**
* Description on how draw a background for the applet
*/
enum BackgroundHint {
NoBackground = 0, /**< Not drawing a background under the
applet, the applet has its own implementation */
StandardBackground = 1, /**< The standard background from the theme is drawn */
TranslucentBackground = 2, /**< An alternate version of the background is drawn,
usually more translucent */
DefaultBackground = StandardBackground /**< Default settings:
both standard background */
};
Q_DECLARE_FLAGS(BackgroundHints, BackgroundHint)
~Applet();
/**
* @return a package structure representing an Applet
*/
static PackageStructure::Ptr packageStructure();
/**
* @return the id of this applet
*/
@ -205,7 +182,7 @@ class PLASMA_EXPORT Applet : public QGraphicsWidget
*
* @return the Package object, or 0 if none
**/
const Package *package() const;
Package package() const;
/**
* Returns the view this widget is visible on, or 0 if none can be found.
@ -270,11 +247,6 @@ class PLASMA_EXPORT Applet : public QGraphicsWidget
*/
virtual Location location() const;
/**
* Returns the workspace context which the applet is operating in
*/
Context *context() const;
/**
* @return the preferred aspect ratio mode for placement and resizing
*/
@ -310,7 +282,7 @@ class PLASMA_EXPORT Applet : public QGraphicsWidget
*
* @return list of applets
**/
static KPluginInfo::List listAppletInfoForMimetype(const QString &mimetype);
static KPluginInfo::List listAppletInfoForMimeType(const QString &mimetype);
/**
* Returns a list of all known applets associated with a certain URL.
@ -365,38 +337,6 @@ class PLASMA_EXPORT Applet : public QGraphicsWidget
static Applet *loadPlasmoid(const QString &path, uint appletId = 0,
const QVariantList &args = QVariantList());
/**
* Attempts to load an applet
*
* Returns a pointer to the applet if successful.
* The caller takes responsibility for the applet, including
* deleting it when no longer needed.
*
* @param name the plugin name, as returned by KPluginInfo::pluginName()
* @param appletId unique ID to assign the applet, or zero to have one
* assigned automatically.
* @param args to send the applet extra arguments
* @return a pointer to the loaded applet, or 0 on load failure
**/
static Applet *load(const QString &name, uint appletId = 0,
const QVariantList &args = QVariantList());
/**
* Attempts to load an applet
*
* Returns a pointer to the applet if successful.
* The caller takes responsibility for the applet, including
* deleting it when no longer needed.
*
* @param info KPluginInfo object for the desired applet
* @param appletId unique ID to assign the applet, or zero to have one
* assigned automatically.
* @param args to send the applet extra arguments
* @return a pointer to the loaded applet, or 0 on load failure
**/
static Applet *load(const KPluginInfo &info, uint appletId = 0,
const QVariantList &args = QVariantList());
/**
* Get the category of the given applet
*
@ -465,9 +405,6 @@ class PLASMA_EXPORT Applet : public QGraphicsWidget
*/
ImmutabilityType immutability() const;
void paintWindowFrame(QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget);
/**
* If for some reason, the applet fails to get up on its feet (the
* library couldn't be loaded, necessary hardware support wasn't found,
@ -517,13 +454,13 @@ class PLASMA_EXPORT Applet : public QGraphicsWidget
*
* @param hints the BackgroundHint combination for this applet
*/
void setBackgroundHints(const BackgroundHints hints);
void setBackgroundHints(const Plasma::BackgroundHints hint);
/**
* @return BackgroundHints flags combination telling if the standard background is shown
* and if it has a drop shadow
*/
BackgroundHints backgroundHints() const;
Plasma::BackgroundHints backgroundHints() const;
/**
* @return true if this Applet is currently being used as a Containment, false otherwise
@ -726,18 +663,6 @@ class PLASMA_EXPORT Applet : public QGraphicsWidget
*/
void releaseVisualFocus();
#if QT_VERSION >= 0x040700
protected:
void geometryChanged(); // in QGraphicsWidget now; preserve BC
#else
/**
* Emitted whenever the applet makes a geometry change, so that views
* can coordinate themselves with these changes if they desire.
*/
void geometryChanged();
#endif
Q_SIGNALS:
/**
* Emitted when the user completes a transformation of the applet.
*/
@ -1045,15 +970,10 @@ class PLASMA_EXPORT Applet : public QGraphicsWidget
*/
Extender *extender() const;
/**
* @internal event filter; used for focus watching
**/
bool eventFilter(QObject *o, QEvent *e);
/**
* @internal scene event filter; used to manage applet dragging
*/
bool sceneEventFilter (QGraphicsItem *watched, QEvent *event);
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event);
/**
* @internal manage the mouse movement to drag the applet around
@ -1156,8 +1076,6 @@ class PLASMA_EXPORT Applet : public QGraphicsWidget
} // Plasma namespace
Q_DECLARE_OPERATORS_FOR_FLAGS(Plasma::Applet::BackgroundHints)
/**
* Register an applet when it is contained in a loadable module
*/

View File

@ -54,12 +54,12 @@
#include "abstracttoolbox.h"
#include "animator.h"
#include "context.h"
#include "containmentactions.h"
#include "containmentactionspluginsconfig.h"
#include "corona.h"
#include "extender.h"
#include "extenderitem.h"
#include "pluginloader.h"
#include "svg.h"
#include "wallpaper.h"
@ -295,11 +295,15 @@ bool appletConfigLessThan(const KConfigGroup &c1, const KConfigGroup &c2)
void Containment::restore(KConfigGroup &group)
{
/*kDebug() << "!!!!!!!!!!!!initConstraints" << group.name() << d->type;
/*
#ifndef NDEBUG
kDebug() << "!!!!!!!!!!!!initConstraints" << group.name() << d->type;
kDebug() << " location:" << group.readEntry("location", (int)d->location);
kDebug() << " geom:" << group.readEntry("geometry", geometry());
kDebug() << " formfactor:" << group.readEntry("formfactor", (int)d->formFactor);
kDebug() << " screen:" << group.readEntry("screen", d->screen);*/
kDebug() << " screen:" << group.readEntry("screen", d->screen);
#endif
*/
if (!isContainment()) {
Applet::restore(group);
return;
@ -330,11 +334,7 @@ void Containment::restore(KConfigGroup &group)
d->lastScreen = group.readEntry("lastScreen", d->lastScreen);
d->lastDesktop = group.readEntry("lastDesktop", d->lastDesktop);
d->setScreen(group.readEntry("screen", d->screen), group.readEntry("desktop", d->desktop), false);
QString activityId = group.readEntry("activityId", QString());
if (!activityId.isEmpty()) {
d->context()->setCurrentActivityId(activityId);
}
setActivity(group.readEntry("activity", QString()));
d->activityId = group.readEntry("activityId", QString());
flushPendingConstraintsEvents();
restoreContents(group);
@ -343,7 +343,9 @@ void Containment::restore(KConfigGroup &group)
setWallpaper(group.readEntry("wallpaperplugin", defaultWallpaper),
group.readEntry("wallpaperpluginmode", defaultWallpaperMode));
QMetaObject::invokeMethod(d->toolBox.data(), "restore", Q_ARG(KConfigGroup, group));
if (d->toolBox) {
d->toolBox.data()->restore(group);
}
KConfigGroup cfg;
if (containmentType() == PanelContainment || containmentType() == CustomPanelContainment) {
@ -353,13 +355,13 @@ void Containment::restore(KConfigGroup &group)
d->containmentActionsSource = ContainmentPrivate::Local;
cfg = KConfigGroup(&group, "ActionPlugins");
} else {
QString source = group.readEntry("ActionPluginsSource", QString());
const QString source = group.readEntry("ActionPluginsSource", QString());
if (source == "Global") {
cfg = KConfigGroup(corona()->config(), "ActionPlugins");
d->containmentActionsSource = ContainmentPrivate::Global;
} else if (source == "Activity") {
cfg = KConfigGroup(corona()->config(), "Activities");
cfg = KConfigGroup(&cfg, activityId);
cfg = KConfigGroup(&cfg, d->activityId);
cfg = KConfigGroup(&cfg, "ActionPlugins");
d->containmentActionsSource = ContainmentPrivate::Activity;
} else if (source == "Local") {
@ -376,6 +378,7 @@ void Containment::restore(KConfigGroup &group)
group.writeEntry("ActionPluginsSource", "Global");
}
}
//kDebug() << cfg.keyList();
if (cfg.exists()) {
foreach (const QString &key, cfg.keyList()) {
@ -393,7 +396,9 @@ void Containment::restore(KConfigGroup &group)
}
/*
#ifndef NDEBUG
kDebug() << "Containment" << id() <<
#endif
"screen" << screen() <<
"geometry is" << geometry() <<
"wallpaper" << ((d->wallpaper) ? d->wallpaper->pluginName() : QString()) <<
@ -426,11 +431,11 @@ void Containment::save(KConfigGroup &g) const
group.writeEntry("lastDesktop", d->lastDesktop);
group.writeEntry("formfactor", (int)d->formFactor);
group.writeEntry("location", (int)d->location);
group.writeEntry("activity", d->context()->currentActivity());
group.writeEntry("activityId", d->context()->currentActivityId());
group.writeEntry("activityId", d->activityId);
QMetaObject::invokeMethod(d->toolBox.data(), "save", Q_ARG(KConfigGroup, group));
if (d->toolBox) {
d->toolBox.data()->save(group);
}
if (d->wallpaper) {
@ -461,7 +466,9 @@ void ContainmentPrivate::initApplets()
foreach (Applet *applet, applets) {
applet->restore(*applet->d->mainConfigGroup());
applet->init();
#ifndef NDEBUG
kDebug() << "!!{} STARTUP TIME" << QTime().msecsTo(QTime::currentTime()) << "Applet" << applet->name();
#endif
}
q->flushPendingConstraintsEvents();
@ -470,7 +477,9 @@ void ContainmentPrivate::initApplets()
applet->flushPendingConstraintsEvents();
}
#ifndef NDEBUG
kDebug() << "!!{} STARTUP TIME" << QTime().msecsTo(QTime::currentTime()) << "Containment's applets initialized" << q->name();
#endif
}
void Containment::restoreContents(KConfigGroup &group)
@ -783,7 +792,9 @@ void Containment::setFormFactor(FormFactor formFactor)
d->positionPanel(true);
}
QMetaObject::invokeMethod(d->toolBox.data(), "reposition");
if (d->toolBox) {
d->toolBox.data()->reposition();
}
updateConstraints(Plasma::FormFactorConstraint);
@ -856,12 +867,16 @@ void Containment::addApplet(Applet *applet, const QPointF &pos, bool delayInit)
}
if (!applet) {
#ifndef NDEBUG
kDebug() << "adding null applet!?!";
#endif
return;
}
if (d->applets.contains(applet)) {
#ifndef NDEBUG
kDebug() << "already have this applet!";
#endif
}
Containment *currentContainment = applet->containment();
@ -999,10 +1014,12 @@ void ContainmentPrivate::setScreen(int newScreen, int newDesktop, bool preventIn
// sanity check to make sure someone else doesn't have this screen already!
Containment *currently = corona->containmentForScreen(newScreen, newDesktop);
if (currently && currently != q) {
#ifndef NDEBUG
kDebug() << "currently is on screen" << currently->screen()
<< "desktop" << currently->desktop()
<< "and is" << currently->activity()
<< (QObject*)currently << "i'm" << (QObject*)q;
#endif
currently->setScreen(-1, currently->desktop());
swapScreensWith = currently;
}
@ -1024,7 +1041,9 @@ void ContainmentPrivate::setScreen(int newScreen, int newDesktop, bool preventIn
if (oldScreen != newScreen || oldDesktop != newDesktop) {
/*
#ifndef NDEBUG
kDebug() << "going to signal change for" << q
#endif
<< ", old screen & desktop:" << oldScreen << oldDesktop
<< ", new:" << screen << desktop;
*/
@ -1116,10 +1135,10 @@ KPluginInfo::List Containment::listContainmentsOfType(const QString &type,
return KPluginInfo::fromServices(offers);
}
KPluginInfo::List Containment::listContainmentsForMimetype(const QString &mimetype)
KPluginInfo::List Containment::listContainmentsForMimeType(const QString &mimeType)
{
const QString constraint = QString("'%1' in [X-Plasma-DropMimeTypes]").arg(mimetype);
//kDebug() << mimetype << constraint;
const QString constraint = QString("'%1' in [X-Plasma-DropMimeTypes]").arg(mimeType);
//kDebug() << mimeType << constraint;
const KService::List offers = KServiceTypeTrader::self()->query("Plasma/Containment", constraint);
return KPluginInfo::fromServices(offers);
}
@ -1152,7 +1171,7 @@ void Containment::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
QStringList formats = event->mimeData()->formats();
foreach (const QString &format, formats) {
KPluginInfo::List appletList = Applet::listAppletInfoForMimetype(format);
KPluginInfo::List appletList = Applet::listAppletInfoForMimeType(format);
if (!appletList.isEmpty()) {
event->setAccepted(true);
break;
@ -1250,7 +1269,9 @@ void ContainmentPrivate::dropData(QPointF scenePos, QPoint screenPos, QGraphicsS
if (!mimeData) {
//Selection is either empty or not supported on this OS
#ifndef NDEBUG
kDebug() << "no mime data";
#endif
return;
}
@ -1270,13 +1291,17 @@ void ContainmentPrivate::dropData(QPointF scenePos, QPoint screenPos, QGraphicsS
dropEvent->acceptProposedAction();
}
} else if (mimeData->hasFormat(ExtenderItemMimeData::mimeType())) {
kDebug() << "mimetype plasma/extenderitem is dropped, creating internal:extender";
#ifndef NDEBUG
kDebug() << "mimeType plasma/extenderitem is dropped, creating internal:extender";
#endif
//Handle dropping extenderitems.
const ExtenderItemMimeData *extenderData = qobject_cast<const ExtenderItemMimeData*>(mimeData);
if (extenderData) {
ExtenderItem *item = extenderData->extenderItem();
QRectF geometry(pos - extenderData->pointerOffset(), item->size());
#ifndef NDEBUG
kDebug() << "desired geometry: " << geometry;
#endif
Applet *applet = qobject_cast<ExtenderApplet *>(item->extender() ? item->extender()->applet() : 0);
if (applet) {
qreal left, top, right, bottom;
@ -1296,7 +1321,7 @@ void ContainmentPrivate::dropData(QPointF scenePos, QPoint screenPos, QGraphicsS
item->setExtender(applet->extender());
}
} else if (KUrl::List::canDecode(mimeData)) {
//TODO: collect the mimetypes of available script engines and offer
//TODO: collect the mimeTypes of available script engines and offer
// to create widgets out of the matching URLs, if any
const KUrl::List urls = KUrl::List::fromMimeData(mimeData);
foreach (const KUrl &url, urls) {
@ -1317,7 +1342,9 @@ void ContainmentPrivate::dropData(QPointF scenePos, QPoint screenPos, QGraphicsS
QRectF geom(pos, QSize());
QVariantList args;
args << url.url();
#ifndef NDEBUG
kDebug() << "can decode" << mimeName << args;
#endif
// It may be a directory or a file, let's stat
KIO::JobFlags flags = KIO::HideProgressInfo;
@ -1329,7 +1356,7 @@ void ContainmentPrivate::dropData(QPointF scenePos, QPoint screenPos, QGraphicsS
}
QObject::connect(job, SIGNAL(result(KJob*)), q, SLOT(dropJobResult(KJob*)));
QObject::connect(job, SIGNAL(mimetype(KIO::Job *, const QString&)),
QObject::connect(job, SIGNAL(mimeType(KIO::Job *, const QString&)),
q, SLOT(mimeTypeRetrieved(KIO::Job *, const QString&)));
KMenu *choices = new KMenu("Content dropped");
@ -1354,7 +1381,7 @@ void ContainmentPrivate::dropData(QPointF scenePos, QPoint screenPos, QGraphicsS
QHash<QString, QString> pluginFormats;
foreach (const QString &format, formats) {
KPluginInfo::List plugins = Applet::listAppletInfoForMimetype(format);
KPluginInfo::List plugins = Applet::listAppletInfoForMimeType(format);
foreach (const KPluginInfo &plugin, plugins) {
if (seenPlugins.contains(plugin.pluginName())) {
@ -1417,7 +1444,9 @@ void ContainmentPrivate::dropData(QPointF scenePos, QPoint screenPos, QGraphicsS
QRectF geom(pos, QSize());
QVariantList args;
args << tempFile.fileName();
#ifndef NDEBUG
kDebug() << args;
#endif
tempFile.close();
q->addApplet(selectedPlugin, args, geom);
@ -1442,12 +1471,16 @@ void ContainmentPrivate::remoteAppletReady(Plasma::AccessAppletJob *job)
QPointF pos = dropPoints.take(job);
if (job->error()) {
//TODO: nice user visible error handling (knotification probably?)
#ifndef NDEBUG
kDebug() << "remote applet access failed: " << job->errorText();
#endif
return;
}
if (!job->applet()) {
#ifndef NDEBUG
kDebug() << "how did we end up here? if applet is null, the job->error should be nonzero";
#endif
return;
}
@ -1459,65 +1492,83 @@ void ContainmentPrivate::dropJobResult(KJob *job)
#ifndef PLASMA_NO_KIO
KIO::TransferJob* tjob = dynamic_cast<KIO::TransferJob*>(job);
if (!tjob) {
#ifndef NDEBUG
kDebug() << "job is not a KIO::TransferJob, won't handle the drop...";
#endif
clearDataForMimeJob(tjob);
return;
}
if (job->error()) {
#ifndef NDEBUG
kDebug() << "ERROR" << tjob->error() << ' ' << tjob->errorString();
#endif
}
// We call mimetypeRetrieved since there might be other mechanisms
// We call mimeTypeRetrieved since there might be other mechanisms
// for finding suitable applets. Cleanup happens there as well.
mimeTypeRetrieved(qobject_cast<KIO::Job *>(job), QString());
#endif // PLASMA_NO_KIO
}
void ContainmentPrivate::mimeTypeRetrieved(KIO::Job *job, const QString &mimetype)
void ContainmentPrivate::mimeTypeRetrieved(KIO::Job *job, const QString &mimeType)
{
#ifndef PLASMA_NO_KIO
kDebug() << "Mimetype Job returns." << mimetype;
#ifndef NDEBUG
kDebug() << "Mimetype Job returns." << mimeType;
#endif
KIO::TransferJob* tjob = dynamic_cast<KIO::TransferJob*>(job);
if (!tjob) {
#ifndef NDEBUG
kDebug() << "job should be a TransferJob, but isn't";
#endif
clearDataForMimeJob(job);
return;
}
KPluginInfo::List appletList = Applet::listAppletInfoForUrl(tjob->url());
if (mimetype.isEmpty() && !appletList.count()) {
if (mimeType.isEmpty() && !appletList.count()) {
clearDataForMimeJob(job);
kDebug() << "No applets found matching the url (" << tjob->url() << ") or the mimetype (" << mimetype << ")";
#ifndef NDEBUG
kDebug() << "No applets found matching the url (" << tjob->url() << ") or the mimeType (" << mimeType << ")";
#endif
return;
} else {
QPointF posi; // will be overwritten with the event's position
if (dropPoints.keys().contains(tjob)) {
posi = dropPoints[tjob];
#ifndef NDEBUG
kDebug() << "Received a suitable dropEvent at" << posi;
#endif
} else {
#ifndef NDEBUG
kDebug() << "Bailing out. Cannot find associated dropEvent related to the TransferJob";
#endif
clearDataForMimeJob(job);
return;
}
KMenu *choices = dropMenus.value(tjob);
if (!choices) {
#ifndef NDEBUG
kDebug() << "Bailing out. No QMenu found for this job.";
#endif
clearDataForMimeJob(job);
return;
}
QVariantList args;
args << tjob->url().url() << mimetype;
args << tjob->url().url() << mimeType;
kDebug() << "Creating menu for:" << mimetype << posi << args;
#ifndef NDEBUG
kDebug() << "Creating menu for:" << mimeType << posi << args;
#endif
appletList << Applet::listAppletInfoForMimetype(mimetype);
appletList << Applet::listAppletInfoForMimeType(mimeType);
KPluginInfo::List wallpaperList;
if (drawWallpaper) {
if (wallpaper && wallpaper->supportsMimetype(mimetype)) {
if (wallpaper && wallpaper->supportsMimetype(mimeType)) {
wallpaperList << wallpaper->d->wallpaperDescription;
} else {
wallpaperList = Wallpaper::listWallpaperInfoForMimetype(mimetype);
wallpaperList = Wallpaper::listWallpaperInfoForMimetype(mimeType);
}
}
@ -1526,7 +1577,9 @@ void ContainmentPrivate::mimeTypeRetrieved(KIO::Job *job, const QString &mimetyp
QHash<QAction *, QString> actionsToApplets;
choices->addTitle(i18n("Widgets"));
foreach (const KPluginInfo &info, appletList) {
#ifndef NDEBUG
kDebug() << info.name();
#endif
QAction *action;
if (!info.icon().isEmpty()) {
action = choices->addAction(KIcon(info.icon()), info.name());
@ -1535,7 +1588,9 @@ void ContainmentPrivate::mimeTypeRetrieved(KIO::Job *job, const QString &mimetyp
}
actionsToApplets.insert(action, info.pluginName());
#ifndef NDEBUG
kDebug() << info.pluginName();
#endif
}
actionsToApplets.insert(choices->addAction(i18n("Icon")), "icon");
@ -1565,7 +1620,7 @@ void ContainmentPrivate::mimeTypeRetrieved(KIO::Job *job, const QString &mimetyp
// Put the job on hold so it can be recycled to fetch the actual content,
// which is to be expected when something's dropped onto the desktop and
// an applet is to be created with this URL
if (!mimetype.isEmpty() && !tjob->error()) {
if (!mimeType.isEmpty() && !tjob->error()) {
tjob->putOnHold();
KIO::Scheduler::publishSlaveOnHold();
}
@ -1574,13 +1629,13 @@ void ContainmentPrivate::mimeTypeRetrieved(KIO::Job *job, const QString &mimetyp
//set wallpapery stuff
plugin = actionsToWallpapers.value(choice);
if (!wallpaper || plugin != wallpaper->pluginName()) {
kDebug() << "Wallpaper dropped:" << tjob->url();
//kDebug() << "Wallpaper dropped:" << tjob->url();
q->setWallpaper(plugin);
}
if (wallpaper) {
kDebug() << "Wallpaper dropped:" << tjob->url();
wallpaper->setUrls(KUrl::List() << tjob->url());
//kDebug() << "Wallpaper dropped:" << tjob->url();
wallpaper->addUrls(KUrl::List() << tjob->url());
}
} else {
addApplet(actionsToApplets[choice], args, QRectF(posi, QSize()));
@ -1599,13 +1654,6 @@ void ContainmentPrivate::mimeTypeRetrieved(KIO::Job *job, const QString &mimetyp
#endif // PLASMA_NO_KIO
}
#ifndef KDE_NO_DEPRECATED
const QGraphicsItem *Containment::toolBoxItem() const
{
return d->toolBox.data();
}
#endif
void Containment::setToolBox(AbstractToolBox *toolBox)
{
if (d->toolBox.data()) {
@ -1627,7 +1675,7 @@ void Containment::resizeEvent(QGraphicsSceneResizeEvent *event)
if (d->isPanelContainment()) {
d->positionPanel();
} else if (corona()) {
QMetaObject::invokeMethod(corona(), "layoutContainments");
corona()->layoutContainments();
}
if (d->wallpaper) {
@ -1642,7 +1690,9 @@ void Containment::keyPressEvent(QKeyEvent *event)
// << "and hoping and wishing for a" << Qt::Key_Tab;
if (event->key() == Qt::Key_Tab) { // && event->modifiers() == 0) {
if (!d->applets.isEmpty()) {
#ifndef NDEBUG
kDebug() << "let's give focus to...." << (QObject*)d->applets.first();
#endif
d->applets.first()->setFocus(Qt::TabFocusReason);
}
}
@ -1678,11 +1728,6 @@ void Containment::wheelEvent(QGraphicsSceneWheelEvent *event)
}
}
bool Containment::sceneEventFilter(QGraphicsItem *watched, QEvent *event)
{
return Applet::sceneEventFilter(watched, event);
}
QVariant Containment::itemChange(GraphicsItemChange change, const QVariant &value)
{
//FIXME if the applet is moved to another containment we need to unfocus it
@ -1697,7 +1742,7 @@ QVariant Containment::itemChange(GraphicsItemChange change, const QVariant &valu
break;
default:
if (corona()) {
QMetaObject::invokeMethod(corona(), "layoutContainments");
corona()->layoutContainments();
}
break;
}
@ -1902,10 +1947,10 @@ void Containment::setContainmentActions(const QString &trigger, const QString &p
case ContainmentPrivate::Activity:
//FIXME
case ContainmentPrivate::Local:
plugin = ContainmentActions::load(this, pluginName);
plugin = PluginLoader::self()->loadContainmentActions(this, pluginName);
break;
default:
plugin = ContainmentActions::load(0, pluginName);
plugin = PluginLoader::self()->loadContainmentActions(0, pluginName);
}
if (plugin) {
cfg.writeEntry(trigger, pluginName);
@ -1930,60 +1975,26 @@ QString Containment::containmentActions(const QString &trigger)
return c ? c->pluginName() : QString();
}
void Containment::setActivity(const QString &activity)
void Containment::setActivity(const QString &activityId)
{
Context *context = d->context();
if (context->currentActivity() != activity) {
context->setCurrentActivity(activity);
}
}
void ContainmentPrivate::onContextChanged(Plasma::Context *con)
{
foreach (Applet *a, applets) {
a->updateConstraints(ContextConstraint);
if (activityId.isEmpty()) {
return;
}
KConfigGroup c = q->config();
QString act = con->currentActivityId();
d->activityId = activityId;
KConfigGroup c = config();
c.writeEntry("activityId", activityId);
//save anything that's been set (boy I hope this avoids overwriting things)
//FIXME of course if the user sets the name to an empty string we have a bug
//but once we get context retrieving the name as soon as the id is set, this issue should go away
if (!act.isEmpty()) {
c.writeEntry("activityId", act);
}
act = con->currentActivity();
if (!act.isEmpty()) {
c.writeEntry("activity", act);
if (d->toolBox) {
d->toolBox.data()->update();
}
if (toolBox) {
toolBox.data()->update();
}
emit q->configNeedsSaving();
emit q->contextChanged(con);
emit configNeedsSaving();
}
QString Containment::activity() const
{
return d->context()->currentActivity();
}
Context *Containment::context() const
{
return d->context();
}
Context *ContainmentPrivate::context()
{
if (!con) {
con = new Context(q);
q->connect(con, SIGNAL(changed(Plasma::Context*)),
q, SLOT(onContextChanged(Plasma::Context*)));
}
return con;
return d->activityId;
}
KActionCollection* ContainmentPrivate::actions()
@ -2028,7 +2039,9 @@ void Containment::focusNextApplet()
if (index >= d->applets.size()) {
index = 0;
}
#ifndef NDEBUG
kDebug() << "index" << index;
#endif
d->focusApplet(d->applets.at(index));
}
@ -2041,7 +2054,9 @@ void Containment::focusPreviousApplet()
if (index < 0) {
index = d->applets.size() - 1;
}
#ifndef NDEBUG
kDebug() << "index" << index;
#endif
d->focusApplet(d->applets.at(index));
}
@ -2055,10 +2070,6 @@ void Containment::showConfigurationInterface()
Applet::showConfigurationInterface();
}
void Containment::configChanged()
{
}
void ContainmentPrivate::configChanged()
{
if (drawWallpaper) {
@ -2131,7 +2142,9 @@ void ContainmentPrivate::createToolBox()
void ContainmentPrivate::positionToolBox()
{
QMetaObject::invokeMethod(toolBox.data(), "reposition");
if (toolBox) {
toolBox.data()->reposition();
}
}
void ContainmentPrivate::updateToolBoxVisibility()
@ -2203,7 +2216,9 @@ Applet *ContainmentPrivate::addApplet(const QString &name, const QVariantList &a
}
if (!delayInit && q->immutability() != Mutable) {
#ifndef NDEBUG
kDebug() << "addApplet for" << name << "requested, but we're currently immutable!";
#endif
return 0;
}
@ -2212,13 +2227,15 @@ Applet *ContainmentPrivate::addApplet(const QString &name, const QVariantList &a
v->setCursor(Qt::BusyCursor);
}
Applet *applet = Applet::load(name, id, args);
Applet *applet = PluginLoader::self()->loadApplet(name, id, args);
if (v) {
v->unsetCursor();
}
if (!applet) {
#ifndef NDEBUG
kDebug() << "Applet" << name << "could not be loaded.";
#endif
applet = new Applet(0, QString(), id);
applet->setFailedToLaunch(true, i18n("Could not find requested component: %1", name));
}
@ -2272,7 +2289,9 @@ void ContainmentPrivate::appletAppeared(Applet *applet)
void ContainmentPrivate::positionPanel(bool force)
{
if (!q->scene()) {
#ifndef NDEBUG
kDebug() << "no scene yet";
#endif
return;
}
@ -2369,12 +2388,16 @@ QPointF ContainmentPrivate::preferredPanelPos(Corona *corona) const
if (horiz) {
bottom -= lastHeight + INTER_CONTAINMENT_MARGIN;
//TODO: fix x position for non-flush-left panels
#ifndef NDEBUG
kDebug() << "moved to" << QPointF(0, bottom - q->size().height());
#endif
newPos = QPointF(0, bottom - q->size().height());
} else {
bottom += lastHeight + INTER_CONTAINMENT_MARGIN;
//TODO: fix y position for non-flush-top panels
#ifndef NDEBUG
kDebug() << "moved to" << QPointF(bottom + q->size().width(), -INTER_CONTAINMENT_MARGIN - q->size().height());
#endif
newPos = QPointF(bottom + q->size().width(), -INTER_CONTAINMENT_MARGIN - q->size().height());
}
@ -2434,7 +2457,7 @@ KConfigGroup Containment::containmentActionsConfig()
break;
case ContainmentPrivate::Activity:
cfg = KConfigGroup(corona()->config(), "Activities");
cfg = KConfigGroup(&cfg, d->context()->currentActivityId());
cfg = KConfigGroup(&cfg, d->activityId);
cfg = KConfigGroup(&cfg, "ActionPlugins");
break;
default:

View File

@ -193,11 +193,11 @@ class PLASMA_EXPORT Containment : public Applet
static QStringList listContainmentTypes();
/**
* Returns a list of all known applets associated with a certain mimetype
* Returns a list of all known applets associated with a certain MimeType
*
* @return list of applets
**/
static KPluginInfo::List listContainmentsForMimetype(const QString &mimetype);
static KPluginInfo::List listContainmentsForMimeType(const QString &mimeType);
/**
* Adds an applet to this Containment
@ -356,23 +356,17 @@ class PLASMA_EXPORT Containment : public Applet
Plasma::Wallpaper *wallpaper() const;
/**
* Sets the current activity by name
* Sets the current activity by id
*
* @param activity the name of the activity
* @param activity the id of the activity
*/
void setActivity(const QString &activity);
void setActivity(const QString &activityId);
/**
* @return the current activity name associated with this containment
* @return the current activity id associated with this containment
*/
QString activity() const;
/**
* @return the context for this containment
* @since 4.5
*/
Context* context() const;
/**
* Shows the context menu for the containment directly, bypassing Applets
* altogether.
@ -427,12 +421,6 @@ Q_SIGNALS:
*/
void appletRemoved(Plasma::Applet *applet);
/**
* Emitted when the containment requests zooming in or out one step.
* @deprecated
*/
void zoomRequested(Plasma::Containment *containment, Plasma::ZoomDirection direction);
/**
* Emitted when the user clicks on the toolbox
*/
@ -474,11 +462,6 @@ Q_SIGNALS:
*/
void configureRequested(Plasma::Containment *containment);
/**
* The context associated to this containment has changed
*/
void contextChanged(Plasma::Context *context);
public Q_SLOTS:
/**
* Informs the Corona as to what position it is in. This is informational
@ -533,13 +516,6 @@ Q_SIGNALS:
*/
void showConfigurationInterface();
/**
* Called when applet configuration values have changed.
* @reimp
* @sa Applet::configChanged()
*/
void configChanged();
protected:
//FIXME plasma2: those should be public to allow scripted containments access them
/**
@ -574,7 +550,6 @@ Q_SIGNALS:
void contextMenuEvent(QGraphicsSceneContextMenuEvent *event);
void keyPressEvent(QKeyEvent *event);
void wheelEvent(QGraphicsSceneWheelEvent *event);
bool sceneEventFilter(QGraphicsItem *watched, QEvent *event);
QVariant itemChange(GraphicsItemChange change, const QVariant &value);
/**
@ -607,13 +582,6 @@ Q_SIGNALS:
*/
void resizeEvent(QGraphicsSceneResizeEvent *event);
/**
* @returns the toolbox associated with this containment, or a null pointer if none
*/
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED const QGraphicsItem *toolBoxItem() const;
#endif
/**
* Sets a custom ToolBox
* if there was an old one it will be deleted
@ -650,7 +618,6 @@ Q_SIGNALS:
Q_PRIVATE_SLOT(d, void showDropZoneDelayed())
Q_PRIVATE_SLOT(d, void checkStatus(Plasma::ItemStatus))
Q_PRIVATE_SLOT(d, void remoteAppletReady(Plasma::AccessAppletJob *))
Q_PRIVATE_SLOT(d, void onContextChanged(Plasma::Context *con))
/**
* This slot is called when the 'stat' after a job event has finished.
*/

View File

@ -42,8 +42,6 @@
namespace Plasma
{
PackageStructure::Ptr ContainmentActionsPrivate::s_packageStructure(0);
ContainmentActions::ContainmentActions(QObject * parentObject)
: d(new ContainmentActionsPrivate(KService::serviceByStorageId(QString()), this))
{
@ -70,64 +68,6 @@ ContainmentActions::~ContainmentActions()
delete d;
}
KPluginInfo::List ContainmentActions::listContainmentActionsInfo()
{
QString constraint;
KService::List offers = KServiceTypeTrader::self()->query("Plasma/ContainmentActions", constraint);
return KPluginInfo::fromServices(offers);
}
ContainmentActions *ContainmentActions::load(Containment *parent, const QString &containmentActionsName, const QVariantList &args)
{
if (containmentActionsName.isEmpty()) {
return 0;
}
QString constraint = QString("[X-KDE-PluginInfo-Name] == '%1'").arg(containmentActionsName);
KService::List offers = KServiceTypeTrader::self()->query("Plasma/ContainmentActions", constraint);
if (offers.isEmpty()) {
kDebug() << "offers is empty for " << containmentActionsName;
return 0;
}
KService::Ptr offer = offers.first();
KPluginLoader plugin(*offer);
if (!Plasma::isPluginVersionCompatible(plugin.pluginVersion())) {
return 0;
}
QVariantList allArgs;
allArgs << offer->storageId() << args;
QString error;
ContainmentActions *containmentActions = offer->createInstance<Plasma::ContainmentActions>(parent, allArgs, &error);
if (!containmentActions) {
kDebug() << "Couldn't load containmentActions \"" << containmentActionsName << "\"! reason given: " << error;
}
return containmentActions;
}
ContainmentActions *ContainmentActions::load(Containment *parent, const KPluginInfo &info, const QVariantList &args)
{
if (!info.isValid()) {
return 0;
}
return load(parent, info.pluginName(), args);
}
PackageStructure::Ptr ContainmentActions::packageStructure()
{
if (!ContainmentActionsPrivate::s_packageStructure) {
ContainmentActionsPrivate::s_packageStructure = new ContainmentActionsPackage();
}
return ContainmentActionsPrivate::s_packageStructure;
}
Containment *ContainmentActions::containment()
{
if (d->containment) {

View File

@ -25,7 +25,6 @@
#include <kplugininfo.h>
#include <plasma/plasma.h>
#include <plasma/packagestructure.h>
#include <plasma/version.h>
class QAction;
@ -67,46 +66,6 @@ class PLASMA_EXPORT ContainmentActions : public QObject
~ContainmentActions();
/**
* Returns a list of all known containmentactions plugins.
*
* @return list of containmentactions plugins
**/
static KPluginInfo::List listContainmentActionsInfo();
/**
* Attempts to load a containmentactions
*
* Returns a pointer to the containmentactions if successful.
* The caller takes responsibility for the containmentactions, including
* deleting it when no longer needed.
*
* @param parent the parent containment. @since 4.6 null is allowed.
* @param name the plugin name, as returned by KPluginInfo::pluginName()
* @param args to send the containmentactions extra arguments
* @return a pointer to the loaded containmentactions, or 0 on load failure
**/
static ContainmentActions *load(Containment *parent, const QString &name, const QVariantList &args = QVariantList());
/**
* Attempts to load a containmentactions
*
* Returns a pointer to the containmentactions if successful.
* The caller takes responsibility for the containmentactions, including
* deleting it when no longer needed.
*
* @param parent the parent containment. @since 4.6 null is allowed.
* @param info KPluginInfo object for the desired containmentactions
* @param args to send the containmentactions extra arguments
* @return a pointer to the loaded containmentactions, or 0 on load failure
**/
static ContainmentActions *load(Containment *parent, const KPluginInfo &info, const QVariantList &args = QVariantList());
/**
* Returns the Package specialization for containmentactions.
*/
static PackageStructure::Ptr packageStructure();
/**
* Returns the user-visible name for the containmentactions, as specified in the
* .desktop file.

View File

@ -1,89 +0,0 @@
/*
* Copyright 2008 by Aaron Seigo <aseigo@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License 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 "context.h"
namespace Plasma
{
class ContextPrivate
{
public:
QString activityId;
QString activityName;
};
Context::Context(QObject *parent)
: QObject(parent),
d(new ContextPrivate)
{
//TODO: look up activity in Nepomuk
//except we can't, because that code is in kdebase.
}
Context::~Context()
{
delete d;
}
void Context::createActivity(const QString &name)
{
Q_UNUSED(name);
}
QStringList Context::listActivities() const
{
return QStringList();
}
void Context::setCurrentActivity(const QString &name)
{
if (d->activityName == name || name.isEmpty()) {
return;
}
d->activityName = name;
emit activityChanged(this);
emit changed(this);
}
QString Context::currentActivity() const
{
return d->activityName;
}
void Context::setCurrentActivityId(const QString &id)
{
if (d->activityId == id) {
return;
}
d->activityId = id;
emit changed(this);
}
QString Context::currentActivityId() const
{
return d->activityId;
}
} // namespace Plasma
#include "context.moc"

View File

@ -1,67 +0,0 @@
/*
* Copyright 2008 by Aaron Seigo <aseigo@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License 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_CONTEXT_H
#define PLASMA_CONTEXT_H
#include <QtCore/QObject>
#include <QtCore/QStringList>
#include "plasma_export.h"
namespace Plasma
{
class ContextPrivate;
class PLASMA_EXPORT Context : public QObject
{
Q_OBJECT
public:
explicit Context(QObject *parent = 0);
~Context();
//don't use these two
void createActivity(const QString &name);
QStringList listActivities() const;
//activity name
void setCurrentActivity(const QString &name);
QString currentActivity() const;
//activity id
void setCurrentActivityId(const QString &id);
QString currentActivityId() const;
//TODO: location
Q_SIGNALS:
void changed(Plasma::Context *context);
void activityChanged(Plasma::Context *context);
void locationChanged(Plasma::Context *context);
private:
ContextPrivate * const d;
};
} // namespace Plasma
#endif // multiple inclusion guard

View File

@ -26,7 +26,6 @@
#include <QApplication>
#include <QDesktopWidget>
#include <QGraphicsView>
#include <QGraphicsSceneDragDropEvent>
#include <QGraphicsGridLayout>
#include <QMimeData>
#include <QPainter>
@ -42,16 +41,17 @@
#include <kshortcutsdialog.h>
#include <kwindowsystem.h>
#include "animator.h"
#include "abstractdialogmanager.h"
#include "abstracttoolbox.h"
#include "animator.h"
#include "containment.h"
#include "containmentactionspluginsconfig.h"
#include "view.h"
#include "pluginloader.h"
#include "private/animator_p.h"
#include "private/applet_p.h"
#include "private/containment_p.h"
#include "tooltipmanager.h"
#include "abstractdialogmanager.h"
#include "view.h"
using namespace Plasma;
@ -64,9 +64,10 @@ Corona::Corona(QObject *parent)
: QGraphicsScene(parent),
d(new CoronaPrivate(this))
{
#ifndef NDEBUG
kDebug() << "!!{} STARTUP TIME" << QTime().msecsTo(QTime::currentTime()) << "Corona ctor start";
#endif
d->init();
ToolTipManager::self()->m_corona = this;
//setViewport(new QGLWidget(QGLFormat(QGL::StencilBuffer | QGL::AlphaChannel)));
}
@ -274,8 +275,8 @@ void Corona::loadLayout(const QString &configName)
d->configName = configName;
}
KSharedConfigPtr conf = config();
d->importLayout(*conf, false);
KConfigGroup conf(config(), QString());
d->importLayout(conf, false);
}
QList<Plasma::Containment *> Corona::importLayout(const KConfigGroup &conf)
@ -283,13 +284,6 @@ QList<Plasma::Containment *> Corona::importLayout(const KConfigGroup &conf)
return d->importLayout(conf, true);
}
#ifndef KDE_NO_DEPRECATED
QList<Plasma::Containment *> Corona::importLayout(const KConfigBase &conf)
{
return d->importLayout(conf, true);
}
#endif
Containment *Corona::containmentForScreen(int screen, int desktop) const
{
foreach (Containment *containment, d->containments) {
@ -375,7 +369,9 @@ void Corona::addOffscreenWidget(QGraphicsWidget *widget)
{
foreach (QGraphicsWidget *w, d->offscreenWidgets) {
if (w == widget) {
#ifndef NDEBUG
kDebug() << "widget is already an offscreen widget!";
#endif
return;
}
}
@ -453,18 +449,9 @@ QRegion Corona::availableScreenRegion(int id) const
return QRegion(screenGeometry(id));
}
QPoint Corona::popupPosition(const QGraphicsItem *item, const QSize &s)
{
return popupPosition(item, s, Qt::AlignLeft);
}
QPoint Corona::popupPosition(const QGraphicsItem *item, const QSize &s, Qt::AlignmentFlag alignment)
{
// TODO: merge both methods (also these in Applet) into one (with optional alignment) when we can break compatibility
// TODO: add support for more flags in the future?
const QGraphicsItem *actualItem = item;
const QGraphicsView *v = viewFor(item);
if (!v) {
@ -482,7 +469,9 @@ QPoint Corona::popupPosition(const QGraphicsItem *item, const QSize &s, Qt::Alig
}
}
#ifndef NDEBUG
kDebug() << actualItem;
#endif
if (actualItem) {
v = viewFor(actualItem);
@ -636,21 +625,6 @@ QString Corona::preferredToolBoxPlugin(const Containment::Type type) const
return d->toolBoxPlugins.value(type);
}
void Corona::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
QGraphicsScene::dragEnterEvent(event);
}
void Corona::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
{
QGraphicsScene::dragLeaveEvent(event);
}
void Corona::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
{
QGraphicsScene::dragMoveEvent(event);
}
ImmutabilityType Corona::immutability() const
{
return d->immutability;
@ -662,7 +636,9 @@ void Corona::setImmutability(const ImmutabilityType immutable)
return;
}
#ifndef NDEBUG
kDebug() << "setting immutability to" << immutable;
#endif
d->immutability = immutable;
d->updateContainmentImmutability();
//tell non-containments that might care (like plasmaapp or a custom corona)
@ -935,13 +911,15 @@ Containment *CoronaPrivate::addContainment(const QString &name, const QVariantLi
bool loadingNull = pluginName == "null";
if (!loadingNull) {
applet = Applet::load(pluginName, id, args);
applet = PluginLoader::self()->loadApplet(pluginName, id, args);
containment = dynamic_cast<Containment*>(applet);
}
if (!containment) {
if (!loadingNull) {
#ifndef NDEBUG
kDebug() << "loading of containment" << name << "failed.";
#endif
}
// in case we got a non-Containment from Applet::loadApplet or
@ -1006,13 +984,11 @@ Containment *CoronaPrivate::addContainment(const QString &name, const QVariantLi
return containment;
}
QList<Plasma::Containment *> CoronaPrivate::importLayout(const KConfigBase &conf, bool mergeConfig)
QList<Plasma::Containment *> CoronaPrivate::importLayout(const KConfigGroup &conf, bool mergeConfig)
{
if (const KConfigGroup *group = dynamic_cast<const KConfigGroup *>(&conf)) {
if (!group->isValid()) {
if (!conf.isValid()) {
return QList<Containment *>();
}
}
QList<Plasma::Containment *> newContainments;
QSet<uint> containmentsIds;
@ -1046,7 +1022,9 @@ QList<Plasma::Containment *> CoronaPrivate::importLayout(const KConfigBase &conf
}
//kDebug() << "got a containment in the config, trying to make a" << containmentConfig.readEntry("plugin", QString()) << "from" << group;
#ifndef NDEBUG
kDebug() << "!!{} STARTUP TIME" << QTime().msecsTo(QTime::currentTime()) << "Adding Containment" << containmentConfig.readEntry("plugin", QString());
#endif
Containment *c = addContainment(containmentConfig.readEntry("plugin", QString()), QVariantList(), cid, true);
if (!c) {
continue;
@ -1056,16 +1034,22 @@ QList<Plasma::Containment *> CoronaPrivate::importLayout(const KConfigBase &conf
containmentsIds.insert(c->id());
c->init();
#ifndef NDEBUG
kDebug() << "!!{} STARTUP TIME" << QTime().msecsTo(QTime::currentTime()) << "Init Containment" << c->pluginName();
#endif
c->restore(containmentConfig);
#ifndef NDEBUG
kDebug() << "!!{} STARTUP TIME" << QTime().msecsTo(QTime::currentTime()) << "Restored Containment" << c->pluginName();
#endif
}
foreach (Containment *containment, newContainments) {
containment->updateConstraints(Plasma::StartupCompletedConstraint);
containment->d->initApplets();
emit q->containmentAdded(containment);
#ifndef NDEBUG
kDebug() << "!!{} STARTUP TIME" << QTime().msecsTo(QTime::currentTime()) << "Containment" << containment->name();
#endif
}
return newContainments;

View File

@ -173,15 +173,6 @@ public:
*/
virtual QRegion availableScreenRegion(int id) const;
/**
* Recommended position for a popup window like a menu or a tooltip
* given its size
* @param item the item that the popup should appear adjacent to (an applet, say)
* @param size size of the popup
* @returns reccomended position
*/
QPoint popupPosition(const QGraphicsItem *item, const QSize &size);
/**
* @since 4.4
* Recommended position for a popup window like a menu or a tooltip
@ -191,7 +182,7 @@ public:
* @param alignment alignment of the popup, valid flags are Qt::AlignLeft, Qt::AlignRight and Qt::AlignCenter
* @returns reccomended position
*/
QPoint popupPosition(const QGraphicsItem *item, const QSize &size, Qt::AlignmentFlag alignment);
QPoint popupPosition(const QGraphicsItem *item, const QSize &size, Qt::AlignmentFlag alignment = Qt::AlignCenter);
/**
* This method is useful in order to retrieve the list of available
@ -275,20 +266,6 @@ public:
*/
AbstractDialogManager *dialogManager();
/**
* Imports an applet layout from a config file. The results will be added to the
* current set of Containments.
* @deprecated Use the 4.6 version that takes a KConfigGroup
*
* @param config the name of the config file to load from,
* or the default config file if QString()
* @return the list of containments that were loaded
* @since 4.5
*/
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED QList<Plasma::Containment *> importLayout(const KConfigBase &config);
#endif
/**
* Returns the name of the preferred plugin to be used as containment toolboxes.
* CustomContainments and CustomPanelContainments can still override it as their liking. It's also not guaranteed that the plugin will actually exist.
@ -377,7 +354,7 @@ public Q_SLOTS:
* organizes them in a grid-like view, but subclasses can reimplement
* this slot to provide their own layout.
*/
void layoutContainments();
virtual void layoutContainments();
Q_SIGNALS:
/**
@ -491,11 +468,6 @@ protected:
*/
void setDefaultContainmentPlugin(const QString &name);
//Reimplemented from QGraphicsScene
void dragEnterEvent(QGraphicsSceneDragDropEvent *event);
void dragLeaveEvent(QGraphicsSceneDragDropEvent *event);
void dragMoveEvent(QGraphicsSceneDragDropEvent *event);
private:
CoronaPrivate *const d;

View File

@ -1,84 +1,3 @@
[Desktop Entry]
Type=ServiceType
X-KDE-ServiceType=Plasma/PackageStructure
Comment=Plasma package structure definition
Comment[ar]=تعريف بنية حزمة بلازما
Comment[as]=Plasma
Comment[ast]=Definición d'estructura de paquete Plasma
Comment[be@latin]=Aznačeńnie struktury pakunka Plasma
Comment[bg]=Структурно определение на пакет на Plasma
Comment[bs]=Definicija strukture plazma paketa
Comment[ca]=Definició de l'estructura d'un paquet Plasma
Comment[ca@valencia]=Definició de l'estructura d'un paquet Plasma
Comment[cs]=Definice struktury Plasma balíčku
Comment[da]=Definition af pakkestruktur til Plasma
Comment[de]=Plasma-Paket-Struktur-Definition
Comment[el]=Ορισμός δομής πακέτου του Plasma
Comment[en_GB]=Plasma package structure definition
Comment[es]=Definición de estructura de paquete para Plasma
Comment[et]=Plasma paketi struktuuri definitsioon
Comment[eu]=Plasma paketearen egituraren definizioa
Comment[fi]=Plasma-pakettirakenteen määritelmä
Comment[fr]=Définition de la structure des paquetages Plasma
Comment[fy]=Plasma pakket sstruktuer defenysje
Comment[ga]=Sainmhíniú ar struchtúr pacáiste Plasma
Comment[gl]=Definición da estrutura do paquete de Plasma
Comment[gu]=
Comment[he]=הגדרת מבנה של חבילת Plasma
Comment[hne]= ि
Comment[hr]=Plasmina definicija strukture paketa
Comment[hsb]=Strukturna definicija Plasma-pakćika
Comment[hu]=Struktúraleíró Plasma-csomagokhoz
Comment[ia]=Definition del structura de pacchetto de Plasma
Comment[id]=Definisi struktur paket Plasma
Comment[is]=Skilgreiningar Plasma pakkauppbyggingar
Comment[it]=Definizione struttura pacchetto Plasma
Comment[ja]=Plasma
Comment[kk]=Plasma дестесінің құрамынын анықтауы
Comment[km]=
Comment[kn]= () (ಿ)
Comment[ko]=Plasma
Comment[ku]=Daxuyaniya çêbûna pakêta Plasma
Comment[lt]=Plasma paketo struktūros aprašymas
Comment[lv]=Plasma pakotņu struktūras definīcija
Comment[mai]= ि
Comment[ml]= ി
Comment[nb]=Definisjon av Plasma pakkestruktur
Comment[nds]=Paketstruktuur-Fastleggen vun Plasma
Comment[nl]=Structuurdefinitie van plasmapakket
Comment[nn]=Pakkestrukturdefinisjon for Plasma
Comment[pa]= ਿ
Comment[pl]=Definicja struktury pakietu Plazmy
Comment[pt]=Definição da estrutura de pacotes do Plasma
Comment[pt_BR]=Definição de estrutura de pacote do Plasma
Comment[ro]=Definiție de structură a pachetului Plasma
Comment[ru]=Определение структуры пакета Plasma
Comment[se]=Plasma-páhkkaráhkadusdefinišuvdna
Comment[sk]=Definícia štruktúry Plasma balíčkov
Comment[sl]=Definicija strukture paketa za Plasmo
Comment[sr]=Дефиниција структуре плазма пакета
Comment[sr@ijekavian]=Дефиниција структуре плазма пакета
Comment[sr@ijekavianlatin]=Definicija strukture plasma paketa
Comment[sr@latin]=Definicija strukture plasma paketa
Comment[sv]=Strukturdefinition av Plasma-paket
Comment[ta]=ி ி ி
Comment[tg]=Барномаи муайянкунии сохтори Plasma
Comment[th]=
Comment[tr]=Plasma paketi yapı tanımlaması
Comment[ug]=Plasma بوغچا قۇرۇلما ئېنىقلىمىسى
Comment[uk]=Опис структури пакунка плазми
Comment[wa]=Definixha del sitructeure do pacaedje di Plasma
Comment[x-test]=xxPlasma package structure definitionxx
Comment[zh_CN]=Plasma
Comment[zh_TW]=Plasma
[PropertyDef::X-Plasma-PackageFileFilter]
Type=QString
[PropertyDef::X-Plasma-PackageFileMimetypes]
Type=QStringList
[PropertyDef::X-Plasma-ProvidesWidgetBrowser]
Type=bool

View File

@ -287,7 +287,7 @@ void DataContainer::disconnectVisualization(QObject *visualization)
}
d->relayObjects.erase(objIt);
checkUsage();
d->checkUsage();
}
void DataContainer::checkForUpdate()
@ -328,13 +328,18 @@ void DataContainer::setNeedsUpdate(bool update)
d->cached = update;
}
void DataContainer::checkUsage()
bool DataContainer::isUsed() const
{
if (d->relays.count() < 1 &&
receivers(SIGNAL(dataUpdated(QString, Plasma::DataEngine::Data))) < 1) {
return !d->relays.isEmpty() &&
receivers(SIGNAL(dataUpdated(QString, Plasma::DataEngine::Data))) > 0;
}
void DataContainerPrivate::checkUsage()
{
if (!q->isUsed()) {
// DO NOT CALL ANYTHING AFTER THIS LINE AS IT MAY GET DELETED!
kDebug() << objectName() << "is unused";
emit becameUnused(objectName());
//kDebug() << q->objectName() << "is unused";
emit q->becameUnused(q->objectName());
}
}

View File

@ -154,6 +154,11 @@ class PLASMA_EXPORT DataContainer : public QObject
*/
DataEngine* getDataEngine();
/**
* @return true if one or more visualizations is connected to this DataContainer
*/
bool isUsed() const;
public Q_SLOTS:
/**
* Disconnects an object from this DataContainer.
@ -234,17 +239,6 @@ class PLASMA_EXPORT DataContainer : public QObject
**/
void setNeedsUpdate(bool update = true);
protected Q_SLOTS:
/**
* Check if the DataContainer is still in use.
*
* If not the signal "becameUnused" will be emitted.
*
* Warning: The DataContainer may be invalid after calling this function, because a listener
* to becameUnused() may have deleted it.
**/
void checkUsage();
private:
friend class SignalRelay;
friend class DataContainerPrivate;

View File

@ -32,13 +32,15 @@
#include <kservice.h>
#include <kstandarddirs.h>
#include "authorizationmanager.h"
#include "datacontainer.h"
#include "package.h"
#include "pluginloader.h"
#include "remote/authorizationmanager.h"
#include "remote/authorizationmanager_p.h"
#include "service.h"
#include "scripting/dataenginescript.h"
#include "private/authorizationmanager_p.h"
#include "private/datacontainer_p.h"
#include "private/dataengineservice_p.h"
#include "private/remotedataengine_p.h"
#include "private/service_p.h"
@ -146,7 +148,7 @@ DataEngine::Data DataEngine::query(const QString &source) const
}
DataEngine::Data data = s->data();
s->checkUsage();
s->d->checkUsage();
return data;
}
@ -247,7 +249,9 @@ void DataEngine::removeData(const QString &source, const QString &key)
void DataEngine::addSource(DataContainer *source)
{
if (d->sources.contains(source->objectName())) {
#ifndef NDEBUG
kDebug() << "source named \"" << source->objectName() << "\" already exists.";
#endif
return;
}
@ -437,7 +441,7 @@ Service* DataEngine::createDefaultService(QObject *parent)
{
QVariantList args;
args << QVariant::fromValue<DataEngine*>(this);
return Service::load(d->serviceName, args, parent);
return PluginLoader::self()->loadService(d->serviceName, args, parent);
}
void DataEnginePrivate::publish(AnnouncementMethods methods, const QString &name)
@ -450,7 +454,9 @@ void DataEnginePrivate::publish(AnnouncementMethods methods, const QString &name
//i18nc("%1 is the name of a dataengine, %2 the name of the machine that engine is published
//on",
//"%1 dataengine on %2", name(), AuthorizationManager::self()->d->myCredentials.name());
#ifndef NDEBUG
kDebug() << "name: " << name;
#endif
publishedService->d->publish(methods, name);
}
@ -472,9 +478,9 @@ bool DataEnginePrivate::isPublished() const
}
}
const Package *DataEngine::package() const
Package DataEngine::package() const
{
return d->package;
return d->package ? *d->package : Package();
}
void DataEngine::scheduleSourcesUpdated()
@ -540,14 +546,18 @@ DataEnginePrivate::DataEnginePrivate(DataEngine *e, const KPluginInfo &info)
const QString path =
KStandardDirs::locate("data",
"plasma/dataengines/" + dataEngineDescription.pluginName() + '/');
PackageStructure::Ptr structure = Plasma::packageStructure(api, Plasma::DataEngineComponent);
structure->setPath(path);
package = new Package(path, structure);
package = new Package(PluginLoader::self()->loadPackage("Plasma/DataEngine", api));
package->setPath(path);
if (package->isValid()) {
script = Plasma::loadScriptEngine(api, q);
}
if (!script) {
#ifndef NDEBUG
kDebug() << "Could not create a" << api << "ScriptEngine for the"
<< dataEngineDescription.name() << "DataEngine.";
#endif
delete package;
package = 0;
}
@ -580,7 +590,9 @@ void DataEnginePrivate::internalUpdateSource(DataContainer *source)
//kDebug() << "queuing an update";
q->scheduleSourcesUpdated();
}/* else {
#ifndef NDEBUG
kDebug() << "no update";
#endif
}*/
}
@ -736,17 +748,17 @@ void DataEnginePrivate::setupScriptSupport()
}
/*
#ifndef NDEBUG
kDebug() << "sletting up script support, package is in" << package->path()
#endif
<< "which is a" << package->structure()->type() << "package"
<< ", main script is" << package->filePath("mainscript");
*/
QString translationsPath = package->filePath("translations");
const QString translationsPath = package->filePath("translations");
if (!translationsPath.isEmpty()) {
//FIXME: we should _probably_ use a KComponentData to segregate the applets
// from each other; but I want to get the basics working first :)
KGlobal::dirs()->addResourceDir("locale", translationsPath);
KGlobal::locale()->insertCatalog(package->metadata().pluginName());
KGlobal::locale()->insertCatalog(dataEngineDescription.pluginName());
}
}

View File

@ -231,7 +231,7 @@ NoAlignment) const;
*
* @return the Package object, or 0 if none
**/
const Package *package() const;
Package package() const;
/**
* @return the plugin name for the applet

View File

@ -129,7 +129,7 @@ Plasma::DataEngine *DataEngineManager::loadEngine(const QString &name)
return engine;
}
DataEngine *engine = PluginLoader::pluginLoader()->loadDataEngine(name);
DataEngine *engine = PluginLoader::self()->loadDataEngine(name);
if (!engine) {
// Try installing the engine. However, it's too late for this request.
ComponentInstaller::self()->installMissingComponent("dataengine", name);
@ -182,7 +182,7 @@ QStringList DataEngineManager::listAllEngines(const QString &parentApp)
KPluginInfo::List DataEngineManager::listEngineInfo(const QString &parentApp)
{
return PluginLoader::pluginLoader()->listDataEngineInfo(parentApp);
return PluginLoader::self()->listDataEngineInfo(parentApp);
}
KPluginInfo::List DataEngineManager::listEngineInfoByCategory(const QString &category, const QString &parentApp)

View File

@ -1,146 +0,0 @@
/*
* Copyright 2007 Aaron Seigo <aseigo@kde.org>
* 2007 Alexis Ménard <darktears31@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "animationdriver.h"
#include <QPainter>
#include <QGraphicsItem>
namespace Plasma
{
AnimationDriver::AnimationDriver(QObject *parent)
: QObject(parent),
d(0)
{
}
AnimationDriver::~AnimationDriver()
{
}
int AnimationDriver::animationFps(Plasma::Animator::Animation animation) const
{
Q_UNUSED(animation)
return 0;
}
int AnimationDriver::movementAnimationFps(Plasma::Animator::Movement movement) const
{
Q_UNUSED(movement)
return 40;
}
int AnimationDriver::elementAnimationFps(Plasma::Animator::Animation animation) const
{
Q_UNUSED(animation)
return 0;
}
int AnimationDriver::animationDuration(Plasma::Animator::Animation) const
{
return 200;
}
int AnimationDriver::movementAnimationDuration(Plasma::Animator::Movement movement) const
{
switch (movement) {
case Animator::FastSlideInMovement:
case Animator::FastSlideOutMovement:
return 150;
break;
default:
break;
}
return 250;
}
int AnimationDriver::elementAnimationDuration(Plasma::Animator::Animation) const
{
return 333;
}
Animator::CurveShape AnimationDriver::animationCurve(Plasma::Animator::Animation) const
{
return Animator::EaseInOutCurve;
}
Animator::CurveShape AnimationDriver::movementAnimationCurve(Plasma::Animator::Movement) const
{
return Animator::EaseInOutCurve;
}
Animator::CurveShape AnimationDriver::elementAnimationCurve(Plasma::Animator::Animation) const
{
return Animator::EaseInOutCurve;
}
QPixmap AnimationDriver::elementAppear(qreal progress, const QPixmap &pixmap)
{
Q_UNUSED(progress)
return pixmap;
}
QPixmap AnimationDriver::elementDisappear(qreal progress, const QPixmap &pixmap)
{
Q_UNUSED(progress)
QPixmap pix(pixmap.size());
pix.fill(Qt::transparent);
return pix;
}
void AnimationDriver::itemAppear(qreal frame, QGraphicsItem *item)
{
Q_UNUSED(frame)
Q_UNUSED(item)
}
void AnimationDriver::itemDisappear(qreal frame, QGraphicsItem *item)
{
Q_UNUSED(frame)
Q_UNUSED(item)
}
void AnimationDriver::itemActivated(qreal frame, QGraphicsItem *item)
{
Q_UNUSED(frame)
Q_UNUSED(item)
}
void AnimationDriver::itemSlideIn(qreal progress, QGraphicsItem *item, const QPoint &start, const QPoint &destination)
{
double x = start.x() + (destination.x() - start.x()) * progress;
double y = start.y() + (destination.y() - start.y()) * progress;
item->setPos(x, y);
}
void AnimationDriver::itemSlideOut(qreal progress, QGraphicsItem *item, const QPoint &start, const QPoint &destination)
{
//kDebug();
double x = start.x() + (destination.x() - start.x()) * progress;
double y = start.y() + (destination.y() - start.y()) * progress;
item->setPos(x, y);
}
} // Plasma namespace
#include "../animationdriver.moc"

View File

@ -1,788 +0,0 @@
/*
* Copyright 2007 Aaron Seigo <aseigo@kde.org>
* 2007 Alexis Ménard <darktears31@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "animator.h"
#include "private/animator_p.h"
#include <QGraphicsItem>
#include <QTimeLine>
#include <QTimerEvent>
#include <kconfig.h>
#include <kconfiggroup.h>
#include <kdebug.h>
#include <kservice.h>
#include <kservicetypetrader.h>
#include <kglobalsettings.h>
#include "animationdriver.h"
#include "private/kineticscroll_p.h"
namespace Plasma
{
static const int MIN_TICK_RATE_INT = 10;
static const qreal MIN_TICK_RATE = 10;
AnimatorPrivate::AnimatorPrivate(Animator *parent)
: q(parent),
driver(0),
animId(0),
timerId(0)
{
}
AnimatorPrivate::~AnimatorPrivate()
{
cleanupStates();
qDeleteAll(animatedItems);
qDeleteAll(animatedElements);
qDeleteAll(movingItems);
QMutableHashIterator<int, CustomAnimationState*> it(customAnims);
while (it.hasNext()) {
it.next();
delete[] it.value()->slot;
delete it.value();
it.remove();
}
// Animator is a QObject
// and we don't own the items
}
qreal AnimatorPrivate::calculateProgress(int time, int duration, Animator::CurveShape curve)
{
if (!(KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects)) {
return qreal(1.0);
}
timeline.setCurveShape(static_cast<QTimeLine::CurveShape>(curve));
timeline.setDuration(duration);
qreal progress = timeline.valueForTime(time);
return progress;
}
void AnimatorPrivate::performAnimation(qreal amount, const AnimationState *state)
{
/* TODO: write new animations to replace this.
*/
switch (state->animation) {
case Animator::AppearAnimation:
driver->itemAppear(amount, state->item);
break;
case Animator::DisappearAnimation:
driver->itemDisappear(amount, state->item);
if (amount >= 1) {
state->item->hide();
}
break;
case Animator::ActivateAnimation:
driver->itemActivated(amount, state->item);
break;
default:
kDebug() << "Unsupported animation type.";
}
}
void AnimatorPrivate::performMovement(qreal amount, const MovementState *state)
{
switch (state->movement) {
case Animator::SlideInMovement:
case Animator::FastSlideInMovement:
//kDebug() << "performMovement, SlideInMovement";
driver->itemSlideIn(amount, state->item, state->start, state->destination);
break;
case Animator::SlideOutMovement:
case Animator::FastSlideOutMovement:
//kDebug() << "performMovement, SlideOutMovement";
driver->itemSlideOut(amount, state->item, state->start, state->destination);
break;
}
}
void AnimatorPrivate::scrollStateChanged(QAbstractAnimation::State newState,
QAbstractAnimation::State oldState)
{
KineticScrolling *scroll = qobject_cast<KineticScrolling*>(q->sender());
if (!scroll) {
kDebug() << "Could not find KineticScrolling object";
return;
}
emit q->scrollStateChanged(scrollingManagers.key(scroll), newState, oldState);
}
class AnimatorSingleton
{
public:
Animator self;
};
K_GLOBAL_STATIC(AnimatorSingleton, privateSelf)
Animator *Animator::self()
{
return &privateSelf->self;
}
Animator::Animator(QObject *parent)
: QObject(parent),
d(new AnimatorPrivate(this))
{
d->init(this);
}
Animator::~Animator()
{
delete d;
}
void AnimatorPrivate::animatedItemDestroyed(QObject *o)
{
//kDebug() << "testing for" << (void*)o;
QMutableHashIterator<QGraphicsItem*, AnimationState*> it(animatedItems);
while (it.hasNext()) {
it.next();
//kDebug() << "comparing against" << it.value()->qobj;
if (it.value()->qobj == o) {
kDebug() << "found deleted animated item";
if (timerId) {
animatedItemsToDelete.insert(it.value());
} else {
delete it.value();
}
it.remove();
}
}
}
void AnimatorPrivate::movingItemDestroyed(QObject *o)
{
QMutableHashIterator<QGraphicsItem*, MovementState*> it(movingItems);
while (it.hasNext()) {
it.next();
if (it.value()->qobj == o) {
if (timerId) {
movingItemsToDelete.insert(it.value());
} else {
delete it.value();
}
it.remove();
}
}
}
void AnimatorPrivate::animatedElementDestroyed(QObject *o)
{
QMutableHashIterator<int, ElementAnimationState*> it(animatedElements);
while (it.hasNext()) {
it.next();
if (it.value()->qobj == o) {
if (timerId) {
animatedElementsToDelete.insert(it.value());
} else {
delete it.value();
}
it.remove();
}
}
}
void AnimatorPrivate::customAnimReceiverDestroyed(QObject *o)
{
QMutableHashIterator<int, CustomAnimationState*> it(customAnims);
while (it.hasNext()) {
if (it.next().value()->receiver == o) {
if (timerId) {
customAnimsToDelete.insert(it.value());
} else {
delete[] it.value()->slot;
delete it.value();
}
it.remove();
}
}
}
int Animator::animateItem(QGraphicsItem *item, Animation animation)
{
//kDebug();
// get rid of any existing animations on this item.
QHash<QGraphicsItem*, AnimationState*>::iterator it = d->animatedItems.find(item);
if (it != d->animatedItems.end()) {
if (d->timerId) {
d->animatedItemsToDelete.insert(it.value());
} else {
delete it.value();
}
d->animatedItems.erase(it);
}
int frames = d->driver->animationFps(animation);
if (frames < 1) {
// evidently this animator doesn't have an implementation
// for this Animation
return -1;
}
int duration = d->driver->animationDuration(animation);
AnimationState *state = new AnimationState;
state->id = ++d->animId;
state->item = item;
state->animation = animation;
state->curve = d->driver->animationCurve(animation);
state->frames = qMax(1.0, frames * (duration / 1000.0)); //krazy:exclude=qminmax
state->currentFrame = 0;
state->interval = d->driver->animationDuration(animation) / qreal(state->frames);
state->interval = qMax(MIN_TICK_RATE_INT, state->interval - (state->interval % MIN_TICK_RATE_INT));
state->currentInterval = state->interval;
state->qobj = dynamic_cast<QObject*>(item);
if (state->qobj) {
//kDebug() << "!!!!!!!!!!!!!!!!!!!!!!!!! got us an object!";
disconnect(state->qobj, SIGNAL(destroyed(QObject*)),
this, SLOT(animatedItemDestroyed(QObject*)));
connect(state->qobj, SIGNAL(destroyed(QObject*)),
this, SLOT(animatedItemDestroyed(QObject*)));
}
d->animatedItems[item] = state;
d->performAnimation(0, state);
if (!d->timerId) {
d->timerId = startTimer(MIN_TICK_RATE);
d->time.restart();
}
return state->id;
}
int Animator::moveItem(QGraphicsItem *item, Movement movement, const QPoint &destination)
{
//kDebug();
QHash<QGraphicsItem*, MovementState*>::iterator it = d->movingItems.find(item);
if (it != d->movingItems.end()) {
if (d->timerId) {
d->movingItemsToDelete.insert(it.value());
} else {
delete it.value();
}
d->movingItems.erase(it);
}
int frames = d->driver->movementAnimationFps(movement);
if (frames <= 1) {
// evidently this animator doesn't have an implementation
// for this Animation
return -1;
}
MovementState *state = new MovementState;
state->id = ++d->animId;
state->destination = destination;
state->start = item->pos().toPoint();
state->item = item;
state->movement = movement;
state->curve = d->driver->movementAnimationCurve(movement);
int duration = d->driver->movementAnimationDuration(movement);
state->frames = qMax(1.0, frames * (duration / 1000.0)); //krazy:exclude=qminmax
state->currentFrame = 0;
state->interval = duration / qreal(state->frames);
state->interval = qMax(MIN_TICK_RATE_INT, state->interval - (state->interval % MIN_TICK_RATE_INT));
// state->interval = (state->interval / MIN_TICK_RATE) * MIN_TICK_RATE;
// kDebug() << "interval of" << state->interval << state->frames << duration << frames;
state->currentInterval = state->interval;
state->qobj = dynamic_cast<QObject*>(item);
if (state->qobj) {
disconnect(state->qobj, SIGNAL(destroyed(QObject*)), this, SLOT(movingItemDestroyed(QObject*)));
connect(state->qobj, SIGNAL(destroyed(QObject*)), this, SLOT(movingItemDestroyed(QObject*)));
}
d->movingItems[item] = state;
d->performMovement(0, state);
if (!d->timerId) {
d->timerId = startTimer(MIN_TICK_RATE);
d->time.restart();
}
return state->id;
}
int Animator::customAnimation(int frames, int duration, Animator::CurveShape curve,
QObject *receiver, const char *slot)
{
if (frames < 1 || duration < 1 || !receiver || !slot) {
return -1;
}
CustomAnimationState *state = new CustomAnimationState;
state->id = ++d->animId;
state->frames = frames;
state->currentFrame = 0;
state->curve = curve;
state->frameInterval = qMax(qreal(1.0), duration / qreal(state->frames));
state->interval = qMax(MIN_TICK_RATE_INT, state->frameInterval - (state->frameInterval % MIN_TICK_RATE_INT));
state->currentInterval = state->interval;
state->receiver = receiver;
state->slot = qstrdup(slot);
d->customAnims[state->id] = state;
disconnect(receiver, SIGNAL(destroyed(QObject*)),
this, SLOT(customAnimReceiverDestroyed(QObject*)));
connect(receiver, SIGNAL(destroyed(QObject*)),
this, SLOT(customAnimReceiverDestroyed(QObject*)));
// try with only progress as argument
if (!QMetaObject::invokeMethod(receiver, slot, Q_ARG(qreal, 0))) {
//try to pass also the animation id
QMetaObject::invokeMethod(receiver, slot, Q_ARG(qreal, 0), Q_ARG(int, state->id));
}
if (!d->timerId) {
d->timerId = startTimer(MIN_TICK_RATE);
d->time.restart();
}
return state->id;
}
void Animator::stopCustomAnimation(int id)
{
QHash<int, CustomAnimationState*>::iterator it = d->customAnims.find(id);
if (it != d->customAnims.end()) {
if (d->timerId) {
d->customAnimsToDelete.insert(it.value());
} else {
delete[] it.value()->slot;
delete it.value();
}
d->customAnims.erase(it);
}
//kDebug() << "stopCustomAnimation(AnimId " << id << ") done";
}
void Animator::stopItemAnimation(int id)
{
QMutableHashIterator<QGraphicsItem*, AnimationState*> it(d->animatedItems);
while (it.hasNext()) {
it.next();
if (it.value()->id == id) {
if (d->timerId) {
d->animatedItemsToDelete.insert(it.value());
} else {
delete it.value();
}
it.remove();
return;
}
}
}
void Animator::stopItemMovement(int id)
{
QMutableHashIterator<QGraphicsItem*, MovementState*> it(d->movingItems);
while (it.hasNext()) {
it.next();
if (it.value()->id == id) {
if (d->timerId) {
d->movingItemsToDelete.insert(it.value());
} else {
delete it.value();
}
it.remove();
return;
}
}
}
int Animator::animateElement(QGraphicsItem *item, Animation animation)
{
//kDebug() << "startElementAnimation(AnimId " << animation << ")";
int frames = d->driver->elementAnimationFps(animation);
int duration = d->driver->animationDuration(animation);
ElementAnimationState *state = new ElementAnimationState;
state->item = item;
state->curve = d->driver->elementAnimationCurve(animation);
state->animation = animation;
state->frames = qMax(1.0, frames * (duration / 1000.0)); //krazy:exclude=qminmax
state->currentFrame = 0;
state->interval = duration / qreal(state->frames);
state->interval = qMax(MIN_TICK_RATE_INT, state->interval - (state->interval % MIN_TICK_RATE_INT));
state->currentInterval = state->interval;
state->id = ++d->animId;
state->qobj = dynamic_cast<QObject*>(item);
if (state->qobj) {
disconnect(state->qobj, SIGNAL(destroyed(QObject*)),
this, SLOT(animatedElementDestroyed(QObject*)));
connect(state->qobj, SIGNAL(destroyed(QObject*)),
this, SLOT(animatedElementDestroyed(QObject*)));
}
//kDebug() << "animateElement " << animation << ", interval: "
// << state->interval << ", frames: " << state->frames;
bool needTimer = true;
if (state->frames < 1) {
state->frames = 1;
state->currentFrame = 1;
needTimer = false;
}
d->animatedElements[state->id] = state;
//kDebug() << "startElementAnimation(AnimId " << animation << ") returning " << state->id;
if (needTimer && !d->timerId) {
// start a 20fps timer;
d->timerId = startTimer(MIN_TICK_RATE);
d->time.restart();
}
return state->id;
}
void Animator::stopElementAnimation(int id)
{
QHash<int, ElementAnimationState*>::iterator it = d->animatedElements.find(id);
if (it != d->animatedElements.end()) {
if (d->timerId) {
d->animatedElementsToDelete.insert(it.value());
} else {
delete it.value();
}
d->animatedElements.erase(it);
}
//kDebug() << "stopElementAnimation(AnimId " << id << ") done";
}
void Animator::setInitialPixmap(int id, const QPixmap &pixmap)
{
QHash<int, ElementAnimationState*>::iterator it = d->animatedElements.find(id);
if (it == d->animatedElements.end()) {
kDebug() << "No entry found for id " << id;
return;
}
it.value()->pixmap = pixmap;
}
QPixmap Animator::currentPixmap(int id)
{
QHash<int, ElementAnimationState*>::const_iterator it = d->animatedElements.constFind(id);
if (it == d->animatedElements.constEnd()) {
//kDebug() << "Animator::currentPixmap(" << id << ") found no entry for it!";
return QPixmap();
}
ElementAnimationState *state = it.value();
qreal progress = d->calculateProgress(state->currentFrame * state->interval,
state->frames * state->interval,
state->curve);
//kDebug() << "Animator::currentPixmap(" << id << " at " << progress;
switch (state->animation) {
case AppearAnimation:
return d->driver->elementAppear(progress, state->pixmap);
break;
case DisappearAnimation:
return d->driver->elementDisappear(progress, state->pixmap);
break;
case ActivateAnimation:
break;
default:
kDebug() << "Unsupported animation type.";
}
return state->pixmap;
}
bool Animator::isAnimating() const
{
return (!d->animatedItems.isEmpty() ||
!d->movingItems.isEmpty() ||
!d->animatedElements.isEmpty() ||
!d->customAnims.isEmpty());
}
void Animator::timerEvent(QTimerEvent *event)
{
if (event->timerId() != d->timerId) {
QObject::timerEvent(event);
return;
}
Q_UNUSED(event)
bool animationsRemain = false;
int elapsed = MIN_TICK_RATE;
if (d->time.elapsed() > elapsed) {
elapsed = d->time.elapsed();
}
d->time.restart();
//kDebug() << "timeEvent, elapsed time: " << elapsed;
foreach (AnimationState *state, d->animatedItems) {
if (d->animatedItemsToDelete.contains(state)) {
continue;
}
if (state->currentInterval <= elapsed) {
// we need to step forward!
state->currentFrame +=
(KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects) ?
qMax(1, elapsed / state->interval) : state->frames - state->currentFrame;
if (state->currentFrame < state->frames) {
qreal progress = d->calculateProgress(state->currentFrame * state->interval,
state->frames * state->interval,
state->curve);
d->performAnimation(progress, state);
state->currentInterval = state->interval;
animationsRemain = true;
} else {
d->performAnimation(1, state);
d->animatedItems.erase(d->animatedItems.find(state->item));
emit animationFinished(state->item, state->animation);
d->animatedItemsToDelete.insert(state);
}
} else {
state->currentInterval -= elapsed;
animationsRemain = true;
}
}
foreach (MovementState *state, d->movingItems) {
if (d->movingItemsToDelete.contains(state)) {
continue;
}
if (state->currentInterval <= elapsed) {
// we need to step forward!
state->currentFrame +=
(KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects) ?
qMax(1, elapsed / state->interval) : state->frames - state->currentFrame;
if (state->currentFrame < state->frames) {
//kDebug() << "movement";
qreal progress = d->calculateProgress(state->currentFrame * state->interval,
state->frames * state->interval,
state->curve);
d->performMovement(progress, state);
animationsRemain = true;
} else {
//kDebug() << "movement";
d->performMovement(1, state);
d->movingItems.erase(d->movingItems.find(state->item));
emit movementFinished(state->item);
d->movingItemsToDelete.insert(state);
}
} else {
state->currentInterval -= elapsed;
animationsRemain = true;
}
}
foreach (ElementAnimationState *state, d->animatedElements) {
if (d->animatedElementsToDelete.contains(state)) {
continue;
}
if (state->currentFrame == state->frames) {
//kDebug() << "skipping" << state->id << "as it is already at frame"
// << state->currentFrame << "of" << state->frames;
// since we keep element animations around until they are
// removed, we will end up with finished animations in the queue;
// just skip them
continue;
}
if (state->currentInterval <= elapsed) {
// we need to step forward!
/*kDebug() << "stepping forwards element anim " << state->id
<< " from " << state->currentFrame
<< " by " << qMax(1, elapsed / state->interval) << " to "
<< state->currentFrame + qMax(1, elapsed / state->interval) << endl;*/
state->currentFrame +=
(KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects) ?
qMax(1, elapsed / state->interval) : state->frames - state->currentFrame;
state->item->update();
if (state->currentFrame < state->frames) {
state->currentInterval = state->interval;
animationsRemain = true;
} else {
d->animatedElements.remove(state->id);
emit elementAnimationFinished(state->id);
d->animatedElementsToDelete.insert(state);
}
} else {
state->currentInterval -= elapsed;
animationsRemain = true;
}
}
foreach (CustomAnimationState *state, d->customAnims) {
if (d->customAnimsToDelete.contains(state)) {
continue;
}
if (state->currentInterval <= elapsed) {
// advance the frame
state->currentFrame +=
(KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects) ?
qMax(1, elapsed / state->frameInterval) : state->frames - state->currentFrame;
/*kDebug() << "custom anim for" << state->receiver
<< "to slot" << state->slot
<< "with interval of" << state->interval
<< "at frame" << state->currentFrame;*/
if (state->currentFrame < state->frames) {
//kDebug () << "not the final frame";
state->currentInterval = state->interval;
animationsRemain = true;
// signal the object
// try with only progress as argument
qreal progress = d->calculateProgress(state->currentFrame * state->interval,
state->frames * state->interval,
state->curve);
if (!QMetaObject::invokeMethod(state->receiver, state->slot, Q_ARG(qreal, progress))) {
//if fails try to add the animation id
QMetaObject::invokeMethod(state->receiver, state->slot, Q_ARG(qreal, progress),
Q_ARG(int, state->id));
}
} else {
if (!QMetaObject::invokeMethod(state->receiver, state->slot, Q_ARG(qreal, 1))) {
QMetaObject::invokeMethod(state->receiver, state->slot, Q_ARG(qreal, 1), Q_ARG(int, state->id));
}
d->customAnims.erase(d->customAnims.find(state->id));
emit customAnimationFinished(state->id);
d->customAnimsToDelete.insert(state);
}
} else {
state->currentInterval -= elapsed;
animationsRemain = true;
}
}
if (!animationsRemain && d->timerId) {
killTimer(d->timerId);
d->timerId = 0;
}
d->cleanupStates();
}
void AnimatorPrivate::init(Animator *q)
{
//FIXME: usage between different applications?
KConfig c("plasmarc");
KConfigGroup cg(&c, "Animator");
QString pluginName = cg.readEntry("driver", "default");
if (!pluginName.isEmpty()) {
QString constraint = QString("[X-KDE-PluginInfo-Name] == '%1'").arg(pluginName);
KService::List offers = KServiceTypeTrader::self()->query("Plasma/Animator", constraint);
if (!offers.isEmpty()) {
QString error;
KPluginLoader plugin(*offers.first());
if (Plasma::isPluginVersionCompatible(plugin.pluginVersion())) {
driver = offers.first()->createInstance<Plasma::AnimationDriver>(q, QVariantList(), &error);
}
if (!driver) {
kDebug() << "Could not load requested animator "
<< offers.first() << ". Error given: " << error;
}
}
}
if (!driver) {
driver = new AnimationDriver(q);
}
}
void AnimatorPrivate::cleanupStates()
{
/*
kDebug() << animatedItemsToDelete.count() << animatedElementsToDelete.count()
<< movingItemsToDelete.count() << customAnimsToDelete.count();
*/
qDeleteAll(animatedItemsToDelete);
animatedItemsToDelete.clear();
qDeleteAll(animatedElementsToDelete);
animatedElementsToDelete.clear();
qDeleteAll(movingItemsToDelete);
movingItemsToDelete.clear();
QSetIterator<CustomAnimationState*> it(customAnimsToDelete);
while (it.hasNext()) {
CustomAnimationState *state = it.next();
delete[] state->slot;
delete state;
}
customAnimsToDelete.clear();
}
void Animator::registerScrollingManager(QGraphicsWidget *widget)
{
if (!d->scrollingManagers.contains(widget)) {
KineticScrolling *scroll = new KineticScrolling(widget);
d->scrollingManagers.insert(widget, scroll);
connect(scroll,
SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), this,
SLOT(scrollStateChanged(QAbstractAnimation::State, QAbstractAnimation::State)));
}
}
void Animator::unregisterScrollingManager(QGraphicsWidget *widget)
{
if (d->scrollingManagers.contains(widget)) {
disconnect(d->scrollingManagers.value(widget),
SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), this,
SLOT(scrollStateChanged(QAbstractAnimation::State, QAbstractAnimation::State)));
d->scrollingManagers.value(widget)->deleteLater();
d->scrollingManagers.remove(widget);
}
}
} // namespace Plasma

View File

@ -0,0 +1,72 @@
=== QGraphicsView dependencies ===
= HIGH IMPORTANCE =
Applet -> simple QObject, loads a qml component as child of containment from paths of its package.
Containment -> still subclass of applet, pure qobject (probably containment and applet change name)
PopupApplet -> is an applet/QGWidget, could die, icons could be properties
Corona -> Simple QObject keeps track of: Containments, scenes in case of SceneGraph and their association probably containment->setScreen() must be significantly different
View: QGraphicsView -> one library with QGraphicsView one with QSGCanvas
GlApplet -> BURN
Widgets DIE (or moved in the support lib)
Animations: DIE
Extenders: current api doesn't work well, -> components, out of main libplasma2
ToolTipManager/Content: QGW api, should go in components together with ToolTipData
AbstractToolx -> a component loaded from the containment
Dialog -> probably a component as well
= Medium importance =
Wallpaper: no qgw dep but needs to change to make sense in qml
Theme: no qgw, but if we change api we could use it directly in QML (notifying properties)
Svg/FrameSvg: no deps, to be used in QML pixmaprovider vs item? painter functions should still be maintained
AbstractDialogManager: DIE (other topic: qml conf dialogs)
= Completely independent =
service, servicejob runnersyntax runnermanager runnercontext querymatch : ok
PluginLoader: ok
plasma.h: global enums, will there be an upstream way to register them?
PaintUtils -> probably useless
Package, ok
Delegate -> BURN
DataengineManager, DataEngine, dataContainer : ok
Context -> ok
ContainmentActionsConfig, ContainmentActions: ok
ConfigLoader: ok
Animator -> BURN
AnimationDriver -> BURN
AbstractRunner: ok

View File

@ -55,6 +55,7 @@
#include "plasma/theme.h"
#include "plasma/widgets/scrollwidget.h"
#include "plasma/windoweffects.h"
#include "plasma/private/windowshadows_p.h"
#ifdef Q_WS_X11
#include <X11/Xlib.h>
@ -94,6 +95,11 @@ void DialogPrivate::scheduleBorderCheck(bool triggeredByResize)
void DialogPrivate::themeChanged()
{
checkBorders(false);
if (background->hasElement("shadow-top")) {
WindowShadows::self()->addWindow(q);
} else {
WindowShadows::self()->removeWindow(q);
}
const bool translucency = Plasma::Theme::defaultTheme()->windowTranslucencyEnabled();
// WA_NoSystemBackground is going to fail combined with sliding popups, but is needed
@ -292,7 +298,9 @@ void Dialog::syncToGraphicsWidget()
d->resizeStartCorner = -1;
QSize prevSize = size();
/*
#ifndef NDEBUG
kDebug() << "Widget size:" << graphicsWidget->size()
#endif
<< "| Widget size hint:" << graphicsWidget->effectiveSizeHint(Qt::PreferredSize)
<< "| Widget minsize hint:" << graphicsWidget->minimumSize()
<< "| Widget maxsize hint:" << graphicsWidget->maximumSize()
@ -655,8 +663,7 @@ void Dialog::setGraphicsWidget(QGraphicsWidget *widget)
}
}
//KDE5 FIXME: should be const
QGraphicsWidget *Dialog::graphicsWidget()
QGraphicsWidget *Dialog::graphicsWidget() const
{
return d->graphicsWidgetPtr.data();
}

View File

@ -84,7 +84,7 @@ class PLASMA_EXPORT Dialog : public QWidget
/**
* @return the graphics widget shown in this dialog
*/
QGraphicsWidget *graphicsWidget();
QGraphicsWidget *graphicsWidget() const;
/**
* @param corners the corners the resize handlers should be placed in.

View File

@ -35,6 +35,7 @@
#include "extenderitem.h"
#include "framesvg.h"
#include "paintutils.h"
#include "pluginloader.h"
#include "popupapplet.h"
#include "svg.h"
#include "theme.h"
@ -446,13 +447,17 @@ void Extender::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
//targetting.
PopupApplet *popupApplet = qobject_cast<PopupApplet*>(d->applet.data());
if (popupApplet && sourceExtender != this) {
#ifndef NDEBUG
kDebug() << "leaving another extender then the extender we started, so hide the popup.";
#endif
popupApplet->showPopup(250);
}
//Hide popups when we drag the last item away.
if (popupApplet && sourceExtender == this && (attachedItems().count() < 2)) {
#ifndef NDEBUG
kDebug() << "leaving the extender, and there are no more attached items so hide the popup.";
#endif
popupApplet->hidePopup();
}
@ -462,7 +467,9 @@ void Extender::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
if (extenderApplet && sourceExtender == this && attachedItems().count() < 2 &&
extenderApplet->formFactor() != Plasma::Horizontal &&
extenderApplet->formFactor() != Plasma::Vertical) {
#ifndef NDEBUG
kDebug() << "leaving the internal extender container, so hide the applet and it's handle.";
#endif
extenderApplet->hide();
AppletHandle *handle = dynamic_cast<AppletHandle*>(extenderApplet->parentItem());
if (handle) {
@ -507,9 +514,13 @@ void Extender::itemAddedEvent(ExtenderItem *item, const QPointF &pos)
d->layout->addItem(item);
}
} else {
#ifndef NDEBUG
kDebug() << "inserting at" << pos << d->insertIndexFromPos(pos) << item->size();
#endif
d->layout->insertItem(d->insertIndexFromPos(pos), item);
#ifndef NDEBUG
kDebug() << item->size();
#endif
}
}
@ -744,8 +755,12 @@ void ExtenderPrivate::loadExtenderItems()
bool temporarySourceApplet = false;
#ifndef NDEBUG
kDebug() << "applet id = " << applet.data()->id();
#endif
#ifndef NDEBUG
kDebug() << "sourceappletid = " << sourceAppletId;
#endif
//find the source applet.
Applet *sourceApplet = 0;
@ -776,16 +791,22 @@ void ExtenderPrivate::loadExtenderItems()
//There is no source applet. We just instantiate one just for the sake of creating
//detachables.
if (!sourceApplet) {
#ifndef NDEBUG
kDebug() << "creating a temporary applet as factory";
sourceApplet = Applet::load(appletName);
#endif
sourceApplet = PluginLoader::self()->loadApplet(appletName);
temporarySourceApplet = true;
//TODO: maybe add an option to applet to indicate that it shouldn't be deleted after
//having used it as factory.
}
if (!sourceApplet) {
#ifndef NDEBUG
kDebug() << "sourceApplet is null? appletName = " << appletName;
#endif
#ifndef NDEBUG
kDebug() << " extenderItemId = " << extenderItemId;
#endif
} else {
ExtenderItem *item;
if (dg.readEntry("isGroup", false)) {

View File

@ -379,7 +379,6 @@ int ExtenderGroupPrivate::insertIndexFromPos(const QPointF &pos) const
{
int insertIndex = -1;
//XXX: duplicated from panel
if (pos != QPointF(-1, -1)) {
for (int i = 0; i < layout->count(); ++i) {
QRectF siblingGeometry = layout->itemAt(i)->geometry();

View File

@ -406,7 +406,9 @@ void ExtenderItem::setExtender(Extender *extender, const QPointF &pos)
KConfigGroup extenderItemGroup(corona->config(), "DetachedExtenderItems");
if (isDetached()) {
#ifndef NDEBUG
kDebug() << "detached, adding entry to the global group";
#endif
KConfigGroup itemConfig = extenderItemGroup.group(QString::number(d->extenderItemId));
itemConfig.writeEntry("sourceAppletPluginName",
config().readEntry("sourceAppletPluginName", ""));
@ -415,7 +417,9 @@ void ExtenderItem::setExtender(Extender *extender, const QPointF &pos)
itemConfig.writeEntry("extenderItemName",
config().readEntry("extenderItemName", ""));
} else if (extenderItemGroup.hasGroup(QString::number(d->extenderItemId))) {
#ifndef NDEBUG
kDebug() << "no longer detached, removing entry from the global group";
#endif
extenderItemGroup.deleteGroup(QString::number(d->extenderItemId));
}
@ -438,12 +442,6 @@ Extender *ExtenderItem::extender() const
return d->extender;
}
//TODO KDE5: only one setGroup()
void ExtenderItem::setGroup(ExtenderGroup *group)
{
setGroup(group, QPointF(-1, -1));
}
void ExtenderItem::setGroup(ExtenderGroup *group, const QPointF &pos)
{
if (isGroup()) {
@ -460,7 +458,9 @@ void ExtenderItem::setGroup(ExtenderGroup *group, const QPointF &pos)
config().writeEntry("group", group->name());
//TODO: move to another extender if the group we set is actually detached.
if (group->extender() != extender()) {
#ifndef NDEBUG
kDebug() << "moving to another extender because we're joining a detached group.";
#endif
setExtender(group->extender());
}
group->d->addItemToGroup(this, pos);
@ -730,7 +730,9 @@ void ExtenderItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
if (extenderApplet && d->extender->attachedItems().count() < 2 &&
extenderApplet->formFactor() != Plasma::Horizontal &&
extenderApplet->formFactor() != Plasma::Vertical) {
#ifndef NDEBUG
kDebug() << "leaving the internal extender container, so hide the applet and it's handle.";
#endif
extenderApplet->hide();
}
@ -1008,7 +1010,9 @@ Applet *ExtenderItemPrivate::hostApplet() const
void ExtenderItemPrivate::themeChanged()
{
#ifndef NDEBUG
kDebug();
#endif
if (dragStarted) {
background->setImagePath("opaque/dialogs/background");
background->setEnabledBorders(FrameSvg::AllBorders);

View File

@ -176,19 +176,9 @@ class PLASMA_EXPORT ExtenderItem : public QGraphicsWidget
/**
* @param group the group you want this item to belong to. Note that you can't nest
* ExtenderGroups.
* @since 4.3
*/
void setGroup(ExtenderGroup *group);
/**
* @param group the group you want this item to belong to. Note that you can't nest
* ExtenderGroups.
*
* @param group the new group
* @param pos position inside the extender group
* @since 4.5
*/
void setGroup(ExtenderGroup *group, const QPointF &pos);
void setGroup(ExtenderGroup *group, const QPointF &pos = QPointF(-1, -1));
/**
* @returns the group this item belongs to.

View File

@ -321,7 +321,9 @@ void FrameSvg::resizeFrame(const QSizeF &size)
}
if (size.isEmpty()) {
#ifndef NDEBUG
kDebug() << "Invalid size" << size;
#endif
return;
}
@ -539,7 +541,9 @@ void FrameSvg::paintFrame(QPainter *painter, const QPointF &pos)
FrameSvgPrivate::~FrameSvgPrivate()
{
#ifdef DEBUG_FRAMESVG_CACHE
#ifndef NDEBUG
kDebug() << "*************" << q << q->imagePath() << "****************";
#endif
#endif
QHashIterator<QString, FrameData *> it(frames);
@ -551,17 +555,23 @@ FrameSvgPrivate::~FrameSvgPrivate()
if (it.value()->removeRefs(q)) {
const QString key = cacheId(it.value(), it.key());
#ifdef DEBUG_FRAMESVG_CACHE
#ifndef NDEBUG
kDebug() << "2. Removing it" << key << it.value() << it.value()->refcount() << s_sharedFrames.contains(key);
#endif
#endif
s_sharedFrames.remove(key);
delete it.value();
}
#ifdef DEBUG_FRAMESVG_CACHE
else {
#ifndef NDEBUG
kDebug() << "still shared:" << cacheId(it.value(), it.key()) << it.value() << it.value()->refcount() << it.value()->isUsed();
#endif
}
} else {
#ifndef NDEBUG
kDebug() << "lost our value for" << it.key();
#endif
#endif
}
}
@ -573,16 +583,24 @@ FrameSvgPrivate::~FrameSvgPrivate()
it2.next();
const int rc = it2.value()->refcount();
if (rc == 0) {
#ifndef NDEBUG
kDebug() << " LOST!" << it2.key() << rc << it2.value();// << it2.value()->references;
#endif
} else {
#ifndef NDEBUG
kDebug() << " " << it2.key() << rc << it2.value();
#endif
foreach (FrameSvg *data, it2.value()->references.keys()) {
#ifndef NDEBUG
kDebug( )<< " " << (void*)data << it2.value()->references[data];
#endif
}
shares += rc - 1;
}
}
#ifndef NDEBUG
kDebug() << "#####################################" << s_sharedFrames.count() << ", pixmaps saved:" << shares;
#endif
#endif
frames.clear();
@ -746,7 +764,9 @@ void FrameSvgPrivate::generateFrameBackground(FrameData *frame)
if (!size.isValid()) {
#ifndef NDEBUG
kDebug() << "Invalid frame size" << size;
#endif
return;
}
if (size.width() >= MAX_FRAME_SIZE || size.height() >= MAX_FRAME_SIZE) {

View File

@ -1,213 +0,0 @@
/*
* Copyright 2007 Zack Rusin <zack@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 "glapplet.h"
#include <QtOpenGL/QGLPixelBuffer>
#include <QtGui/QPainter>
#include <QtGui/QImage>
namespace Plasma {
class GLAppletPrivate
{
public:
GLAppletPrivate()
{
init();
}
~GLAppletPrivate()
{
delete pbuf;
delete dummy;
}
void init()
{
dummy = new QGLWidget((QWidget *) 0);
QGLFormat format = QGLFormat::defaultFormat();
format.setSampleBuffers(true);
format.setAlphaBufferSize(8);
//dummy size construction
pbuf = new QGLPixelBuffer(300, 300, format, dummy);
if (pbuf->isValid()) {
pbuf->makeCurrent();
}
}
void updateGlSize(const QSize &size)
{
if (size.width() > pbuf->width() ||
size.height() > pbuf->height()) {
QGLFormat format = pbuf->format();
delete pbuf;
pbuf = new QGLPixelBuffer(size, format, dummy);
}
}
public:
QGLPixelBuffer *pbuf;
QGLWidget *dummy;
};
GLApplet::GLApplet(QGraphicsItem *parent,
const QString &serviceId,
int appletId)
: Applet(parent, serviceId, appletId),
d(new GLAppletPrivate)
{
if (!d->dummy->isValid() ||
!QGLPixelBuffer::hasOpenGLPbuffers() ||
!d->pbuf->isValid()) {
setFailedToLaunch(true, i18n("This system does not support OpenGL widgets."));
}
}
GLApplet::GLApplet(QObject *parent, const QVariantList &args)
: Applet(parent, args),
d(new GLAppletPrivate)
{
if (!d->dummy->isValid() ||
!QGLPixelBuffer::hasOpenGLPbuffers() ||
!d->pbuf->isValid()) {
setFailedToLaunch(true, i18n("This system does not support OpenGL widgets."));
}
}
GLApplet::~GLApplet()
{
delete d;
}
GLuint GLApplet::bindTexture(const QImage &image, GLenum target)
{
Q_ASSERT(d->pbuf);
if (!d->dummy->isValid()) {
return 0;
}
return d->dummy->bindTexture(image, target);
}
void GLApplet::deleteTexture(GLuint textureId)
{
Q_ASSERT(d->pbuf);
d->dummy->deleteTexture(textureId);
}
void GLApplet::paintGLInterface(QPainter *painter,
const QStyleOptionGraphicsItem *option)
{
Q_UNUSED(painter)
Q_UNUSED(option)
}
static inline QPainterPath headerPath(const QRectF &r, int roundness,
int headerHeight=10)
{
QPainterPath path;
int xRnd = roundness;
int yRnd = roundness;
if (r.width() > r.height()) {
xRnd = int(roundness * r.height() / r.width());
} else {
yRnd = int(roundness * r.width() / r.height());
}
if(xRnd >= 100) { // fix ranges
xRnd = 99;
}
if(yRnd >= 100) {
yRnd = 99;
}
if(xRnd <= 0 || yRnd <= 0) { // add normal rectangle
path.addRect(r);
return path;
}
QRectF rect = r.normalized();
if (rect.isNull()) {
return path;
}
qreal x = rect.x();
qreal y = rect.y();
qreal w = rect.width();
qreal h = rect.height();
qreal rxx = w * xRnd / 200;
qreal ryy = h * yRnd / 200;
// were there overflows?
if (rxx < 0) {
rxx = w / 200 * xRnd;
}
if (ryy < 0) {
ryy = h / 200 * yRnd;
}
qreal rxx2 = 2 * rxx;
qreal ryy2 = 2 * ryy;
path.arcMoveTo(x, y, rxx2, ryy2, 90);
path.arcTo(x, y, rxx2, ryy2, 90, 90);
QPointF pt = path.currentPosition();
path.lineTo(x, pt.y() + headerHeight);
path.lineTo(x + w, pt.y() + headerHeight);
path.lineTo(x + w, pt.y());
path.arcTo(x + w - rxx2, y, rxx2, ryy2, 0, 90);
path.closeSubpath();
return path;
}
void GLApplet::paintInterface(QPainter *painter,
const QStyleOptionGraphicsItem *option,
const QRect &contentsRect)
{
Q_UNUSED(contentsRect)
Q_ASSERT(d->pbuf);
if ((!d->dummy->isValid() ||
!d->pbuf->isValid())) {
if (!hasFailedToLaunch()) {
setFailedToLaunch(true, i18n("Your machine does not support OpenGL widgets."));
}
return;
}
d->pbuf->makeCurrent();
QMatrix m = painter->worldMatrix();
QRect deviceRect = m.mapRect(QRect(QPoint(23, 25), boundingRect().size().toSize()));
d->updateGlSize(deviceRect.size());
// redirect this widget's painting into the pbuffer
QPainter p(d->pbuf);
paintGLInterface(&p, option);
// draw the pbuffer contents to the backingstore
QImage image = d->pbuf->toImage();
painter->drawImage(0, 0, image);
}
void GLApplet::makeCurrent()
{
if (!d->dummy->isValid() || !d->pbuf->isValid()) {
d->dummy->makeCurrent();
}
}
} // Plasma namespace
#include "glapplet.moc"

View File

@ -1,88 +0,0 @@
/*
* Copyright 2007 Zack Rusin <zack@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_GLAPPLET_H
#define PLASMA_GLAPPLET_H
#include <plasma/applet.h>
#include <QtOpenGL/QGLWidget>
namespace Plasma
{
class GLAppletPrivate;
/**
* @class GLApplet plasma/glapplet.h <Plasma/GLApplet>
*
* @short Plasma Applet that is fully rendered using OpengGL
*/
class PLASMA_EXPORT_DEPRECATED GLApplet : public Applet
{
Q_OBJECT
public:
/**
* @param parent the QGraphicsItem this applet is parented to
* @param serviceId the name of the .desktop file containing the
* information about the widget
* @param appletId a unique id used to differentiate between multiple
* instances of the same Applet type
*/
GLApplet(QGraphicsItem *parent,
const QString &serviceId,
int appletId);
/**
* This constructor is to be used with the plugin loading systems
* found in KPluginInfo and KService. The argument list is expected
* to have two elements: the KService service ID for the desktop entry
* and an applet ID which must be a base 10 number.
*
* @param parent a QObject parent; you probably want to pass in 0
* @param args a list of strings containing two entries: the service id
* and the applet id
*/
GLApplet(QObject *parent, const QVariantList &args);
~GLApplet();
GLuint bindTexture(const QImage &image, GLenum target = GL_TEXTURE_2D);
void deleteTexture(GLuint texture_id);
/**
* Reimplement this method to render using OpenGL. QPainter passed
* to this method will always use OpenGL engine and rendering
* using OpenGL api directly is supported.
*/
virtual void paintGLInterface(QPainter *painter,
const QStyleOptionGraphicsItem *option);
void makeCurrent();
private:
virtual void paintInterface(QPainter *painter,
const QStyleOptionGraphicsItem *option,
const QRect &contentsRect);
private:
GLAppletPrivate *const d;
};
}
#endif

File diff suppressed because it is too large Load Diff

366
package.h
View File

@ -1,6 +1,5 @@
/******************************************************************************
* Copyright 2007 by Aaron Seigo <aseigo@kde.org> *
* Copyright 2007 by Riccardo Iaconelli <riccardo@kde.org> *
* Copyright 2007-2011 by Aaron Seigo <aseigo@kde.org> *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
@ -23,8 +22,9 @@
#include <QtCore/QStringList>
#include <kplugininfo.h>
#include <plasma/plasma.h>
#include <plasma/packagestructure.h>
#include <plasma/plasma_export.h>
namespace Plasma
@ -33,38 +33,57 @@ namespace Plasma
/**
* @class Package plasma/package.h <Plasma/Package>
*
* @short object representing an installed Plasmagik package
**/
* @short object representing an installed Plasma package
*
* Package defines what is in a package and provides easy access to the contents.
*
* To define a package, one might write the following code:
*
@code
Package package;
package.addDirectoryDefinition("images", "pics/", i18n("Images"));
QStringList mimeTypes;
mimeTypes << "image/svg" << "image/png" << "image/jpeg";
package.setMimeTypes("images", mimeTypes);
package.addDirectoryDefinition("scripts", "code/", i18n("Executable Scripts"));
mimeTypes.clear();
mimeTypes << "text/\*";
package.setMimeTypes("scripts", mimeTypes);
package.addFileDefinition("mainscript", "code/main.js", i18n("Main Script File"));
package.setRequired("mainscript", true);
@endcode
* One may also choose to create a subclass of PackageStructure and include the setup
* in the constructor.
*
* Either way, Package creates a self-documenting contract between the packager and
* the application without exposing package internals such as actual on-disk structure
* of the package or requiring that all contents be explicitly known ahead of time.
*
* Subclassing PackageStructure does have provide a number of potential const benefits:
* * the package can be notified of path changes via the virtual pathChanged() method
* * the subclass may implement mechanisms to install and remove packages using the
* virtual installPackage and uninstallPackage methods
* * subclasses can be compiled as plugins for easy re-use
**/
//TODO: write documentation on USING a package
class PackageMetadata;
class PackagePrivate;
class PackageStructure;
class PLASMA_EXPORT Package
{
public:
public:
/**
* Default constructor that creates an invalid Package
* Default constructor
*
* @arg structure if a NULL pointer is passed in, this will creates an empty (invalid) Package;
* otherwise the structure is allowed to set up the Package's initial layout
* @since 4.6
*/
explicit Package();
/**
* Construct a Package object
*
* @param packageRoot path to the package installation root
* @param package the name of the package
* @param structure the package structure describing this package
**/
Package(const QString &packageRoot, const QString &package,
PackageStructure::Ptr structure);
/**
* Construct a Package object.
*
* @param packagePath full path to the package directory
* @param structure the package structure describing this package
*/
Package(const QString &packagePath, PackageStructure::Ptr structure);
explicit Package(PackageStructure *structure = 0);
/**
* Copy constructore
@ -81,45 +100,10 @@ class PLASMA_EXPORT Package
Package &operator=(const Package &rhs);
/**
* @return true if all the required components as defined in
* the PackageStructure exist
* @return true if all the required components exist
**/
bool isValid() const;
/**
* Get the path to a given file.
*
* @param fileType the type of file to look for, as defined in the
* package structure
* @param filename the name of the file
* @return path to the file on disk. QString() if not found.
**/
QString filePath(const char *fileType, const QString &filename) const;
/**
* Get the path to a given file.
*
* @param fileType the type of file to look for, as defined in the
* package structure. The type must refer to a file
* in the package structure and not a directory.
* @return path to the file on disk. QString() if not found
**/
QString filePath(const char *fileType) const;
/**
* Get the list of files of a given type.
*
* @param fileType the type of file to look for, as defined in the
* package structure.
* @return list of files by name, suitable for passing to filePath
**/
QStringList entryList(const char *fileType) const;
/**
* @return the package metadata object.
*/
PackageMetadata metadata() const;
/**
* Sets the path to the root of this package
* @param path and absolute path
@ -127,31 +111,76 @@ class PLASMA_EXPORT Package
*/
void setPath(const QString &path);
/**
* Publish this package on the network.
* @param methods the ways to announce this package on the network.
*/
void publish(AnnouncementMethods methods, const QString &name);
/**
* Remove this package from the network.
*/
void unpublish(const QString &name = QString());
/**
* @returns whether or not this service is currently published on the network.
*/
bool isPublished() const;
/**
* @return the path to the root of this particular package
*/
const QString path() const;
/**
* @return the PackageStructure use in this Package
* Get the path to a given file based on the key and.an optional filename.
* Example: finding the main script in a scripting package:
* filePath("mainscript")
*
* Example: finding a specific image in the images directory:
* filePath("images", "myimage.png")
*
* @param key the key of the file type to look for,
* @param filename optional name of the file to locate within the package
* @return path to the file on disk. QString() if not found.
**/
QString filePath(const char *key, const QString &filename = QString()) const;
/**
* Get the list of files of a given type.
*
* @param fileType the type of file to look for, as defined in the
* package structure.
* @return list of files by name, suitable for passing to filePath
**/
QStringList entryList(const char *key) const;
/**
* @return user visible name for the given entry
**/
QString name(const char *key) const;
/**
* @return true if the item at path exists and is required
**/
bool isRequired(const char *key) const;
/**
* @return the mimeTypes associated with the path, if any
**/
QStringList mimeTypes(const char *key) const;
/**
* @return the prefix paths inserted between the base path and content entries, in order of priority.
* When searching for a file, all paths will be tried in order.
* @since 4.6
*/
const PackageStructure::Ptr structure() const;
QStringList contentsPrefixPaths() const;
/**
* @return preferred package root. This defaults to plasma/plasmoids/
*/
QString defaultPackageRoot() const;
/**
* @return service prefix used in desktop files. This defaults to plasma-applet-
*/
QString servicePrefix() const;
/**
* @return true if paths/symlinks outside the package itself should be followed.
* By default this is set to false for security reasons.
*/
bool allowExternalPaths() const;
/**
* @return the package metadata object.
*/
KPluginInfo metadata() const;
/**
* @return a SHA1 hash digest of the contents of the package in hexadecimal form
@ -160,84 +189,143 @@ class PLASMA_EXPORT Package
QString contentsHash() const;
/**
* Returns a list of all installed packages by name
* Adds a directory to the structure of the package. It is added as
* a not-required element with no associated mimeTypes.
*
* @param packageRoot path to the directory where Plasmagik packages
* have been installed to
* @return a list of installed Plasmagik packages
* Starting in 4.6, if an entry with the given key
* already exists, the path is added to it as a search alternative.
*
* @param key used as an internal label for this directory
* @param path the path within the package for this directory
* @param name the user visible (translated) name for the directory
**/
static QStringList listInstalled(const QString &packageRoot);
void addDirectoryDefinition(const char *key, const QString &path, const QString &name);
/**
* Returns a list of all paths of installed packages in the given root
* Adds a file to the structure of the package. It is added as
* a not-required element with no associated mimeTypes.
*
* @param packageRoot path to the directory where Plasmagik packages
* have been installed to
* @return a list of installed Plasmagik packages by path
* Starting in 4.6, if an entry with the given key
* already exists, the path is added to it as a search alternative.
*
* @param key used as an internal label for this file
* @param path the path within the package for this file
* @param name the user visible (translated) name for the file
**/
static QStringList listInstalledPaths(const QString &packageRoot);
void addFileDefinition(const char *key, const QString &path, const QString &name);
/**
* Installs a package.
* Removes a definition from the structure of the package.
* @since 4.6
* @param key the internal label of the file or directory to remove
*/
void removeDefinition(const char *key);
/**
* Sets whether or not a given part of the structure is required or not.
* The path must already have been added using addDirectoryDefinition
* or addFileDefinition.
*
* @param package path to the Plasmagik package
* @param key the entry within the package
* @param required true if this entry is required, false if not
*/
void setRequired(const char *key, bool required);
/**
* Defines the default mimeTypes for any definitions that do not have
* associated mimeTypes. Handy for packages with only one or predominantly
* one file type.
*
* @param mimeTypes a list of mimeTypes
**/
void setDefaultMimeTypes(QStringList mimeTypes);
/**
* Define mimeTypes for a given part of the structure
* The path must already have been added using addDirectoryDefinition
* or addFileDefinition.
*
* @param key the entry within the package
* @param mimeTypes a list of mimeTypes
**/
void setMimeTypes(const char *key, QStringList mimeTypes);
/**
* Sets the prefixes that all the contents in this package should
* appear under. This defaults to "contents/" and is added automatically
* between the base path and the entries as defined by the package
* structure. Multiple entries can be added.
* In this case each file request will be searched in all prefixes in order,
* and the first found will be returned.
*
* @param prefix paths the directory prefix to use
* @since 4.6
*/
void setContentsPrefixPaths(const QStringList &prefixPaths);
/**
* Sets service prefix.
*/
void setServicePrefix(const QString &servicePrefix);
/**
* Sets whether or not external paths/symlinks can be followed by a package
* @param allow true if paths/symlinks outside of the package should be followed,
* false if they should be rejected.
*/
void setAllowExternalPaths(bool allow);
/**
* Sets preferred package root.
*/
void setDefaultPackageRoot(const QString &packageRoot);
// Content structure description methods
/**
* @return all directories registered as part of this Package's structure
*/
QList<const char*> directories() const;
/**
* @return all directories registered as part of this Package's required structure
*/
QList<const char*> requiredDirectories() const;
/**
* @return all files registered as part of this Package's structure
*/
QList<const char*> files() const;
/**
* @return all files registered as part of this Package's required structure
*/
QList<const char*> requiredFiles() const;
/**
* Installs a package matching this package structure. By default installs a
* native Plasma::Package.
*
* @param archivePath path to the package archive file
* @param packageRoot path to the directory where the package should be
* installed to
* @param servicePrefix the prefix for the desktop file, so as not to interfere
* with unrelated services (eg: "plasma-applet-"). If no prefix
* is set (e.g. a QString() is passed in), then the package will NOT
* be registered as a service
* @return true on successful installation, false otherwise
**/
static bool installPackage(const QString &package,
const QString &packageRoot,
const QString &servicePrefix);
bool installPackage(const QString &archivePath, const QString &packageRoot);
/**
* Uninstalls a package.
* Uninstalls a package matching this package structure.
*
* @param package path to the Plasmagik package
* @param packageRoot path to the directory where the package should be
* installed to
* @param servicePrefix the prefix for the desktop file, so as not to interfere
* with unrelated services (eg: "plasma-applet-")
* @return true on successful uninstallation, false otherwise
**/
static bool uninstallPackage(const QString &package,
const QString &packageRoot,
const QString &servicePrefix);
/**
* Registers a package described by the given desktop file
*
* @param the full path to the desktop file (must be KPluginInfo compatible)
* @return true on success, false on failure
* @param packageName the name of the package to remove
* @param packageRoot path to the directory where the package should be installed to
* @return true on successful removal of the package, false otherwise
*/
static bool registerPackage(const PackageMetadata &data, const QString &iconPath);
bool uninstallPackage(const QString &packageName, const QString &packageRoot);
/**
* Creates a package based on the metadata from the files contained
* in the source directory
*
* @param metadata description of the package to create
* @param source path to local directory containing the individual
* files to be added to the package
* @param destination path to the package that should be created
* @param icon path to the package icon
**/
static bool createPackage(const PackageMetadata &metadata,
const QString &source,
const QString &destination,
const QString &icon = QString());
private:
PackagePrivate * const d;
friend class Applet;
friend class AppletPrivate;
private:
QExplicitlySharedDataPointer<PackagePrivate> d;
};
} // Namespace
}
Q_DECLARE_METATYPE(Plasma::Package)
#endif

View File

@ -1,309 +0,0 @@
/******************************************************************************
* Copyright 2007 by Riccardo Iaconelli <riccardo@kde.org> *
* *
* This library 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 of the License, or (at your option) any later version. *
* *
* This library 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 *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public License *
* along with this library; see the file COPYING.LIB. If not, write to *
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, *
* Boston, MA 02110-1301, USA. *
*******************************************************************************/
#include <packagemetadata.h>
#include <QDir>
#include <kconfiggroup.h>
#include <kdesktopfile.h>
namespace Plasma
{
class PackageMetadataPrivate
{
public:
PackageMetadataPrivate()
: type("Service")
{
}
QString name;
QString icon;
QString description;
QStringList keywords;
QString author;
QString email;
QString version;
QString website;
QString license;
QString app;
QString category;
QString requiredVersion;
QString pluginName;
QString type;
QString serviceType;
QString api;
KUrl location;
};
PackageMetadata::PackageMetadata(const PackageMetadata &other)
: d(new PackageMetadataPrivate(*other.d))
{
}
PackageMetadata &PackageMetadata::operator=(const PackageMetadata &other)
{
*d = *other.d;
return *this;
}
PackageMetadata::PackageMetadata(const QString &path)
: d(new PackageMetadataPrivate)
{
read(path);
}
PackageMetadata::~PackageMetadata()
{
delete d;
}
bool PackageMetadata::isValid() const
{
return ! (d->name.isEmpty() ||
d->author.isEmpty() ||
d->license.isEmpty() ||
d->type.isEmpty());
}
void PackageMetadata::write(const QString &filename) const
{
KDesktopFile cfg(filename);
KConfigGroup config = cfg.desktopGroup();
config.writeEntry("Encoding", "UTF-8");
config.writeEntry("Name", d->name);
config.writeEntry("Icon", d->icon);
config.writeEntry("Comment", d->description);
config.writeEntry("Keywords", d->keywords);
config.writeEntry("X-KDE-ServiceTypes", d->serviceType);
config.writeEntry("X-KDE-PluginInfo-Name", d->pluginName);
config.writeEntry("X-KDE-PluginInfo-Author", d->author);
config.writeEntry("X-KDE-PluginInfo-Email", d->email);
config.writeEntry("X-KDE-PluginInfo-Version", d->version);
config.writeEntry("X-KDE-PluginInfo-Website", d->website);
config.writeEntry("X-KDE-PluginInfo-License", d->license);
config.writeEntry("X-KDE-PluginInfo-Category", d->category);
config.writeEntry("X-Plasma-API", d->api);
config.writeEntry("X-KDE-ParentApp", d->app);
config.writeEntry("Type", d->type);
config.writeEntry("X-Plasma-RemoteLocation", d->location);
}
void PackageMetadata::read(const QString &filename)
{
if (filename.isEmpty()) {
return;
}
KDesktopFile cfg(filename);
KConfigGroup config = cfg.desktopGroup();
d->name = config.readEntry("Name", d->name);
d->icon = config.readEntry("Icon", d->icon);
d->description = config.readEntry("Comment", d->description);
d->keywords = config.readEntry("Keywords", d->keywords);
d->serviceType = config.readEntry("X-KDE-ServiceTypes", d->serviceType);
d->pluginName = config.readEntry("X-KDE-PluginInfo-Name", d->pluginName);
d->author = config.readEntry("X-KDE-PluginInfo-Author", d->author);
d->email = config.readEntry("X-KDE-PluginInfo-Email", d->email);
d->version = config.readEntry("X-KDE-PluginInfo-Version", d->version);
d->website = config.readEntry("X-KDE-PluginInfo-Website", d->website);
d->license = config.readEntry("X-KDE-PluginInfo-License", d->license);
d->category = config.readEntry("X-KDE-PluginInfo-Category", d->category);
d->api = config.readEntry("X-Plasma-API", d->api);
d->app = config.readEntry("X-KDE-ParentApp", d->app);
d->type = config.readEntry("Type", d->type);
d->location = config.readEntry("X-Plasma-RemoteLocation", d->location);
}
QString PackageMetadata::name() const
{
return d->name;
}
QString PackageMetadata::description() const
{
return d->description;
}
QString PackageMetadata::serviceType() const
{
return d->serviceType;
}
QString PackageMetadata::author() const
{
return d->author;
}
QString PackageMetadata::email() const
{
return d->email;
}
QString PackageMetadata::icon() const
{
return d->icon;
}
void PackageMetadata::setIcon(const QString &icon)
{
d->icon = icon;
}
QString PackageMetadata::version() const
{
return d->version;
}
QString PackageMetadata::website() const
{
return d->website;
}
QString PackageMetadata::license() const
{
return d->license;
}
QString PackageMetadata::application() const
{
return d->app;
}
QString PackageMetadata::category() const
{
return d->category;
}
void PackageMetadata::setKeywords(const QStringList &keywords)
{
d->keywords = keywords;
}
QStringList PackageMetadata::keywords() const
{
return d->keywords;
}
QString PackageMetadata::requiredVersion() const
{
return d->requiredVersion;
}
KUrl PackageMetadata::remoteLocation() const
{
return d->location;
}
QString PackageMetadata::type() const
{
return d->type;
}
QString PackageMetadata::implementationApi() const
{
return d->api;
}
void PackageMetadata::setImplementationApi(const QString &api)
{
d->api = api;
}
QString PackageMetadata::pluginName() const
{
return d->pluginName;
}
void PackageMetadata::setPluginName(const QString &pluginName)
{
d->pluginName = pluginName;
}
void PackageMetadata::setName(const QString &name)
{
d->name = name;
}
void PackageMetadata::setDescription(const QString &description)
{
d->description = description;
}
void PackageMetadata::setServiceType(const QString &serviceType)
{
d->serviceType = serviceType;
}
void PackageMetadata::setAuthor(const QString &author)
{
d->author = author;
}
void PackageMetadata::setEmail(const QString &email)
{
d->email = email;
}
void PackageMetadata::setVersion(const QString &version)
{
d->version = version;
}
void PackageMetadata::setWebsite(const QString &website)
{
d->website = website;
}
void PackageMetadata::setLicense(const QString &license)
{
d->license = license;
}
void PackageMetadata::setApplication(const QString &application)
{
d->app = application;
}
void PackageMetadata::setCategory(const QString &category)
{
d->category = category;
}
void PackageMetadata::setRequiredVersion(const QString &requiredVersion)
{
d->requiredVersion = requiredVersion;
}
void PackageMetadata::setRemoteLocation(const KUrl &location)
{
d->location = location;
}
void PackageMetadata::setType(const QString &type)
{
d->type = type;
}
} // namespace Plasma

View File

@ -1,213 +0,0 @@
/******************************************************************************
* Copyright 2007 by Riccardo Iaconelli <riccardo@kde.org> *
* *
* This library 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 of the License, or (at your option) any later version. *
* *
* This library 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 *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public License *
* along with this library; see the file COPYING.LIB. If not, write to *
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, *
* Boston, MA 02110-1301, USA. *
*******************************************************************************/
#ifndef PLASMA_PACKAGEMETADATA_H
#define PLASMA_PACKAGEMETADATA_H
#include <QtCore/QString>
#include <plasma/plasma_export.h>
#include <kurl.h>
namespace Plasma
{
class PackageMetadataPrivate;
/**
* @class PackageMetadata plasma/packagemetadata.h <Plasma/PackageMetadata>
*
* @short Provides metadata for a Package.
**/
class PLASMA_EXPORT PackageMetadata
{
public:
/**
* Constructs a metadata object using the values in the file at path
*
* @param path path to a metadata.desktop file
**/
explicit PackageMetadata(const QString &path = QString());
/**
* Copy constructor
**/
PackageMetadata(const PackageMetadata &other);
~PackageMetadata();
PackageMetadata &operator=(const PackageMetadata &other);
bool isValid() const;
/**
* Writes out the metadata to filename, which should be a .desktop
* file. It writes out the information in a format that is compatible
* with KPluginInfo
* @see KPluginInfo
*
* @param filename path to the file to write to
**/
void write(const QString &filename) const;
/**
* Reads in metadata from a file, which should be a .desktop
* file. It writes out the information in a format that is compatible
* with KPluginInfo
* @see KPluginInfo
*
* @param filename path to the file to write to
**/
void read(const QString &filename);
QString name() const;
QString description() const;
QStringList keywords() const;
QString serviceType() const;
QString author() const;
QString email() const;
QString version() const;
QString website() const;
QString license() const;
QString application() const;
QString category() const;
QString requiredVersion() const;
QString pluginName() const;
QString implementationApi() const;
KUrl remoteLocation() const;
QString type() const;
/**
* Set the name of the package used to displayed
* a short describing name.
*/
void setName(const QString &);
/**
* Set the description used to provide some general
* information what the package is about.
*/
void setDescription(const QString &);
/**
* Returns the icon name associated with this package, or QString() if none
* @since 4.5
*/
QString icon() const;
/**
* Set the icon name to be used with this package
* @since 4.5
*/
void setIcon(const QString &icon);
/**
* Set the keywords used to provide search and categorizations
* @param keywords the keywords to associate with this package
*/
void setKeywords(const QStringList &keywords);
/**
* Set the service-type which defines the X-KDE-ServiceTypes
* type within the desktop file. If not defined this
* defaults to "Plasma/Applet,Plasma/Containment" in the
* desktop file.
*/
void setServiceType(const QString &);
/**
* Set the name of the author of the package.
*/
void setAuthor(const QString &);
/**
* Set the E-Mail address of the author or of the project
* that provided the package.
*/
void setEmail(const QString &);
/**
* Set the version of the package.
*/
void setVersion(const QString &);
/**
* Set the website URL where the package is hosted or
* where additional details about the project are available.
*/
void setWebsite(const QString &);
/**
* Set the license the package is distributed under.
*/
void setLicense(const QString &);
/**
* Set the name of the application this package may
* belongs to. This is used only for display purposes
* so far.
*/
void setApplication(const QString &);
/**
* Sets the category this package belongs in
*/
void setCategory(const QString &);
/**
* Set the required version. See also the setVersion()
* method.
*/
void setRequiredVersion(const QString &);
/**
* Set the url where this package is hosted.
*/
void setRemoteLocation(const KUrl &);
/**
* Set the type of the package. If not defined this
* defaults to "Service" in the desktop file.
*/
void setType(const QString &type);
/**
* Set the plugin name of the package.
*
* The plugin name is used to locate the package;
* @code
* QString serviceName("plasma-applet-" + data.pluginName());
* QString service = KStandardDirs::locateLocal("services", serviceName + ".desktop");
* @endcode
*/
void setPluginName(const QString &name);
/**
* Set the implementation API this package uses.
*/
void setImplementationApi(const QString &api);
private:
PackageMetadataPrivate * const d;
};
}
#endif

View File

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright 2007 by Aaron Seigo <aseigo@kde.org> *
* Copyright 2011 by Aaron Seigo <aseigo@kde.org> *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
@ -19,639 +19,41 @@
#include "packagestructure.h"
#include "config-plasma.h"
#include <QDir>
#include <QMap>
#include <QFileInfo>
#include <kconfiggroup.h>
#include <kdebug.h>
#ifndef PLASMA_NO_KIO
#include <kio/job.h>
#endif
#include <kmimetype.h>
#include <kstandarddirs.h>
#include <kservicetypetrader.h>
#include <ktar.h>
#include <ktemporaryfile.h>
#include <ktempdir.h>
#include <kurl.h>
#include <kzip.h>
#include "package.h"
#include "private/packages_p.h"
#include "theme.h"
#include "private/package_p.h"
namespace Plasma
{
class ContentStructure
{
public:
ContentStructure()
: directory(false),
required(false)
{
}
ContentStructure(const ContentStructure &other)
{
paths = other.paths;
name = other.name;
mimetypes = other.mimetypes;
directory = other.directory;
required = other.required;
}
QStringList paths;
QString name;
QStringList mimetypes;
bool directory : 1;
bool required : 1;
};
class PackageStructurePrivate
{
public:
PackageStructurePrivate(const QString &t)
: type(t),
packageRoot("plasma/plasmoids"),
servicePrefix("plasma-applet-"),
metadata(0),
externalPaths(false)
{
contentsPrefixPaths << "contents/";
}
~PackageStructurePrivate()
{
delete metadata;
}
void createPackageMetadata(const QString &path);
QStringList entryList(const QString &prefix, const QString &requestedPath);
QString type;
QString path;
QStringList contentsPrefixPaths;
QString packageRoot;
QString servicePrefix;
QMap<QByteArray, ContentStructure> contents;
QStringList mimetypes;
PackageMetadata *metadata;
bool externalPaths;
};
PackageStructure::PackageStructure(QObject *parent, const QString &type)
PackageStructure::PackageStructure(QObject *parent, const QVariantList &args)
: QObject(parent),
d(new PackageStructurePrivate(type))
d(0)
{
Q_UNUSED(args)
}
PackageStructure::~PackageStructure()
{
delete d;
}
PackageStructure::Ptr PackageStructure::load(const QString &packageFormat)
void PackageStructure::initPackage(Package *package)
{
if (packageFormat.isEmpty()) {
return Ptr(new PackageStructure());
}
PackageStructure::Ptr structure;
if (packageFormat == "Plasma/Applet") {
structure = defaultPackageStructure(AppletComponent);
structure->d->type = "Plasma/Applet";
} else if (packageFormat == "Plasma/DataEngine") {
structure = defaultPackageStructure(DataEngineComponent);
structure->d->type = "Plasma/DataEngine";
} else if (packageFormat == "Plasma/Runner") {
structure = defaultPackageStructure(RunnerComponent);
structure->d->type = "Plasma/Runner";
} else if (packageFormat == "Plasma/Wallpaper") {
structure = defaultPackageStructure(WallpaperComponent);
structure->d->type = "Plasma/Wallpaper";
} else if (packageFormat == "Plasma/Theme") {
structure = Theme::packageStructure();
structure->d->type = "Plasma/Theme";
} else if (packageFormat == "Plasma/Generic") {
structure = defaultPackageStructure(GenericComponent);
structure->d->type = "Plasma/Generic";
structure->setDefaultPackageRoot(KStandardDirs::locate("data", "plasma/packages/"));
}
if (structure) {
return structure;
}
// first we check for plugins in sycoca
QString constraint = QString("[X-KDE-PluginInfo-Name] == '%1'").arg(packageFormat);
KService::List offers =
KServiceTypeTrader::self()->query("Plasma/PackageStructure", constraint);
QVariantList args;
QString error;
foreach (const KService::Ptr &offer, offers) {
PackageStructure::Ptr structure(
offer->createInstance<Plasma::PackageStructure>(0, args, &error));
if (structure) {
return structure;
}
kDebug() << "Couldn't load PackageStructure for" << packageFormat
<< "! reason given: " << error;
}
// if that didn't give us any love, then we try to load from a config file
structure = new PackageStructure();
QString configPath("plasma/packageformats/%1rc");
configPath = KStandardDirs::locate("data", configPath.arg(packageFormat));
if (!configPath.isEmpty()) {
KConfig config(configPath);
structure->read(&config);
return structure;
}
// try to load from absolute file path
KUrl url(packageFormat);
if (url.isLocalFile()) {
KConfig config(url.toLocalFile(), KConfig::SimpleConfig);
structure->read(&config);
}
#ifndef PLASMA_NO_KIO
else {
KTemporaryFile tmp;
if (tmp.open()) {
KIO::Job *job = KIO::file_copy(url, KUrl(tmp.fileName()),
-1, KIO::Overwrite | KIO::HideProgressInfo);
if (job->exec()) {
KConfig config(tmp.fileName(), KConfig::SimpleConfig);
structure->read(&config);
}
}
}
#endif
return structure;
Q_UNUSED(package)
}
PackageStructure &PackageStructure::operator=(const PackageStructure &rhs)
void PackageStructure::pathChanged(Package *package)
{
if (this == &rhs) {
return *this;
}
*d = *rhs.d;
return *this;
Q_UNUSED(package)
}
QString PackageStructure::type() const
bool PackageStructure::installPackage(Package *package, const QString &archivePath, const QString &packageRoot)
{
return d->type;
return PackagePrivate::installPackage(archivePath, packageRoot, package->servicePrefix());
}
QList<const char*> PackageStructure::directories() const
bool PackageStructure::uninstallPackage(Package *package, const QString &packageName, const QString &packageRoot)
{
QList<const char*> dirs;
QMap<QByteArray, ContentStructure>::const_iterator it = d->contents.constBegin();
while (it != d->contents.constEnd()) {
if (it.value().directory) {
dirs << it.key();
}
++it;
}
return dirs;
return PackagePrivate::uninstallPackage(packageName, packageRoot, package->servicePrefix());
}
QList<const char*> PackageStructure::requiredDirectories() const
{
QList<const char*> dirs;
QMap<QByteArray, ContentStructure>::const_iterator it = d->contents.constBegin();
while (it != d->contents.constEnd()) {
if (it.value().directory &&
it.value().required) {
dirs << it.key();
}
++it;
}
return dirs;
}
QList<const char*> PackageStructure::files() const
{
QList<const char*> files;
QMap<QByteArray, ContentStructure>::const_iterator it = d->contents.constBegin();
while (it != d->contents.constEnd()) {
if (!it.value().directory) {
files << it.key();
}
++it;
}
return files;
}
QList<const char*> PackageStructure::requiredFiles() const
{
QList<const char*> files;
QMap<QByteArray, ContentStructure>::const_iterator it = d->contents.constBegin();
while (it != d->contents.constEnd()) {
if (!it.value().directory && it.value().required) {
files << it.key();
}
++it;
}
return files;
}
QStringList PackageStructure::entryList(const char *key)
{
QString p = path(key);
if (p.isEmpty()) {
return QStringList();
}
QStringList list;
if (d->contentsPrefixPaths.isEmpty()) {
// no prefixes is the same as d->contentsPrefixPths with QStringList() << QString()
list << d->entryList(QString(), p);
} else {
foreach (QString prefix, d->contentsPrefixPaths) {
list << d->entryList(prefix, p);
}
}
return list;
}
QStringList PackageStructurePrivate::entryList(const QString &prefix, const QString &requestedPath)
{
QDir dir(path + prefix + requestedPath);
if (externalPaths) {
return dir.entryList(QDir::Files | QDir::Readable);
}
// ensure that we don't return files outside of our base path
// due to symlink or ../ games
QString canonicalized = dir.canonicalPath();
if (canonicalized.startsWith(path)) {
return dir.entryList(QDir::Files | QDir::Readable);
}
return QStringList();
}
void PackageStructure::addDirectoryDefinition(const char *key,
const QString &path, const QString &name)
{
ContentStructure s;
if (d->contents.contains(key)) {
s = d->contents[key];
}
if (!name.isEmpty()) {
s.name = name;
}
s.paths.append(path);
s.directory = true;
d->contents[key] = s;
}
void PackageStructure::addFileDefinition(const char *key, const QString &path, const QString &name)
{
ContentStructure s;
if (d->contents.contains(key)) {
s = d->contents[key];
}
if (!name.isEmpty()) {
s.name = name;
}
s.paths.append(path);
s.directory = false;
d->contents[key] = s;
}
void PackageStructure::removeDefinition(const char *key)
{
d->contents.remove(key);
}
QString PackageStructure::path(const char *key) const
{
//kDebug() << "looking for" << key;
QMap<QByteArray, ContentStructure>::const_iterator it = d->contents.constFind(key);
if (it == d->contents.constEnd()) {
return QString();
}
//kDebug() << "found" << key << "and the value is" << it.value().paths.first();
return it.value().paths.first();
}
QStringList PackageStructure::searchPath(const char *key) const
{
//kDebug() << "looking for" << key;
QMap<QByteArray, ContentStructure>::const_iterator it = d->contents.constFind(key);
if (it == d->contents.constEnd()) {
return QStringList();
}
//kDebug() << "found" << key << "and the value is" << it.value().paths;
return it.value().paths;
}
QString PackageStructure::name(const char *key) const
{
QMap<QByteArray, ContentStructure>::const_iterator it = d->contents.constFind(key);
if (it == d->contents.constEnd()) {
return QString();
}
return it.value().name;
}
void PackageStructure::setRequired(const char *key, bool required)
{
QMap<QByteArray, ContentStructure>::iterator it = d->contents.find(key);
if (it == d->contents.end()) {
return;
}
it.value().required = required;
}
bool PackageStructure::isRequired(const char *key) const
{
QMap<QByteArray, ContentStructure>::const_iterator it = d->contents.constFind(key);
if (it == d->contents.constEnd()) {
return false;
}
return it.value().required;
}
void PackageStructure::setDefaultMimetypes(QStringList mimetypes)
{
d->mimetypes = mimetypes;
}
void PackageStructure::setMimetypes(const char *key, QStringList mimetypes)
{
QMap<QByteArray, ContentStructure>::iterator it = d->contents.find(key);
if (it == d->contents.end()) {
return;
}
it.value().mimetypes = mimetypes;
}
QStringList PackageStructure::mimetypes(const char *key) const
{
QMap<QByteArray, ContentStructure>::const_iterator it = d->contents.constFind(key);
if (it == d->contents.constEnd()) {
return QStringList();
}
if (it.value().mimetypes.isEmpty()) {
return d->mimetypes;
}
return it.value().mimetypes;
}
void PackageStructure::setPath(const QString &path)
{
KUrl url(path);
QDir dir(url.toLocalFile());
QString basePath = dir.canonicalPath();
bool valid = QFile::exists(basePath);
if (valid) {
QFileInfo info(basePath);
if (info.isDir() && !basePath.endsWith('/')) {
basePath.append('/');
}
//kDebug() << "basePath is" << basePath;
} else {
kDebug() << path << "invalid, basePath is" << basePath;
return;
}
if (d->path == basePath) {
return;
}
d->path = basePath;
delete d->metadata;
d->metadata = 0;
pathChanged();
}
QString PackageStructure::path() const
{
return d->path;
}
void PackageStructure::pathChanged()
{
// default impl does nothing, this is a hook for subclasses.
}
void PackageStructure::read(const KConfigBase *config)
{
d->contents.clear();
d->mimetypes.clear();
KConfigGroup general(config, QString());
d->type = general.readEntry("Type", QString());
d->contentsPrefixPaths = general.readEntry("ContentsPrefixPaths", d->contentsPrefixPaths);
d->packageRoot = general.readEntry("DefaultPackageRoot", d->packageRoot);
d->externalPaths = general.readEntry("AllowExternalPaths", d->externalPaths);
QStringList groups = config->groupList();
foreach (const QString &group, groups) {
KConfigGroup entry(config, group);
QByteArray key = group.toAscii();
QString path = entry.readEntry("Path", QString());
QString name = entry.readEntry("Name", QString());
QStringList mimetypes = entry.readEntry("Mimetypes", QStringList());
bool directory = entry.readEntry("Directory", false);
bool required = entry.readEntry("Required", false);
if (directory) {
addDirectoryDefinition(key, path, name);
} else {
addFileDefinition(key, path, name);
}
setMimetypes(key, mimetypes);
setRequired(key, required);
}
}
void PackageStructure::write(KConfigBase *config) const
{
KConfigGroup general = KConfigGroup(config, "");
general.writeEntry("Type", type());
general.writeEntry("ContentsPrefixPaths", d->contentsPrefixPaths);
general.writeEntry("DefaultPackageRoot", d->packageRoot);
general.writeEntry("AllowExternalPaths", d->externalPaths);
QMap<QByteArray, ContentStructure>::const_iterator it = d->contents.constBegin();
while (it != d->contents.constEnd()) {
KConfigGroup group = config->group(it.key());
group.writeEntry("Path", it.value().paths);
group.writeEntry("Name", it.value().name);
if (!it.value().mimetypes.isEmpty()) {
group.writeEntry("Mimetypes", it.value().mimetypes);
}
if (it.value().directory) {
group.writeEntry("Directory", true);
}
if (it.value().required) {
group.writeEntry("Required", true);
}
++it;
}
}
QString PackageStructure::contentsPrefix() const
{
return d->contentsPrefixPaths.isEmpty() ? QString() : d->contentsPrefixPaths.first();
}
void PackageStructure::setContentsPrefix(const QString &prefix)
{
d->contentsPrefixPaths.clear();
d->contentsPrefixPaths << prefix;
}
QStringList PackageStructure::contentsPrefixPaths() const
{
return d->contentsPrefixPaths;
}
void PackageStructure::setContentsPrefixPaths(const QStringList &prefixPaths)
{
d->contentsPrefixPaths = prefixPaths;
}
bool PackageStructure::installPackage(const QString &package, const QString &packageRoot)
{
return Package::installPackage(package, packageRoot, d->servicePrefix);
}
bool PackageStructure::uninstallPackage(const QString &packageName, const QString &packageRoot)
{
return Package::uninstallPackage(packageName, packageRoot, d->servicePrefix);
}
void PackageStructure::createNewWidgetBrowser(QWidget *parent)
{
Q_UNUSED(parent)
emit newWidgetBrowserFinished();
}
QString PackageStructure::defaultPackageRoot() const
{
return d->packageRoot;
}
QString PackageStructure::servicePrefix() const
{
return d->servicePrefix;
}
void PackageStructure::setDefaultPackageRoot(const QString &packageRoot)
{
d->packageRoot = packageRoot;
}
void PackageStructure::setServicePrefix(const QString &servicePrefix)
{
d->servicePrefix = servicePrefix;
}
void PackageStructurePrivate::createPackageMetadata(const QString &path)
{
delete metadata;
metadata = 0;
QString metadataPath(path + "/metadata.desktop");
if (!QFile::exists(metadataPath)) {
kWarning() << "No metadata file in the package, expected it at:" << metadataPath;
metadataPath.clear();
}
metadata = new PackageMetadata(metadataPath);
}
//FIXME KDE5: should be const
PackageMetadata PackageStructure::metadata()
{
if (!d->metadata && !d->path.isEmpty()) {
QFileInfo fileInfo(d->path);
if (fileInfo.isDir()) {
d->createPackageMetadata(d->path);
} else if (fileInfo.exists()) {
KArchive *archive = 0;
KMimeType::Ptr mimetype = KMimeType::findByPath(d->path);
if (mimetype->is("application/zip")) {
archive = new KZip(d->path);
} else if (mimetype->is("application/x-compressed-tar") ||
mimetype->is("application/x-tar")|| mimetype->is("application/x-bzip-compressed-tar")) {
archive = new KTar(d->path);
} else {
kWarning() << "Could not open package file, unsupported archive format:" << d->path << mimetype->name();
}
if (archive && archive->open(QIODevice::ReadOnly)) {
const KArchiveDirectory *source = archive->directory();
KTempDir tempdir;
source->copyTo(tempdir.name());
d->createPackageMetadata(tempdir.name());
} else {
kWarning() << "Could not open package file:" << d->path;
}
delete archive;
}
}
if (!d->metadata) {
d->metadata = new PackageMetadata();
}
return *d->metadata;
}
bool PackageStructure::allowExternalPaths() const
{
return d->externalPaths;
}
void PackageStructure::setAllowExternalPaths(bool allow)
{
d->externalPaths = allow;
}
} // Plasma namespace
#include "packagestructure.moc"

View File

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright 2007 by Aaron Seigo <aseigo@kde.org> *
* Copyright 2011 by Aaron Seigo <aseigo@kde.org> *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
@ -21,368 +21,83 @@
#define PLASMA_PACKAGESTRUCTURE_H
#include <QtCore/QStringList>
#include <QtCore/QSharedData>
#include <kgenericfactory.h>
#include <klocale.h>
#include <ksharedptr.h>
#include <kplugininfo.h>
#include <plasma/version.h>
#include "packagemetadata.h"
class KConfigBase;
#include <plasma/plasma.h>
#include <plasma/plasma_export.h>
#include <plasma/package.h>
namespace Plasma
{
class PackageStructurePrivate;
/**
* @class PackageStructure plasma/packagestructure.h <Plasma/PackageStructure>
*
* @short A description of the expected file structure of a given package type
*
* PackageStructure defines what is in a package. This information is used
* to create packages and provides a way to programatically refer to contents.
*
* An example usage of this class might be:
*
@code
PackageStructure structure;
structure.addDirectoryDefinition("images", "pics/", i18n("Images"));
QStringList mimetypes;
mimetypes << "image/svg" << "image/png" << "image/jpeg";
structure.setMimetypes("images", mimetypes);
structure.addDirectoryDefinition("scripts", "code/", i18n("Executable Scripts"));
mimetypes.clear();
mimetypes << "text/\*";
structure.setMimetypes("scripts", mimetypes);
structure.addFileDefinition("mainscript", "code/main.js", i18n("Main Script File"));
structure.setRequired("mainscript", true);
@endcode
* One may also choose to create a subclass of PackageStructure and include the setup
* in the constructor.
*
* Either way, PackageStructure creates a sort of "contract" between the packager and
* the application which is also self-documenting.
**/
class PLASMA_EXPORT PackageStructure : public QObject, public QSharedData
class PLASMA_EXPORT PackageStructure : public QObject
{
Q_OBJECT
public:
typedef KSharedPtr<PackageStructure> Ptr;
explicit PackageStructure(QObject *parent = 0, const QVariantList &args = QVariantList());
~PackageStructure();
/**
* Default constructor for a package structure definition
* Called when a the PackageStructure should initialize a Package with the initial
* structure. This allows setting paths before setPath is called.
*
* @param type the type of package. This is often application specific.
**/
explicit PackageStructure(QObject *parent = 0,
const QString &type = i18nc("A non-functional package", "Invalid"));
/**
* Destructor
**/
virtual ~PackageStructure();
/**
* Assignment operator
**/
PackageStructure &operator=(const PackageStructure &rhs);
/**
* Loads a package format by name.
* Note: one special value is "metadata" which can be set to the location of KPluginInfo
* compatible .desktop file within the package. If not defined, it is assumed that this file
* exists under the top level directory of the package.
*
* @param format If not empty, attempts to locate the given format, either
* from built-ins or via plugins.
* @return a package that matches the format, if available. The caller
* is responsible for deleting the object.
* @arg package the Package to set up. The object is empty of all definition when
* first passed in.
*/
static PackageStructure::Ptr load(const QString &packageFormat);
/**
* Type of package this structure describes
**/
QString type() const;
/**
* The directories defined for this package
**/
QList<const char*> directories() const;
/**
* The required directories defined for this package
**/
QList<const char*> requiredDirectories() const;
/**
* The individual files, by key, that are defined for this package
**/
QList<const char*> files() const;
/**
* The individual required files, by key, that are defined for this package
**/
QList<const char*> requiredFiles() const;
/**
* Adds a directory to the structure of the package. It is added as
* a not-required element with no associated mimetypes.
*
* Starting in 4.6, if an entry with the given key
* already exists, the path is added to it as a search alternative.
*
* @param key used as an internal label for this directory
* @param path the path within the package for this directory
* @param name the user visible (translated) name for the directory
**/
void addDirectoryDefinition(const char *key, const QString &path, const QString &name);
/**
* Adds a file to the structure of the package. It is added as
* a not-required element with no associated mimetypes.
*
* Starting in 4.6, if an entry with the given key
* already exists, the path is added to it as a search alternative.
*
* @param key used as an internal label for this file
* @param path the path within the package for this file
* @param name the user visible (translated) name for the file
**/
void addFileDefinition(const char *key, const QString &path, const QString &name);
/**
* Removes a definition from the structure of the package.
* @since 4.6
* @param key the internal label of the file or directory to remove
*/
void removeDefinition(const char *key);
/**
* @return path relative to the package root for the given entry
* @deprecatd use searchPaths instead
**/
QString path(const char *key) const;
/**
* @return a list of paths relative to the package root for the given entry.
* They are orted by importance: when searching for a file the paths
* will be searched in order
* @since 4.6
**/
QStringList searchPath(const char *key) const;
/**
* Get the list of files of a given type.
*
* @param key the type of file to look for
* @return list of files by name
* @since 4.3
*/
QStringList entryList(const char *key);
/**
* @return user visible name for the given entry
**/
QString name(const char *key) const;
/**
* Sets whether or not a given part of the structure is required or not.
* The path must already have been added using addDirectoryDefinition
* or addFileDefinition.
*
* @param key the entry within the package
* @param required true if this entry is required, false if not
*/
void setRequired(const char *key, bool required);
/**
* @return true if the item at path exists and is required
**/
bool isRequired(const char *key) const;
/**
* Defines the default mimetypes for any definitions that do not have
* associated mimetypes. Handy for packages with only one or predominantly
* one file type.
*
* @param mimetypes a list of mimetypes
**/
void setDefaultMimetypes(QStringList mimetypes);
/**
* Define mimetypes for a given part of the structure
* The path must already have been added using addDirectoryDefinition
* or addFileDefinition.
*
* @param key the entry within the package
* @param mimetypes a list of mimetypes
**/
void setMimetypes(const char *key, QStringList mimetypes);
/**
* @return the mimetypes associated with the path, if any
**/
QStringList mimetypes(const char *key) const;
/**
* Sets the path to the package. Useful for package formats
* which do not have well defined contents prior to installation.
*/
void setPath(const QString &path);
/**
* @return the path to the package, or QString() if none
*/
QString path() const;
/**
* Read a package structure from a config file.
*/
void read(const KConfigBase *config);
/**
* Write this package structure to a config file.
*/
void write(KConfigBase *config) const;
/**
* Installs a package matching this package structure. By default installs a
* native Plasma::Package.
*
* @param archivePath path to the package archive file
* @param packageRoot path to the directory where the package should be
* installed to
* @return true on successful installation, false otherwise
**/
virtual bool installPackage(const QString &archivePath, const QString &packageRoot);
/**
* Uninstalls a package matching this package structure.
*
* @param packageName the name of the package to remove
* @param packageRoot path to the directory where the package should be installed to
* @return true on successful removal of the package, false otherwise
*/
virtual bool uninstallPackage(const QString &packageName, const QString &packageRoot);
/**
* When called, the package plugin should display a window to the user
* that they can use to browser, select and then install widgets supported by
* this package plugin with.
*
* The user interface may be an in-process dialog or an out-of-process application.
*
* When the process is complete, the newWidgetBrowserFinished() signal must be
* emitted.
*
* @param parent the parent widget to use for the widget
*/
virtual void createNewWidgetBrowser(QWidget *parent = 0);
/**
* @return the prefix inserted between the base path and content entries
* @deprecated use contentsPrefixPaths() instead.
*/
KDE_DEPRECATED QString contentsPrefix() const;
/**
* @return the prefix paths inserted between the base path and content entries, in order of priority.
* When searching for a file, all paths will be tried in order.
* @since 4.6
*/
QStringList contentsPrefixPaths() const;
/**
* @return preferred package root. This defaults to plasma/plasmoids/
*/
QString defaultPackageRoot() const;
/**
* @return service prefix used in desktop files. This defaults to plasma-applet-
*/
QString servicePrefix() const;
/**
* Sets service prefix.
*/
void setServicePrefix(const QString &servicePrefix);
/**
* @return the package metadata object.
*/
virtual PackageMetadata metadata();
/**
* @return true if paths/symlinks outside the package itself should be followed.
* By default this is set to false for security reasons.
*/
bool allowExternalPaths() const;
Q_SIGNALS:
/**
* Emitted when the new widget browser process completes.
*/
void newWidgetBrowserFinished();
protected:
/**
* Sets whether or not external paths/symlinks can be followed by a package
* @param allow true if paths/symlinks outside of the package should be followed,
* false if they should be rejected.
*/
void setAllowExternalPaths(bool allow);
/**
* Sets the prefix that all the contents in this package should
* appear under. This defaults to "contents/" and is added automatically
* between the base path and the entries as defined by the package
* structure
*
* @param prefix the directory prefix to use
* @deprecated use setContentsPrefixPaths() instead.
*/
KDE_DEPRECATED void setContentsPrefix(const QString &prefix);
/**
* Sets the prefixes that all the contents in this package should
* appear under. This defaults to "contents/" and is added automatically
* between the base path and the entries as defined by the package
* structure. Multiple entries can be added.
* In this case each file request will be searched in all prefixes in order,
* and the first found will be returned.
*
* @param prefix paths the directory prefix to use
* @since 4.6
*/
void setContentsPrefixPaths(const QStringList &prefixPaths);
/**
* Sets preferred package root.
*/
void setDefaultPackageRoot(const QString &packageRoot);
virtual void initPackage(Package *package);
/**
* Called whenever the path changes so that subclasses may take
* package specific actions.
*/
virtual void pathChanged();
virtual void pathChanged(Package *package);
/**
* Installs a package matching this package structure. By default installs a
* native Plasma::Package.
*
* @param package the instance of Package that is being used for the install; useful for
* accessing file paths
* @param archivePath path to the package archive file
* @param packageRoot path to the directory where the package should be
* installed to
* @return true on successful installation, false otherwise
**/
virtual bool installPackage(Package *package, const QString &archivePath, const QString &packageRoot);
/**
* Uninstalls a package matching this package structure.
*
* @param package the instance of Package that is being used for the install; useful for
* accessing file paths
* @param packageName the name of the package to remove
* @param packageRoot path to the directory where the package should be installed to
* @return true on successful removal of the package, false otherwise
*/
virtual bool uninstallPackage(Package *package, const QString &packageName, const QString &packageRoot);
private:
PackageStructurePrivate * const d;
PackageStructurePrivate *const d;
};
} // Plasma namespace
/**
* Register an applet when it is contained in a loadable module
* Register a Package class when it is contained in a loadable module
*/
#define K_EXPORT_PLASMA_PACKAGESTRUCTURE(libname, classname) \
#define K_EXPORT_PLASMA_PACKAGE(libname, classname) \
K_PLUGIN_FACTORY(factory, registerPlugin<classname>();) \
K_EXPORT_PLUGIN(factory("plasma_packagestructure_" #libname)) \
K_EXPORT_PLUGIN_VERSION(PLASMA_VERSION)
} // Plasma namespace
#endif

View File

@ -24,30 +24,13 @@
#include <QGraphicsView>
#include <QMenu>
#include <plasma/containment.h>
#include <plasma/view.h>
#include "containment.h"
#include "view.h"
#include "private/packages_p.h"
namespace Plasma
{
qreal scalingFactor(ZoomLevel level)
{
switch (level) {
case DesktopZoom:
return 1;
break;
case GroupZoom:
return 0.5;
break;
case OverviewZoom:
return 0.2;
break;
}
// to make odd compilers not warn like silly beasts
return 1;
}
Direction locationToDirection(Location location)
{
switch (location) {
@ -109,37 +92,4 @@ QGraphicsView *viewFor(const QGraphicsItem *item)
return found;
}
QList<QAction*> actionsFromMenu(QMenu *menu, const QString &prefix, QObject *parent)
{
Q_ASSERT(menu);
QList<QAction*> ret;
foreach (QAction *action, menu->actions()) {
if (QMenu *submenu = action->menu()) {
//Flatten hierarchy and prefix submenu text to all actions in submenu
ret << actionsFromMenu(submenu, action->text(), parent);
} else if (!action->isSeparator() && action->isEnabled()) {
QString text = action->text();
if (action->isCheckable()) {
if (action->isChecked()) {
text = QString("(%1) %2").arg(QChar(0x2613)).arg(text);
} else {
text = QString("( ) %1").arg(text);
}
}
if (!prefix.isEmpty()) {
text = QString("%1: %2").arg(prefix).arg(text);
}
text = text.replace(QRegExp("&([\\S])"), "\\1");
QAction *a = new QAction(action->icon(), text, parent);
QObject::connect(a, SIGNAL(triggered(bool)), action, SIGNAL(triggered(bool)));
ret << a;
}
}
return ret;
}
} // Plasma namespace

View File

@ -55,12 +55,10 @@ enum Constraint {
ImmutableConstraint = 16,
/** application startup has completed */
StartupCompletedConstraint = 32,
/** the desktop context has changed */
ContextConstraint = 64,
/** the position of the popup needs to be recalculated*/
PopupConstraint = 128,
AllConstraints = FormFactorConstraint | LocationConstraint | ScreenConstraint |
SizeConstraint | ImmutableConstraint | ContextConstraint | PopupConstraint
SizeConstraint | ImmutableConstraint | PopupConstraint
};
Q_DECLARE_FLAGS(Constraints, Constraint)
@ -99,14 +97,6 @@ enum Direction {
Right /**< Display to the right */
};
/**
* The direction of a zoom action.
*/
enum ZoomDirection {
ZoomIn = 0, /**< Zoom in one step */
ZoomOut = 1 /**< Zoom out one step */
};
/**
* The Location enumeration describes where on screen an element, such as an
* Applet or its managing container, is positioned on the screen.
@ -170,17 +160,6 @@ enum FlipDirection {
};
Q_DECLARE_FLAGS(Flip, FlipDirection)
/**
* Zoom levels that Plasma is aware of...
**/
enum ZoomLevel {
DesktopZoom = 0, /**< Normal desktop usage, plasmoids are painted normally
and have full interaction */
GroupZoom, /**< Plasmoids are shown as icons in visual groups; drag
and drop and limited context menu interaction only */
OverviewZoom /**< Groups become icons themselves */
};
/**
* Possible timing alignments
**/
@ -209,7 +188,7 @@ enum ImmutabilityType {
};
/**
* Defines the aspect ratio used when scaling an applet
* Defines the aspect ratio used when resizing an applet
*/
enum AspectRatioMode {
InvalidAspectRatioMode = -1, /**< Unset mode used for dev convenience
@ -234,8 +213,7 @@ enum ComponentType {
RunnerComponent = 4, /**< Plasma::AbstractRunner based plugsin **/
AnimatorComponent = 8, /**< Plasma::Animator based plugins **/
ContainmentComponent = 16,/**< Plasma::Containment based plugins **/
WallpaperComponent = 32, /**< Plasma::Wallpaper based plugins **/
GenericComponent = 64 /** Generic repositories of files, usually they keep QML files and their assets **/
WallpaperComponent = 32 /**< Plasma::Wallpaper based plugins **/
};
Q_DECLARE_FLAGS(ComponentTypes, ComponentType)
@ -275,18 +253,28 @@ enum AnnouncementMethod {
Q_DECLARE_FLAGS(AnnouncementMethods, AnnouncementMethod)
enum TrustLevel {
InvalidCredentials = 0, /**< The credentials are invalid **/
UnknownCredentials = 1, /**< The credentials are unknown **/
ValidCredentials = 2, /**< The credentials are valid **/
TrustedCredentials = 3, /**< The credentials are trusted **/
UltimateCredentials = 4 /**< The ultimate trust level applies to the credentials **/
UnverifiableTrust = 0, /**< The trust of the object can not be verified, usually because no
trust information (e.g. a cryptographic signature) was provided */
CompletelyUntrusted, /**< The signature is broken/expired/false */
UnknownTrusted, /**< The signature is valid, but the key is unknown */
UserTrusted, /**< The signature is valid and made with a key signed by one of the
user's own keys*/
SelfTrusted, /**< The signature is valid and made with one of the user's own keys*/
FullyTrusted, /**< The signature is valid and made with a key signed by the vendor's key*/
UltimatelyTrusted /**< The signature is valid and made with the vendor's key*/
};
Q_ENUMS(TrustLevel)
/**
* @return the scaling factor (0..1) for a ZoomLevel
**/
PLASMA_EXPORT qreal scalingFactor(ZoomLevel level);
* Description on how draw a background for the applet
*/
enum BackgroundHints {
NoBackground = 0, /**< Not drawing a background under the applet, the applet has its own implementation */
StandardBackground = 1, /**< The standard background from the theme is drawn */
TranslucentBackground = 2, /**< An alternate version of the background is drawn, usually more translucent */
DefaultBackground = StandardBackground /**< Default settings: both standard background */
};
Q_ENUMS(BackgroundHints)
/**
* Converts a location to a direction. Handy for figuring out which way to send a popup based on
@ -314,21 +302,6 @@ PLASMA_EXPORT Direction locationToInverseDirection(Location location);
*/
PLASMA_EXPORT QGraphicsView *viewFor(const QGraphicsItem *item);
/**
* Returns a list of all actions in the given QMenu
* This method flattens the hierarchy of the menu by prefixing the
* text of all actions in a submenu with the submenu title.
*
* @param menu the QMenu storing the actions
* @param prefix text to display before the text of all actions in the menu
* @param parent QObject to be passed as parent of all the actions in the list
*
* @since 4.4
*/
PLASMA_EXPORT QList<QAction*> actionsFromMenu(QMenu *menu,
const QString &prefix = QString(),
QObject *parent = 0);
} // Plasma namespace
Q_DECLARE_OPERATORS_FOR_FLAGS(Plasma::Constraints)
@ -336,5 +309,4 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(Plasma::Flip)
Q_DECLARE_OPERATORS_FOR_FLAGS(Plasma::ComponentTypes)
Q_DECLARE_OPERATORS_FOR_FLAGS(Plasma::MessageButtons)
#endif // multiple inclusion guard

View File

@ -24,34 +24,48 @@
#include <kservice.h>
#include <kservicetypetrader.h>
#include <kstandarddirs.h>
#include <ktemporaryfile.h>
#include <kplugininfo.h>
#ifndef PLASMA_NO_KIO
#include <kio/job.h>
#endif
#include "applet.h"
#include "abstractrunner.h"
#include "containment.h"
#include "packagestructure.h"
#include "containmentactions.h"
#include "package.h"
#include "popupapplet.h"
#include "private/applet_p.h"
#include "private/extenderapplet_p.h"
#include "private/packages_p.h"
#include "private/service_p.h" // for NullService
#include "private/storage_p.h"
namespace Plasma {
static PluginLoader* s_pluginLoader = 0;
static PluginLoader *s_pluginLoader = 0;
class PluginLoaderPrivate
{
public:
QHash<QString, QWeakPointer<PackageStructure> > structures;
bool isDefaultLoader;
};
PluginLoader::PluginLoader()
: d(0)
: d(new PluginLoaderPrivate)
{
d->isDefaultLoader = false;
}
PluginLoader::~PluginLoader()
{
typedef QWeakPointer<PackageStructure> pswp;
foreach (pswp wp, d->structures) {
delete wp.data();
}
delete d;
}
@ -60,17 +74,20 @@ void PluginLoader::setPluginLoader(PluginLoader* loader)
if (!s_pluginLoader) {
s_pluginLoader = loader;
} else {
#ifndef NDEBUG
kDebug() << "Cannot set pluginLoader, already set!" << s_pluginLoader;
#endif
}
}
PluginLoader *PluginLoader::pluginLoader()
PluginLoader *PluginLoader::self()
{
if (!s_pluginLoader) {
// we have been called before any PluginLoader was set, so just use the default
// implementation. this prevents plugins from nefariously injecting their own
// plugin loader if the app doesn't
s_pluginLoader = new PluginLoader;
s_pluginLoader->d->isDefaultLoader = true;
}
return s_pluginLoader;
@ -83,7 +100,7 @@ Applet *PluginLoader::loadApplet(const QString &name, uint appletId, const QVari
return 0;
}
Applet *applet = internalLoadApplet(name, appletId, args);
Applet *applet = d->isDefaultLoader ? 0 : internalLoadApplet(name, appletId, args);
if (applet) {
return applet;
}
@ -102,12 +119,16 @@ Applet *PluginLoader::loadApplet(const QString &name, uint appletId, const QVari
}
/* if (offers.count() > 1) {
#ifndef NDEBUG
kDebug() << "hey! we got more than one! let's blindly take the first one";
#endif
} */
AppletPrivate::filterOffers(offers);
if (offers.isEmpty()) {
#ifndef NDEBUG
kDebug() << "offers is empty for " << name;
#endif
return 0;
}
@ -121,8 +142,10 @@ Applet *PluginLoader::loadApplet(const QString &name, uint appletId, const QVari
allArgs << offer->storageId() << appletId << args;
if (!offer->property("X-Plasma-API").toString().isEmpty()) {
#ifndef NDEBUG
kDebug() << "we have a script using the"
<< offer->property("X-Plasma-API").toString() << "API";
#endif
if (isContainment) {
return new Containment(0, allArgs);
} else {
@ -152,7 +175,9 @@ Applet *PluginLoader::loadApplet(const QString &name, uint appletId, const QVari
}
if (!applet) {
#ifndef NDEBUG
kDebug() << "Couldn't load applet \"" << name << "\"! reason given: " << error;
#endif
}
return applet;
@ -160,7 +185,7 @@ Applet *PluginLoader::loadApplet(const QString &name, uint appletId, const QVari
DataEngine *PluginLoader::loadDataEngine(const QString &name)
{
DataEngine *engine = internalLoadDataEngine(name);
DataEngine *engine = d->isDefaultLoader ? 0 : internalLoadDataEngine(name);
if (engine) {
return engine;
}
@ -172,7 +197,9 @@ DataEngine *PluginLoader::loadDataEngine(const QString &name)
QString error;
if (offers.isEmpty()) {
#ifndef NDEBUG
kDebug() << "offers are empty for " << name << " with constraint " << constraint;
#endif
} else {
QVariantList allArgs;
allArgs << offers.first()->storageId();
@ -190,7 +217,9 @@ DataEngine *PluginLoader::loadDataEngine(const QString &name)
}
if (!engine) {
#ifndef NDEBUG
kDebug() << "Couldn't load engine \"" << name << "\". Error given: " << error;
#endif
}
return engine;
@ -200,12 +229,12 @@ AbstractRunner *PluginLoader::loadRunner(const QString &name)
{
// FIXME: RunnerManager is all wrapped around runner loading; that should be sorted out
// and the actual plugin loading added here
return internalLoadRunner(name);
return d->isDefaultLoader ? 0 : internalLoadRunner(name);
}
Service *PluginLoader::loadService(const QString &name, const QVariantList &args, QObject *parent)
{
Service *service = internalLoadService(name, args, parent);
Service *service = d->isDefaultLoader ? 0 : internalLoadService(name, args, parent);
if (service) {
return service;
}
@ -221,7 +250,9 @@ Service *PluginLoader::loadService(const QString &name, const QVariantList &args
KService::List offers = KServiceTypeTrader::self()->query("Plasma/Service", constraint);
if (offers.isEmpty()) {
#ifndef NDEBUG
kDebug() << "offers is empty for " << name;
#endif
return new NullService(name, parent);
}
@ -233,7 +264,9 @@ Service *PluginLoader::loadService(const QString &name, const QVariantList &args
}
if (!service) {
#ifndef NDEBUG
kDebug() << "Couldn't load Service \"" << name << "\"! reason given: " << error;
#endif
return new NullService(name, parent);
}
@ -244,11 +277,136 @@ Service *PluginLoader::loadService(const QString &name, const QVariantList &args
return service;
}
ContainmentActions *PluginLoader::loadContainmentActions(Containment *parent, const QString &name, const QVariantList &args)
{
if (name.isEmpty()) {
return 0;
}
ContainmentActions *actions = d->isDefaultLoader ? 0 : internalLoadContainmentActions(parent, name, args);
if (actions) {
return actions;
}
QString constraint = QString("[X-KDE-PluginInfo-Name] == '%1'").arg(name);
KService::List offers = KServiceTypeTrader::self()->query("Plasma/ContainmentActions", constraint);
if (offers.isEmpty()) {
#ifndef NDEBUG
kDebug() << "offers is empty for " << name;
#endif
return 0;
}
KService::Ptr offer = offers.first();
KPluginLoader plugin(*offer);
if (!Plasma::isPluginVersionCompatible(plugin.pluginVersion())) {
return 0;
}
QVariantList allArgs;
allArgs << offer->storageId() << args;
QString error;
actions = offer->createInstance<Plasma::ContainmentActions>(parent, allArgs, &error);
if (!actions) {
#ifndef NDEBUG
kDebug() << "Couldn't load containmentActions \"" << name << "\"! reason given: " << error;
#endif
}
return actions;
}
Package PluginLoader::loadPackage(const QString &packageFormat, const QString &specialization)
{
if (!d->isDefaultLoader) {
Package p = internalLoadPackage(packageFormat, specialization);
if (p.isValid()) {
return p;
}
}
if (packageFormat.isEmpty()) {
return Package();
}
const QString hashkey = packageFormat + '%' + specialization;
PackageStructure *structure = d->structures.value(hashkey).data();
if (structure) {
return Package(structure);
}
if (!specialization.isEmpty()) {
QRegExp re("[^a-zA-Z0-9\\-_]");
// check that the provided strings are safe to use in a ServiceType query
if (re.indexIn(specialization) == -1 && re.indexIn(packageFormat) == -1) {
// FIXME: The query below is rather spepcific to script engines. generify if possible
const QString component = packageFormat.right(packageFormat.size() - packageFormat.lastIndexOf('/') - 1);
const QString constraint = QString("[X-Plasma-API] == '%1' and " "'%2' in [X-Plasma-ComponentTypes]").arg(specialization, component);
KService::List offers = KServiceTypeTrader::self()->query("Plasma/ScriptEngine", constraint);
if (!offers.isEmpty()) {
KService::Ptr offer = offers.first();
QString packageFormat = offer->property("X-Plasma-PackageFormat").toString();
if (!packageFormat.isEmpty()) {
return loadPackage(packageFormat);
}
}
}
}
if (packageFormat.startsWith("Plasma")) {
if (packageFormat.endsWith("/Applet")) {
structure = new PlasmoidPackage();
} else if (packageFormat.endsWith("/DataEngine")) {
structure = new DataEnginePackage();
} else if (packageFormat.endsWith("/Runner")) {
structure = new RunnerPackage();
} else if (packageFormat.endsWith("/Wallpaper")) {
structure = new WallpaperPackage();
} else if (packageFormat.endsWith("/Theme")) {
structure = new ThemePackage();
} else if (packageFormat.endsWith("/ContainmentActions")) {
structure = new ContainmentActionsPackage();
} else if (packageFormat.endsWith("/Generic")) {
structure = new GenericPackage();
}
if (structure) {
d->structures.insert(hashkey, structure);
return Package(structure);
}
}
// first we check for plugins in sycoca
QString constraint = QString("[X-KDE-PluginInfo-Name] == '%1'").arg(packageFormat);
KService::List offers = KServiceTypeTrader::self()->query("Plasma/PackageStructure", constraint);
QVariantList args;
QString error;
foreach (const KService::Ptr &offer, offers) {
structure = qobject_cast<PackageStructure *>(offer->createInstance<PackageStructure>(0, args, &error));
if (structure) {
d->structures.insert(hashkey, structure);
return Package(structure);
}
#ifndef NDEBUG
kDebug() << "Couldn't load Package for" << packageFormat << "! reason given: " << error;
#endif
}
return Package();
}
KPluginInfo::List PluginLoader::listAppletInfo(const QString &category, const QString &parentApp)
{
KPluginInfo::List list;
if (parentApp.isEmpty() || parentApp == KGlobal::mainComponent().componentName()) {
if (!d->isDefaultLoader && (parentApp.isEmpty() || parentApp == KGlobal::mainComponent().componentName())) {
list = internalAppletInfo(category);
}
@ -282,7 +440,7 @@ KPluginInfo::List PluginLoader::listDataEngineInfo(const QString &parentApp)
{
KPluginInfo::List list;
if (parentApp.isEmpty() || parentApp == KGlobal::mainComponent().componentName()) {
if (!d->isDefaultLoader && (parentApp.isEmpty() || parentApp == KGlobal::mainComponent().componentName())) {
list = internalDataEngineInfo();
}
@ -301,7 +459,7 @@ KPluginInfo::List PluginLoader::listRunnerInfo(const QString &parentApp)
{
KPluginInfo::List list;
if (parentApp.isEmpty() || parentApp == KGlobal::mainComponent().componentName()) {
if (!d->isDefaultLoader && (parentApp.isEmpty() || parentApp == KGlobal::mainComponent().componentName())) {
list = internalRunnerInfo();
}
@ -316,6 +474,25 @@ KPluginInfo::List PluginLoader::listRunnerInfo(const QString &parentApp)
return list + KPluginInfo::fromServices(offers);
}
KPluginInfo::List PluginLoader::listContainmentActionsInfo(const QString &parentApp)
{
KPluginInfo::List list;
if (!d->isDefaultLoader && (parentApp.isEmpty() || parentApp == KGlobal::mainComponent().componentName())) {
list = internalContainmentActionsInfo();
}
QString constraint;
if (parentApp.isEmpty()) {
constraint.append("not exist [X-KDE-ParentApp]");
} else {
constraint.append("[X-KDE-ParentApp] == '").append(parentApp).append("'");
}
KService::List offers = KServiceTypeTrader::self()->query("Plasma/ContainmentActions", constraint);
return KPluginInfo::fromServices(offers);
}
Applet* PluginLoader::internalLoadApplet(const QString &name, uint appletId, const QVariantList &args)
{
Q_UNUSED(name)
@ -324,19 +501,27 @@ Applet* PluginLoader::internalLoadApplet(const QString &name, uint appletId, con
return 0;
}
DataEngine* PluginLoader::internalLoadDataEngine(const QString &name)
DataEngine *PluginLoader::internalLoadDataEngine(const QString &name)
{
Q_UNUSED(name)
return 0;
}
AbstractRunner* PluginLoader::internalLoadRunner(const QString &name)
AbstractRunner *PluginLoader::internalLoadRunner(const QString &name)
{
Q_UNUSED(name)
return 0;
}
Service* PluginLoader::internalLoadService(const QString &name, const QVariantList &args, QObject *parent)
ContainmentActions *PluginLoader::internalLoadContainmentActions(Containment *containment, const QString &name, const QVariantList &args)
{
Q_UNUSED(containment)
Q_UNUSED(name)
Q_UNUSED(args)
return 0;
}
Service *PluginLoader::internalLoadService(const QString &name, const QVariantList &args, QObject *parent)
{
Q_UNUSED(name)
Q_UNUSED(args)
@ -344,6 +529,13 @@ Service* PluginLoader::internalLoadService(const QString &name, const QVariantLi
return 0;
}
Package PluginLoader::internalLoadPackage(const QString &name, const QString &specialization)
{
Q_UNUSED(name);
Q_UNUSED(specialization);
return Package();
}
KPluginInfo::List PluginLoader::internalAppletInfo(const QString &category) const
{
Q_UNUSED(category)
@ -365,6 +557,11 @@ KPluginInfo::List PluginLoader::internalServiceInfo() const
return KPluginInfo::List();
}
KPluginInfo::List PluginLoader::internalContainmentActionsInfo() const
{
return KPluginInfo::List();
}
static KPluginInfo::List standardInternalInfo(const QString &type, const QString &category = QString())
{
QStringList files = KGlobal::dirs()->findAllResources("appdata",

View File

@ -20,20 +20,23 @@
#ifndef PLUGIN_LOADER_H
#define PLUGIN_LOADER_H
#include <plasma/package.h>
#include <plasma/plasma.h>
#include <kplugininfo.h>
namespace Plasma {
class AbstractRunner;
class Applet;
class Containment;
class ContainmentActions;
class DataEngine;
class Service;
class AbstractRunner;
class PluginLoaderPrivate;
//TODO:
// * add support for ContainmentActions plugins
// * add loadWallpaper
// * add KPluginInfo listing support for Containments (already loaded via the applet loading code)
/**
@ -51,10 +54,6 @@ class PluginLoaderPrivate;
class PLASMA_EXPORT PluginLoader
{
public:
PluginLoader();
virtual ~PluginLoader();
/**
* Load an Applet plugin.
*
@ -93,6 +92,31 @@ public:
**/
Service *loadService(const QString &name, const QVariantList &args, QObject *parent = 0);
/**
* Load a ContainmentActions plugin.
*
* Returns a pointer to the containmentactions if successful.
* The caller takes responsibility for the containmentactions, including
* deleting it when no longer needed.
*
* @param parent the parent containment. @since 4.6 null is allowed.
* @param name the plugin name, as returned by KPluginInfo::pluginName()
* @param args to send the containmentactions extra arguments
* @return a ContaimentActions object
**/
ContainmentActions *loadContainmentActions(Containment *parent, const QString &containmentActionsName,
const QVariantList &args = QVariantList());
/**
* Load a Package plugin.
*
* @param name the plugin name of the package to load
* @param specialization used to find script extensions for the given format, e.g. "QML" for "Plasma/Applet"
*
* @return a Package object matching name, or an invalid package on failure
**/
Package loadPackage(const QString &packageFormat, const QString &specialization = QString());
/**
* Returns a list of all known applets.
* This may skip applets based on security settings and ExcludeCategories in the application's config.
@ -136,6 +160,18 @@ public:
**/
KPluginInfo::List listRunnerInfo(const QString &parentApp = QString());
/**
* Returns a list of all known ContainmentActions.
*
* @param parentApp the application to filter applets on. Uses the
* X-KDE-ParentApp entry (if any) in the plugin info.
* The default value of QString() will result in a
* list containing only applets not specifically
* registered to an application.
* @return list of applets
**/
KPluginInfo::List listContainmentActionsInfo(const QString &parentApp);
/**
* Set the plugin loader which will be queried for all loads.
*
@ -147,7 +183,7 @@ public:
/**
* Return the active plugin loader
**/
static PluginLoader* pluginLoader();
static PluginLoader *self();
protected:
/**
@ -205,6 +241,39 @@ protected:
**/
virtual Service *internalLoadService(const QString &name, const QVariantList &args, QObject *parent = 0);
/**
* A re-implementable method that allows subclasses to override
* the default behaviour of loadContainmentActions. If the Containments Action requested is not recognized,
* then the implementation should return a NULL pointer. This method is called
* by loadService prior to attempting to load a Service using the standard Plasma
* plugin mechanisms.
*
* Returns a pointer to the containmentactions if successful.
* The caller takes responsibility for the containmentactions, including
* deleting it when no longer needed.
*
* @param parent the parent containment. @since 4.6 null is allowed.
* @param name the plugin name, as returned by KPluginInfo::pluginName()
* @param args to send the containmentactions extra arguments
* @return a ContaimentActions object
**/
virtual ContainmentActions *internalLoadContainmentActions(Containment *parent, const QString &containmentActionsName, const QVariantList &args);
/**
* A re-implementable method that allows subclasses to override
* the default behaviour of loadPackage. If the service requested is not recognized,
* then the implementation should return a NULL pointer. This method is called
* by loadService prior to attempting to load a Service using the standard Plasma
* plugin mechanisms.
*
* @param name the plugin name of the service to load
* @param args a list of arguments to supply to the service plugin when loading it
* @param parent the parent object, if any, for the service
*
* @return a Service object, unlike Plasma::Service::loadService, this can return null.
**/
virtual Package internalLoadPackage(const QString &name, const QString &specialization);
/**
* A re-implementable method that allows subclasses to provide additional applets
* for listAppletInfo. If the application has no applets to give to the application,
@ -228,24 +297,31 @@ protected:
* A re-implementable method that allows subclasses to provide additional DataEngines
* for DataEngineManager::listDataEngines.
*
* @return list of DataEngines, or an empty list if none
* @return list of DataEngines info, or an empty list if none
**/
virtual KPluginInfo::List internalDataEngineInfo() const;
/**
* Returns a list of all known Runner implementations
*
* @return list of AbstractRunners, or an empty list if none
* @return list of AbstractRunners info, or an empty list if none
*/
virtual KPluginInfo::List internalRunnerInfo() const;
/**
* Returns a list of all known Runner implementations
*
* @return list of AbstractRunners, or an empty list if none
* @return list of AbstractRunners info, or an empty list if none
*/
virtual KPluginInfo::List internalServiceInfo() const;
/**
* Returns a list of all known Runner implementations
*
* @return list of ContainmentActions info, or an empty list if none
*/
virtual KPluginInfo::List internalContainmentActionsInfo() const;
/**
* Standardized mechanism for providing internal Applets by install .desktop files
* in $APPPDATA/plasma/internal/applets/
@ -296,6 +372,9 @@ protected:
*/
KPluginInfo::List standardInternalServiceInfo() const;
PluginLoader();
virtual ~PluginLoader();
private:
PluginLoaderPrivate * const d;
};

View File

@ -92,9 +92,10 @@ void PopupApplet::setPopupIcon(const QIcon &icon)
void PopupApplet::setPopupIcon(const QString &iconName)
{
// Attempt 1: is it in the plasmoid package?
if (package()) {
const QString file = package()->filePath("images", iconName);
if (Applet::d->package) {
//Attempt1: is it in the plasmoid package?
const QString file = Applet::d->package->filePath("images", iconName);
if (!file.isEmpty()) {
setPopupIcon(KIcon(file));
return;

View File

@ -36,7 +36,7 @@ public:
~AbstractRunnerPrivate();
void init(const KService::Ptr service);
void init(const QString &path);
void prepScripting(const QString &path, QString api = QString());
void prepScripting(const QString &path, const QString &api);
void setupScriptSupport();
AbstractRunner::Priority priority;

View File

@ -45,7 +45,7 @@ class AccessManagerPrivate
AccessManager *q;
DNSSD::ServiceBrowser *browser;
QMap<QString, PackageMetadata> services;
QMap<QString, RemoteObjectDescription> services;
QMap<QString, DNSSD::RemoteService::Ptr> zeroconfServices;
};

View File

@ -32,110 +32,11 @@ class QGraphicsItem;
namespace Plasma
{
class AnimationDriver;
class KineticScrolling;
struct AnimationState
{
QGraphicsItem *item;
QObject *qobj;
Animator::Animation animation;
Animator::CurveShape curve;
int interval;
int currentInterval;
int frames;
int currentFrame;
int id;
};
struct ElementAnimationState
{
QGraphicsItem *item;
QObject *qobj;
Animator::CurveShape curve;
Animator::Animation animation;
int interval;
int currentInterval;
int frames;
int currentFrame;
int id;
QPixmap pixmap;
};
struct MovementState
{
QGraphicsItem *item;
QObject *qobj;
Animator::CurveShape curve;
Animator::Movement movement;
int interval;
int currentInterval;
int frames;
int currentFrame;
QPoint start;
QPoint destination;
int id;
};
struct CustomAnimationState
{
Animator::CurveShape curve;
int frames;
int currentFrame;
int frameInterval;
int interval;
int currentInterval;
int id;
QObject *receiver;
char *slot;
};
class Animator;
class AnimatorPrivate
{
public:
AnimatorPrivate(Animator *parent);
~AnimatorPrivate();
qreal calculateProgress(int time, int duration, Animator::CurveShape curve);
void performAnimation(qreal amount, const AnimationState *state);
void performMovement(qreal amount, const MovementState *state);
void init(Animator *q);
void cleanupStates();
void animatedItemDestroyed(QObject*);
void movingItemDestroyed(QObject*);
void animatedElementDestroyed(QObject*);
void customAnimReceiverDestroyed(QObject*);
void scrollStateChanged(QAbstractAnimation::State newState,
QAbstractAnimation::State oldState);
Animator *q;
AnimationDriver *driver;
int animId;
int timerId;
QTime time;
QTimeLine timeline;
// active items
QHash<QGraphicsItem *, AnimationState *> animatedItems;
QHash<QGraphicsItem *, MovementState *> movingItems;
QHash<int, ElementAnimationState *> animatedElements;
QHash<int, CustomAnimationState *> customAnims;
// items to cull
QSet<AnimationState *> animatedItemsToDelete;
QSet<MovementState *> movingItemsToDelete;
QSet<ElementAnimationState *> animatedElementsToDelete;
QSet<CustomAnimationState *> customAnimsToDelete;
QHash<QGraphicsWidget *, KineticScrolling *> scrollingManagers;
public:
static void mapAnimation(Animator::Animation from, Animator::Animation to);
static void mapAnimation(Animator::Animation from, const QString &to);
static QHash<Animator::Animation, Animator::Animation> s_stockAnimMappings;
static QHash<Animator::Animation, QString> s_loadableAnimMappings;
};

View File

@ -145,7 +145,6 @@ public:
static uint s_maxAppletId;
static int s_maxZValue;
static int s_minZValue;
static PackageStructure::Ptr packageStructure;
static QSet<QString> s_customCategories;
//TODO: examine the usage of memory here; there's a pretty large
@ -156,9 +155,9 @@ public:
// applet attributes
QWeakPointer<Extender> extender;
Service *service;
Applet::BackgroundHints preferredBackgroundHints;
Applet::BackgroundHints backgroundHints;
Plasma::AspectRatioMode aspectRatioMode;
BackgroundHints preferredBackgroundHints;
BackgroundHints backgroundHints;
AspectRatioMode aspectRatioMode;
ImmutabilityType immutability;
// applet info we keep around in case its needed
@ -196,7 +195,7 @@ public:
KKeySequenceWidget *shortcutEditor; //TODO: subclass KConfigDialog and encapsulate this in there
ItemStatus itemStatus;
QString remoteLocation;
KUrl remoteLocation;
Ui::publishWidget publishUI;
// the applet can change size policy by itself, so save the old one for eventual restore

View File

@ -56,7 +56,6 @@ public:
lastScreen(-1),
desktop(-1), // all desktops
lastDesktop(-1),
con(0),
type(Containment::NoContainmentType),
showDropZoneDelayTimer(0),
drawWallpaper(true),
@ -124,16 +123,6 @@ public:
*/
void focusApplet(Plasma::Applet *applet);
/**
* returns the Context for this Containment
*/
Context *context();
/**
* propogates context changes
*/
void onContextChanged(Plasma::Context *con);
/**
* Handles dropped/pasted mimetype data
* @param scenePos scene-relative position
@ -177,7 +166,7 @@ public:
int desktop;
int lastDesktop;
QWeakPointer<AbstractToolBox> toolBox;
Context *con;
QString activityId;
Containment::Type type;
QHash<KJob*, QPointF> dropPoints;
QHash<KJob*, KMenu*> dropMenus;

View File

@ -37,8 +37,6 @@ public:
{
};
static PackageStructure::Ptr s_packageStructure;
ContainmentActions *q;
KPluginInfo containmentActionsDescription;
Package *package;

View File

@ -46,7 +46,7 @@ public:
void syncConfig();
Containment *addContainment(const QString &name, const QVariantList &args, uint id, bool delayedInit);
void offscreenWidgetDestroyed(QObject *);
QList<Plasma::Containment *> importLayout(const KConfigBase &conf, bool mergeConfig);
QList<Plasma::Containment *> importLayout(const KConfigGroup &conf, bool mergeConfig);
static bool s_positioningContainments;

View File

@ -46,6 +46,16 @@ public:
{
}
/**
* Check if the DataContainer is still in use.
*
* If not the signal "becameUnused" will be emitted.
*
* Warning: The DataContainer may be invalid after calling this function, because a listener
* to becameUnused() may have deleted it.
**/
void checkUsage();
SignalRelay *signalRelay(const DataContainer *dc, QObject *visualization,
uint pollingInterval, Plasma::IntervalAlignment align,
bool immediateUpdate);

View File

@ -43,33 +43,50 @@ ServiceMonitor::~ServiceMonitor()
void ServiceMonitor::slotJobFinished(Plasma::ServiceJob *job)
{
#ifndef NDEBUG
kDebug() << "engine ready!";
#endif
QString engineName = job->parameters()["EngineName"].toString();
QString location = job->destination();
QPair<QString, QString> pair(location, engineName);
#ifndef NDEBUG
kDebug() << "pair = " << pair;
#endif
if (!m_consumer->m_remoteEngines.contains(pair)) {
#ifndef NDEBUG
kDebug() << "engine does not exist yet!";
#endif
} else {
KUrl engineLocation(location);
engineLocation.setFileName(job->result().toString());
kDebug() << "setting location : "
<< engineLocation.prettyUrl();
#ifndef NDEBUG
kDebug() << "setting location : " << engineLocation.prettyUrl();
#endif
m_consumer->m_remoteEngines[pair]->setLocation(engineLocation);
}
}
void ServiceMonitor::slotServiceReady(Plasma::Service *plasmoidService)
{
#ifndef NDEBUG
kDebug() << "service ready!";
#endif
if (!m_consumer->m_engineNameForService.contains(plasmoidService)) {
#ifndef NDEBUG
kDebug() << "no engine name for service!";
#endif
#ifndef NDEBUG
kDebug() << "amount of services in map: " << m_consumer->m_engineNameForService.count();
#endif
} else {
#ifndef NDEBUG
kDebug() << "value = " << m_consumer->m_engineNameForService.value(plasmoidService);
#endif
}
#ifndef NDEBUG
kDebug() << "requesting dataengine!";
#endif
KConfigGroup op = plasmoidService->operationDescription("DataEngine");
op.writeEntry("EngineName", m_consumer->m_engineNameForService.value(plasmoidService));
plasmoidService->startOperationCall(op);
@ -113,19 +130,27 @@ DataEngine *DataEngineConsumer::dataEngine(const QString &name)
DataEngine *DataEngineConsumer::remoteDataEngine(const KUrl &location, const QString &name)
{
QPair<QString, QString> pair(location.prettyUrl(), name);
#ifndef NDEBUG
kDebug() << "pair = " << pair;
#endif
if (m_remoteEngines.contains(pair)) {
#ifndef NDEBUG
kDebug() << "existing remote dataengine at " << location;
#endif
return m_remoteEngines[pair];
}
#ifndef NDEBUG
kDebug() << "new remote dataengine at " << location;
#endif
RemoteDataEngine *engine = new RemoteDataEngine(KUrl());
m_remoteEngines[pair] = engine;
Service *plasmoidService = Service::access(location);
plasmoidService->setDestination(location.prettyUrl());
m_engineNameForService[plasmoidService] = name;
#ifndef NDEBUG
kDebug() << "name = " << name;
#endif
QObject::connect(plasmoidService, SIGNAL(serviceReady(Plasma::Service*)),
m_monitor, SLOT(slotServiceReady(Plasma::Service*)));
return engine;

View File

@ -35,8 +35,7 @@ DataEngineService::DataEngineService(DataEngine *engine)
connect(engine, SIGNAL(sourceAdded(QString)), this, SLOT(sourceAdded(QString)));
}
Plasma::ServiceJob* DataEngineService::createJob(const QString& operation,
QMap<QString,QVariant>& parameters)
Plasma::ServiceJob* DataEngineService::createJob(const QString& operation, QHash<QString,QVariant>& parameters)
{
return new GetSource(m_engine, operation, parameters, this);
}

View File

@ -42,15 +42,15 @@ class DataEngineService : public Plasma::Service
protected:
Plasma::ServiceJob* createJob(const QString& operation,
QMap<QString,QVariant>& parameters);
QHash<QString,QVariant>& parameters);
private Q_SLOTS:
void sourceAdded(QString source);
private:
DataEngine *m_engine;
QMap<QString, QStringList> m_peersAlreadyUpdated;
QMap<QString, DataEngine::Data> m_data;
QHash<QString, QStringList> m_peersAlreadyUpdated;
QHash<QString, DataEngine::Data> m_data;
friend class GetSource;
};

View File

@ -31,14 +31,18 @@ int **allocateWaveMap(const QSize &size)
{
int **waveMap = new int *[size.width()];
if (!waveMap) {
#ifndef NDEBUG
kDebug() << "could not allocate wave map";
#endif
return 0;
}
for (int x = 0; x < size.width(); ++x) {
waveMap[x] = new int[size.height()];
if (!waveMap[x]) {
#ifndef NDEBUG
kDebug() << "could not allocate wave map";
#endif
return 0;
}
}

View File

@ -33,7 +33,7 @@ namespace Plasma
{
GetSource::GetSource(DataEngine *engine, const QString& operation,
QMap<QString,QVariant>& parameters,
QHash<QString,QVariant>& parameters,
DataEngineService *service)
: ServiceJob(QString("publickey"), operation, parameters, service),
m_engine(engine),
@ -43,7 +43,9 @@ GetSource::GetSource(DataEngine *engine, const QString& operation,
void GetSource::start()
{
#ifndef NDEBUG
kDebug() << "Trying to perform the action" << operationName();
#endif
//TODO: check with capabilities before performing actions.
if (operationName() == "GetSource") {
@ -62,7 +64,9 @@ void GetSource::start()
Service *service = m_engine->serviceForSource(source);
QString serviceName = "plasma-service-" + service->name();
#ifndef NDEBUG
kDebug() << "serviceForSource: getting source " << serviceName;
#endif
service->d->publish(Plasma::NoAnnouncement, serviceName);
if (!AuthorizationManager::self()->d->matchingRule(serviceName, identity())) {
AuthorizationRule *rule = new AuthorizationRule(serviceName, identity().id());

View File

@ -33,7 +33,7 @@ class GetSource : public Plasma::ServiceJob
public:
GetSource(DataEngine *engine, const QString& operation,
QMap<QString,QVariant>& parameters,
QHash<QString,QVariant>& parameters,
DataEngineService *service = 0);
void start();

View File

@ -23,32 +23,71 @@
#include "../package.h"
#include "../service.h"
#include <QCryptographicHash>
#include <QDir>
#include <QString>
#include <QSharedData>
namespace Plasma
{
class PackagePrivate
class ContentStructure
{
public:
ContentStructure()
: directory(false),
required(false)
{
}
ContentStructure(const ContentStructure &other)
{
paths = other.paths;
#ifndef PLASMA_NO_PACKAGE_EXTRADATA
name = other.name;
mimeTypes = other.mimeTypes;
#endif
directory = other.directory;
required = other.required;
}
QString found;
QStringList paths;
#ifndef PLASMA_NO_PACKAGE_EXTRADATA
QString name;
QStringList mimeTypes;
#endif
bool directory : 1;
bool required : 1;
};
class PackagePrivate : public QSharedData
{
public:
PackagePrivate(const PackageStructure::Ptr st, const QString &p);
PackagePrivate(const PackageStructure::Ptr st, const QString &packageRoot, const QString &path);
PackagePrivate();
PackagePrivate(const PackagePrivate &other);
~PackagePrivate();
PackagePrivate &operator=(const PackagePrivate &rhs);
void publish(AnnouncementMethods methods);
void unpublish();
bool isPublished() const;
void createPackageMetadata(const QString &path);
void updateHash(const QString &basePath, const QString &subPath, const QDir &dir, QCryptographicHash &hash);
static bool installPackage(const QString &archivePath, const QString &packageRoot, const QString &servicePrefix);
static bool uninstallPackage(const QString &packageName, const QString &packageRoot, const QString &servicePrefix);
#ifdef QCA2_FOUND
void updateHash(const QString &basePath, const QString &subPath, const QDir &dir, QCA::Hash &hash);
QWeakPointer<PackageStructure> structure;
QString path;
QStringList contentsPrefixPaths;
QString defaultPackageRoot;
QString servicePrefix;
QHash<QString, QString> discoveries;
QHash<QByteArray, ContentStructure> contents;
#ifndef PLASMA_NO_PACKAGE_EXTRADATA
QStringList mimeTypes;
#endif
PackageStructure::Ptr structure;
Service *service;
bool valid;
KPluginInfo *metadata;
bool externalPaths : 1;
bool valid : 1;
};
}

View File

@ -29,225 +29,203 @@
#include <klocale.h>
#include <kmessagebox.h>
#ifndef PLASMA_NO_KNEWSTUFF
#include <knewstuff3/downloaddialog.h>
#endif
#include "plasma/private/wallpaper_p.h"
#include "private/wallpaper_p.h"
#include "package.h"
#include "config-plasma.h"
namespace Plasma
{
PlasmoidPackage::PlasmoidPackage(QObject *parent)
: Plasma::PackageStructure(parent, QString("Plasmoid"))
void ChangeableMainScriptPackage::pathChanged(Package *package)
{
KDesktopFile config(package->path() + "/metadata.desktop");
KConfigGroup cg = config.desktopGroup();
QString mainScript = cg.readEntry("X-Plasma-MainScript", QString());
if (!mainScript.isEmpty()) {
package->addFileDefinition("mainscript", mainScript, i18n("Main Script File"));
package->setRequired("mainscript", true);
}
}
void PlasmoidPackage::initPackage(Package *package)
{
QString pathsString(getenv("PLASMA_CUSTOM_PREFIX_PATHS"));
if (!pathsString.isEmpty()) {
QStringList prefixPaths(pathsString.split(":"));
if (!prefixPaths.isEmpty()) {
setContentsPrefixPaths(prefixPaths);
package->setContentsPrefixPaths(prefixPaths);
}
}
addDirectoryDefinition("images", "images", i18n("Images"));
package->setServicePrefix("plasma-applet-");
package->setDefaultPackageRoot("plasma/plasmoids");
package->addDirectoryDefinition("images", "images", i18n("Images"));
QStringList mimetypes;
mimetypes << "image/svg+xml" << "image/png" << "image/jpeg";
setMimetypes("images", mimetypes);
package->setMimeTypes("images", mimetypes);
addDirectoryDefinition("config", "config", i18n("Configuration Definitions"));
package->addDirectoryDefinition("config", "config", i18n("Configuration Definitions"));
mimetypes.clear();
mimetypes << "text/xml";
setMimetypes("config", mimetypes);
package->setMimeTypes("config", mimetypes);
addDirectoryDefinition("ui", "ui", i18n("User Interface"));
setMimetypes("ui", mimetypes);
package->addDirectoryDefinition("ui", "ui", i18n("User Interface"));
package->setMimeTypes("ui", mimetypes);
addDirectoryDefinition("data", "data", i18n("Data Files"));
package->addDirectoryDefinition("data", "data", i18n("Data Files"));
addDirectoryDefinition("scripts", "code", i18n("Executable Scripts"));
package->addDirectoryDefinition("scripts", "code", i18n("Executable Scripts"));
mimetypes.clear();
mimetypes << "text/plain";
setMimetypes("scripts", mimetypes);
package->setMimeTypes("scripts", mimetypes);
addDirectoryDefinition("translations", "locale", i18n("Translations"));
package->addDirectoryDefinition("translations", "locale", i18n("Translations"));
addFileDefinition("mainconfigui", "ui/config.ui", i18n("Main Config UI File"));
addFileDefinition("mainconfigxml", "config/main.xml", i18n("Configuration XML file"));
addFileDefinition("mainscript", "code/main", i18n("Main Script File"));
addFileDefinition("defaultconfig", "config/default-configrc", i18n("Default configuration"));
addDirectoryDefinition("animations", "animations", i18n("Animation scripts"));
setRequired("mainscript", true);
package->addFileDefinition("mainconfigui", "ui/config.ui", i18n("Main Config UI File"));
package->addFileDefinition("mainconfigxml", "config/main.xml", i18n("Configuration XML file"));
package->addFileDefinition("mainscript", "code/main", i18n("Main Script File"));
package->addFileDefinition("defaultconfig", "config/default-configrc", i18n("Default configuration"));
package->addDirectoryDefinition("animations", "animations", i18n("Animation scripts"));
package->setRequired("mainscript", true);
}
PlasmoidPackage::~PlasmoidPackage()
void DataEnginePackage::initPackage(Package *package)
{
#ifndef PLASMA_NO_KNEWSTUFF
delete m_knsDialog.data();
#endif
}
package->setServicePrefix("plasma-dataengine-");
package->setDefaultPackageRoot("plasma/dataengines/");
void PlasmoidPackage::pathChanged()
{
KDesktopFile config(path() + "/metadata.desktop");
KConfigGroup cg = config.desktopGroup();
QString mainScript = cg.readEntry("X-Plasma-MainScript", QString());
if (!mainScript.isEmpty()) {
addFileDefinition("mainscript", mainScript, i18n("Main Script File"));
setRequired("mainscript", true);
}
}
package->addDirectoryDefinition("data", "data", i18n("Data Files"));
void PlasmoidPackage::createNewWidgetBrowser(QWidget *parent)
{
#ifndef PLASMA_NO_KNEWSTUFF
KNS3::DownloadDialog *knsDialog = m_knsDialog.data();
if (!knsDialog) {
m_knsDialog = knsDialog = new KNS3::DownloadDialog("plasmoids.knsrc", parent);
connect(knsDialog, SIGNAL(accepted()), this, SIGNAL(newWidgetBrowserFinished()));
}
knsDialog->show();
knsDialog->raise();
#endif
}
DataEnginePackage::DataEnginePackage(QObject *parent)
: Plasma::PackageStructure(parent, QString("DataEngine"))
{
setServicePrefix("plasma-dataengine-");
setDefaultPackageRoot("plasma/dataengine/");
addDirectoryDefinition("data", "data", i18n("Data Files"));
addDirectoryDefinition("scripts", "code", i18n("Executable Scripts"));
package->addDirectoryDefinition("scripts", "code", i18n("Executable Scripts"));
QStringList mimetypes;
mimetypes << "text/plain";
setMimetypes("scripts", mimetypes);
package->setMimeTypes("scripts", mimetypes);
addDirectoryDefinition("services", "services/", i18n("Service Descriptions"));
setMimetypes("services", mimetypes);
package->addDirectoryDefinition("services", "services/", i18n("Service Descriptions"));
package->setMimeTypes("services", mimetypes);
addDirectoryDefinition("translations", "locale", i18n("Translations"));
package->addDirectoryDefinition("translations", "locale", i18n("Translations"));
addFileDefinition("mainscript", "code/main", i18n("Main Script File"));
setRequired("mainscript", true);
package->addFileDefinition("mainscript", "code/main", i18n("Main Script File"));
package->setRequired("mainscript", true);
}
DataEnginePackage::~DataEnginePackage()
void RunnerPackage::initPackage(Package *package)
{
package->setServicePrefix("plasma-runner-");
package->setDefaultPackageRoot("plasma/runners/");
package->addDirectoryDefinition("data", "data", i18n("Data Files"));
package->addDirectoryDefinition("scripts", "code", i18n("Executable Scripts"));
QStringList mimetypes;
mimetypes << "text/plain";
package->setMimeTypes("scripts", mimetypes);
package->addDirectoryDefinition("translations", "locale", i18n("Translations"));
package->addFileDefinition("mainscript", "code/main", i18n("Main Script File"));
package->setRequired("mainscript", true);
}
void DataEnginePackage::pathChanged()
void ThemePackage::initPackage(Package *package)
{
KDesktopFile config(path() + "/metadata.desktop");
KConfigGroup cg = config.desktopGroup();
QString mainScript = cg.readEntry("X-Plasma-MainScript", QString());
if (!mainScript.isEmpty()) {
addFileDefinition("mainscript", mainScript, i18n("Main Script File"));
setRequired("mainscript", true);
}
}
ThemePackage::ThemePackage(QObject *parent)
: Plasma::PackageStructure(parent, QString("Plasma Theme"))
{
addDirectoryDefinition("dialogs", "dialogs/", i18n("Images for dialogs"));
addFileDefinition("dialogs/background", "dialogs/background.svg",
package->addDirectoryDefinition("dialogs", "dialogs/", i18n("Images for dialogs"));
package->addFileDefinition("dialogs/background", "dialogs/background.svg",
i18n("Generic dialog background"));
addFileDefinition("dialogs/shutdowndialog", "dialogs/shutdowndialog.svg",
package->addFileDefinition("dialogs/shutdowndialog", "dialogs/shutdowndialog.svg",
i18n("Theme for the logout dialog"));
addDirectoryDefinition("wallpapers", "wallpapers/", i18n("Wallpaper packages"));
addDirectoryDefinition("animations", "animations/", i18n("Animation scripts"));
package->addDirectoryDefinition("wallpapers", "wallpapers/", i18n("Wallpaper packages"));
package->addDirectoryDefinition("animations", "animations/", i18n("Animation scripts"));
addDirectoryDefinition("widgets", "widgets/", i18n("Images for widgets"));
addFileDefinition("widgets/background", "widgets/background.svg",
package->addDirectoryDefinition("widgets", "widgets/", i18n("Images for widgets"));
package->addFileDefinition("widgets/background", "widgets/background.svg",
i18n("Background image for widgets"));
addFileDefinition("widgets/clock", "widgets/clock.svg",
package->addFileDefinition("widgets/clock", "widgets/clock.svg",
i18n("Analog clock face"));
addFileDefinition("widgets/panel-background", "widgets/panel-background.svg",
package->addFileDefinition("widgets/panel-background", "widgets/panel-background.svg",
i18n("Background image for panels"));
addFileDefinition("widgets/plot-background", "widgets/plot-background.svg",
package->addFileDefinition("widgets/plot-background", "widgets/plot-background.svg",
i18n("Background for graphing widgets"));
addFileDefinition("widgets/tooltip", "widgets/tooltip.svg",
package->addFileDefinition("widgets/tooltip", "widgets/tooltip.svg",
i18n("Background image for tooltips"));
addDirectoryDefinition("opaque/dialogs", "opaque/dialogs/", i18n("Opaque images for dialogs"));
addFileDefinition("opaque/dialogs/background", "opaque/dialogs/background.svg",
package->addDirectoryDefinition("opaque/dialogs", "opaque/dialogs/", i18n("Opaque images for dialogs"));
package->addFileDefinition("opaque/dialogs/background", "opaque/dialogs/background.svg",
i18n("Opaque generic dialog background"));
addFileDefinition("opaque/dialogs/shutdowndialog", "opaque/dialogs/shutdowndialog.svg",
package->addFileDefinition("opaque/dialogs/shutdowndialog", "opaque/dialogs/shutdowndialog.svg",
i18n("Opaque theme for the logout dialog"));
addDirectoryDefinition("opaque/widgets", "opaque/widgets/", i18n("Opaque images for widgets"));
addFileDefinition("opaque/widgets/panel-background", "opaque/widgets/panel-background.svg",
package->addDirectoryDefinition("opaque/widgets", "opaque/widgets/", i18n("Opaque images for widgets"));
package->addFileDefinition("opaque/widgets/panel-background", "opaque/widgets/panel-background.svg",
i18n("Opaque background image for panels"));
addFileDefinition("opaque/widgets/tooltip", "opaque/widgets/tooltip.svg",
package->addFileDefinition("opaque/widgets/tooltip", "opaque/widgets/tooltip.svg",
i18n("Opaque background image for tooltips"));
addDirectoryDefinition("locolor/dialogs", "locolor/dialogs/",
package->addDirectoryDefinition("locolor/dialogs", "locolor/dialogs/",
i18n("Low color images for dialogs"));
addFileDefinition("locolor/dialogs/background", "locolor/dialogs/background.svg",
package->addFileDefinition("locolor/dialogs/background", "locolor/dialogs/background.svg",
i18n("Low color generic dialog background"));
addFileDefinition("locolor/dialogs/shutdowndialog", "locolor/dialogs/shutdowndialog.svg",
package->addFileDefinition("locolor/dialogs/shutdowndialog", "locolor/dialogs/shutdowndialog.svg",
i18n("Low color theme for the logout dialog"));
addDirectoryDefinition("locolor/widgets", "locolor/widgets/", i18n("Images for widgets"));
addFileDefinition("locolor/widgets/background", "locolor/widgets/background.svg",
package->addDirectoryDefinition("locolor/widgets", "locolor/widgets/", i18n("Images for widgets"));
package->addFileDefinition("locolor/widgets/background", "locolor/widgets/background.svg",
i18n("Low color background image for widgets"));
addFileDefinition("locolor/widgets/clock", "locolor/widgets/clock.svg",
package->addFileDefinition("locolor/widgets/clock", "locolor/widgets/clock.svg",
i18n("Low color analog clock face"));
addFileDefinition("locolor/widgets/panel-background", "locolor/widgets/panel-background.svg",
package->addFileDefinition("locolor/widgets/panel-background", "locolor/widgets/panel-background.svg",
i18n("Low color background image for panels"));
addFileDefinition("locolor/widgets/plot-background", "locolor/widgets/plot-background.svg",
package->addFileDefinition("locolor/widgets/plot-background", "locolor/widgets/plot-background.svg",
i18n("Low color background for graphing widgets"));
addFileDefinition("locolor/widgets/tooltip", "locolor/widgets/tooltip.svg",
package->addFileDefinition("locolor/widgets/tooltip", "locolor/widgets/tooltip.svg",
i18n("Low color background image for tooltips"));
addFileDefinition("colors", "colors", i18n("KColorScheme configuration file"));
package->addFileDefinition("colors", "colors", i18n("KColorScheme configuration file"));
QStringList mimetypes;
mimetypes << "image/svg+xml";
setDefaultMimetypes(mimetypes);
package->setDefaultMimeTypes(mimetypes);
}
WallpaperPackage::WallpaperPackage(Wallpaper *paper, QObject *parent)
: PackageStructure(parent, "Background"),
m_paper(paper),
WallpaperPackage::WallpaperPackage(Wallpaper *paper)
: PackageStructure(),
m_fullPackage(true),
m_targetSize(100000, 100000),
m_resizeMethod(Wallpaper::ScaledResize)
{
if (paper) {
connect(paper, SIGNAL(renderHintsChanged()), this, SLOT(renderHintsChanged()));
}
}
void WallpaperPackage::initPackage(Package *package)
{
QStringList mimetypes;
mimetypes << "image/svg" << "image/png" << "image/jpeg" << "image/jpg";
setDefaultMimetypes(mimetypes);
package->setDefaultMimeTypes(mimetypes);
addDirectoryDefinition("images", "images/", i18n("Images"));
setRequired("images", true);
addFileDefinition("screenshot", "screenshot.png", i18n("Screenshot"));
setAllowExternalPaths(true);
if (m_paper) {
m_targetSize = m_paper->d->targetSize.toSize();
m_resizeMethod = m_paper->d->lastResizeMethod;
connect(m_paper, SIGNAL(renderHintsChanged()), this, SLOT(renderHintsChanged()));
connect(m_paper, SIGNAL(destroyed(QObject*)), this, SLOT(paperDestroyed()));
}
package->addDirectoryDefinition("images", "images/", i18n("Images"));
package->setRequired("images", true);
package->addFileDefinition("screenshot", "screenshot.png", i18n("Screenshot"));
package->setAllowExternalPaths(true);
}
void WallpaperPackage::renderHintsChanged()
{
if (m_paper) {
m_targetSize = m_paper->d->targetSize.toSize();
m_resizeMethod = m_paper->d->lastResizeMethod;
Wallpaper *paper = qobject_cast<Wallpaper *>(sender());
if (!paper) {
return;
}
if (m_fullPackage) {
findBestPaper();
//FIXME: findBestPaper(packages.value(paper));
}
}
void WallpaperPackage::pathChanged()
void WallpaperPackage::pathChanged(Package *package)
{
static bool guard = false;
@ -257,20 +235,20 @@ void WallpaperPackage::pathChanged()
guard = true;
QFileInfo info(path());
QFileInfo info(package->path());
m_fullPackage = info.isDir();
removeDefinition("preferred");
setRequired("images", m_fullPackage);
package->removeDefinition("preferred");
package->setRequired("images", m_fullPackage);
if (m_fullPackage) {
setContentsPrefixPaths(QStringList() << "contents/");
findBestPaper();
package->setContentsPrefixPaths(QStringList() << "contents/");
findBestPaper(package);
} else {
// dirty trick to support having a file passed in instead of a directory
addFileDefinition("preferred", info.fileName(), i18n("Recommended wallpaper file"));
setContentsPrefixPaths(QStringList());
package->addFileDefinition("preferred", info.fileName(), i18n("Recommended wallpaper file"));
package->setContentsPrefixPaths(QStringList());
//kDebug() << "changing" << path() << "to" << info.path();
setPath(info.path());
package->setPath(info.path());
}
guard = false;
@ -278,18 +256,17 @@ void WallpaperPackage::pathChanged()
QSize WallpaperPackage::resSize(const QString &str) const
{
int index = str.indexOf('x');
const int index = str.indexOf('x');
if (index != -1) {
return QSize(str.left(index).toInt(),
str.mid(index + 1).toInt());
} else {
return QSize();
return QSize(str.left(index).toInt(), str.mid(index + 1).toInt());
}
return QSize();
}
void WallpaperPackage::findBestPaper()
void WallpaperPackage::findBestPaper(Package *package)
{
QStringList images = entryList("images");
QStringList images = package->entryList("images");
if (images.empty()) {
return;
}
@ -301,7 +278,7 @@ void WallpaperPackage::findBestPaper()
QString bestImage;
foreach (const QString &entry, images) {
QSize candidate = resSize(QFileInfo(entry).baseName());
const QSize candidate = resSize(QFileInfo(entry).baseName());
if (candidate == QSize()) {
continue;
}
@ -319,7 +296,7 @@ void WallpaperPackage::findBestPaper()
}
//kDebug() << "best image" << bestImage;
addFileDefinition("preferred", path("images") + bestImage, i18n("Recommended wallpaper file"));
package->addFileDefinition("preferred", package->filePath("images") + bestImage, i18n("Recommended wallpaper file"));
}
float WallpaperPackage::distance(const QSize& size, const QSize& desired,
@ -352,15 +329,15 @@ float WallpaperPackage::distance(const QSize& size, const QSize& desired,
}
}
void WallpaperPackage::paperDestroyed()
void ContainmentActionsPackage::initPackage(Package *package)
{
m_paper = 0;
package->setDefaultPackageRoot("plasma/containmentactions/");
package->addFileDefinition("mainscript", "code/main", i18n("Main Script File"));
}
ContainmentActionsPackage::ContainmentActionsPackage(QObject *parent)
: Plasma::PackageStructure(parent, QString("ContainmentActions"))
void GenericPackage::initPackage(Package *package)
{
//FIXME how do I do the mimetypes stuff?
package->setDefaultPackageRoot("plasma/packages/");
}
} // namespace Plasma

View File

@ -20,55 +20,41 @@
#ifndef LIBS_PLASMA_PACKAGES_P_H
#define LIBS_PLASMA_PACKAGES_P_H
#include "plasma/packagestructure.h"
#include "plasma/wallpaper.h"
#include "plasma/plasma.h"
#include "config-plasma.h"
#ifndef PLASMA_NO_KNEWSTUFF
namespace KNS3
{
class DownloadDialog;
} // namespace KNS
#endif
#include "packagestructure.h"
#include "plasma.h"
#include "wallpaper.h"
namespace Plasma
{
class PlasmoidPackage : public PackageStructure
class ChangeableMainScriptPackage : public PackageStructure
{
Q_OBJECT
public:
explicit PlasmoidPackage(QObject *parent = 0);
~PlasmoidPackage();
void createNewWidgetBrowser(QWidget *parent = 0);
protected:
void pathChanged();
private:
#ifndef PLASMA_NO_KNEWSTUFF
QWeakPointer<KNS3::DownloadDialog> m_knsDialog;
#endif
void pathChanged(Package *package);
};
class DataEnginePackage : public PackageStructure
class PlasmoidPackage : public ChangeableMainScriptPackage
{
Q_OBJECT
public:
explicit DataEnginePackage(QObject *parent = 0);
~DataEnginePackage();
void initPackage(Package *package);
};
protected:
void pathChanged();
class DataEnginePackage : public ChangeableMainScriptPackage
{
public:
void initPackage(Package *package);
};
class RunnerPackage : public ChangeableMainScriptPackage
{
public:
void initPackage(Package *package);
};
class ThemePackage : public PackageStructure
{
Q_OBJECT
public:
explicit ThemePackage(QObject *parent = 0);
void initPackage(Package *package);
};
class WallpaperPackage : public PackageStructure
@ -76,19 +62,17 @@ class WallpaperPackage : public PackageStructure
Q_OBJECT
public:
explicit WallpaperPackage(Wallpaper *paper = 0, QObject *parent = 0);
protected:
void pathChanged();
explicit WallpaperPackage(Wallpaper *paper = 0);
void initPackage(Package *package);
void pathChanged(Package *package);
private:
QSize resSize(const QString &str) const;
void findBestPaper();
void findBestPaper(Package *package);
float distance(const QSize& size, const QSize& desired,
Plasma::Wallpaper::ResizeMethod method) const;
private Q_SLOTS:
void paperDestroyed();
void renderHintsChanged();
private:
@ -100,13 +84,15 @@ private:
class ContainmentActionsPackage : public PackageStructure
{
Q_OBJECT
public:
explicit ContainmentActionsPackage(QObject *parent = 0);
void initPackage(Package *package);
};
PackageStructure::Ptr defaultPackageStructure(ComponentType type);
class GenericPackage : public PackageStructure
{
public:
void initPackage(Package *package);
};
} // namespace Plasma

View File

@ -25,14 +25,15 @@
#include <plasma/applet.h>
#include <plasma/remote/authorizationmanager.h>
#include <plasma/remote/authorizationrule.h>
#include <plasma/packagemetadata.h>
#include <plasma/service.h>
#include <plasma/servicejob.h>
#include <kdebug.h>
#include <ktemporaryfile.h>
#include <kzip.h>
#include <kservicetypetrader.h>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QHostInfo>
@ -40,37 +41,41 @@
namespace Plasma
{
PlasmoidServiceJob::PlasmoidServiceJob(const QString &plasmoidLocation,
const QString &destination,
PlasmoidServiceJob::PlasmoidServiceJob(const QString &destination,
const QString &operation,
QMap<QString,QVariant>& parameters,
QHash<QString,QVariant>& parameters,
PlasmoidService *service)
: Plasma::ServiceJob(destination, operation, parameters,
static_cast<Plasma::Service*>(service)),
m_service(service),
m_packagePath(plasmoidLocation)
m_service(service)
{
}
void PlasmoidServiceJob::start()
{
if (operationName() == "GetPackage") {
#ifndef NDEBUG
kDebug() << "sending " << m_service->m_packagePath;
#endif
if (m_service->m_packagePath.isEmpty()) {
// just return the plugin name in this case
setResult(m_service->m_pluginName);
} else {
QFileInfo fileInfo(m_service->m_packagePath);
if (fileInfo.exists() && fileInfo.isAbsolute()) {
#ifndef NDEBUG
kDebug() << "file exists, let's try and read it";
#endif
QFile file(m_service->m_packagePath);
file.open(QIODevice::ReadOnly);
setResult(file.readAll());
} else {
kDebug() << "file doesn't exists, we're sending the plugin name";
setResult(m_packagePath);
setResult(QString());
}
}
} else if (operationName() == "GetMetaData") {
KTemporaryFile tempFile;
m_service->m_metadata.write(tempFile.fileName());
QFile file(tempFile.fileName());
QFile file(m_service->m_metadata);
setResult(file.readAll());
} else if (operationName() == "DataEngine") {
DataEngine *engine = m_service->dataEngine(parameters()["EngineName"].toString());
@ -83,63 +88,58 @@ void PlasmoidServiceJob::start()
}
setResult(serviceName);
}
}
PlasmoidService::PlasmoidService(const QString &packageLocation)
: Plasma::Service(0)
{
setName("plasmoidservice");
QString location;
location = packageLocation;
if (!location.endsWith('/')) {
location.append('/');
}
m_metadata.read(location + "metadata.desktop");
if (!m_metadata.isValid()) {
kDebug() << "not a valid package";
}
if (!m_tempFile.open()) {
kDebug() << "could not create tempfile";
}
QString packagePath = m_tempFile.fileName();
m_tempFile.close();
// put everything into a zip archive
KZip creation(packagePath);
creation.setCompression(KZip::NoCompression);
if (!creation.open(QIODevice::WriteOnly)) {
kDebug() << "could not open archive";
}
creation.addLocalFile(location + "metadata.desktop", "metadata.desktop");
location.append("contents/");
creation.addLocalDirectory(location, "contents");
creation.close();
m_packagePath = packagePath;
setResult(false);
}
PlasmoidService::PlasmoidService(Applet *applet)
: Plasma::Service(applet),
m_pluginName(applet->pluginName())
{
setName("plasmoidservice");
if (!applet->package() || !applet->package()->isValid()) {
kDebug() << "not a valid package";
m_packagePath = applet->pluginName();
if (applet->package().isValid()) {
const QString root = applet->package().path();
m_metadata = root + "metadata.desktop";
m_tempFile.open();
m_packagePath = m_tempFile.fileName();
m_tempFile.close();
// put everything into a zip archive
KZip creation(m_packagePath);
creation.setCompression(KZip::NoCompression);
if (creation.open(QIODevice::WriteOnly)) {
QDir dir(root);
foreach (const QString &entry, dir.entryList(QDir::Files)) {
creation.addLocalFile(root + entry, entry);
}
foreach (const QString &entry, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) {
creation.addLocalDirectory(root + entry, entry);
}
creation.close();
} else {
#ifndef NDEBUG
kDebug() << "could not open archive";
#endif
}
} else {
#ifndef NDEBUG
kDebug() << "applet lacks a valid package";
#endif
const QString constraint = QString("[X-KDE-PluginInfo-Name] == '%1'").arg(applet->pluginName());
KService::List offers = KServiceTypeTrader::self()->query("Plasma/Applet", constraint);
if (!offers.isEmpty()) {
m_metadata = offers.first()->entryPath();
}
}
}
PackageMetadata PlasmoidService::metadata() const
Plasma::ServiceJob* PlasmoidService::createJob(const QString& operation, QHash<QString,QVariant>& parameters)
{
return m_metadata;
}
Plasma::ServiceJob* PlasmoidService::createJob(const QString& operation,
QMap<QString,QVariant>& parameters)
{
return new PlasmoidServiceJob(m_packagePath, destination(), operation, parameters, this);
return new PlasmoidServiceJob(destination(), operation, parameters, this);
}
}

View File

@ -21,7 +21,6 @@
#include "dataengineconsumer_p.h"
#include "../packagemetadata.h"
#include "../package.h"
#include "../service.h"
#include "../servicejob.h"
@ -41,17 +40,15 @@ class PlasmoidServiceJob : public ServiceJob
Q_OBJECT
public:
PlasmoidServiceJob(const QString &plasmoidLocation,
const QString &destination,
PlasmoidServiceJob(const QString &destination,
const QString &operation,
QMap<QString,QVariant>& parameters,
PlasmoidService *parent = 0);
QHash<QString,QVariant>& parameters,
PlasmoidService *parent);
void start();
private:
PlasmoidService *m_service;
QString m_packagePath;
QString m_pluginName;
};
@ -60,18 +57,15 @@ class PlasmoidService : public Service, DataEngineConsumer
Q_OBJECT
public:
PlasmoidService(const QString &plasmoidLocation);
PlasmoidService(Applet *applet);
PackageMetadata metadata() const;
protected:
Plasma::ServiceJob* createJob(const QString& operation,
QMap<QString,QVariant>& parameters);
Plasma::ServiceJob* createJob(const QString& operation, QHash<QString,QVariant>& parameters);
private:
QString m_packagePath;
PackageMetadata m_metadata;
QString m_metadata;
QString m_pluginName;
KTemporaryFile m_tempFile;
friend class PlasmoidServiceJob;

View File

@ -42,7 +42,9 @@ RemoteDataEngine::RemoteDataEngine(KUrl location, QObject* parent, const QVarian
if (!location.isEmpty()) {
setLocation(location);
} else {
#ifndef NDEBUG
kDebug() << "LOCATION IS EMPTY";
#endif
}
}
@ -84,10 +86,6 @@ void RemoteDataEngine::initRemoteService(const QString &source, RemoteService *s
}
}
void RemoteDataEngine::init()
{
}
void RemoteDataEngine::serviceReady(Plasma::Service *service)
{
m_service = service;
@ -111,14 +109,18 @@ QStringList RemoteDataEngine::sources() const
void RemoteDataEngine::remoteCallFinished(Plasma::ServiceJob *job)
{
if (job->operationName() == "GetSourceNames") {
#ifndef NDEBUG
kDebug() << "get source names";
#endif
const QSet<QString> oldsources = m_sources;
m_sources = QSet<QString>::fromList(job->result().toStringList());
//first check if there are sources that have to be removed:
foreach (const QString &source, oldsources) {
if (!m_sources.contains(source)) {
#ifndef NDEBUG
kDebug() << "source no longer exists... remove that data.";
#endif
removeSource(source);
emit sourceRemoved(source);
}
@ -135,7 +137,9 @@ void RemoteDataEngine::remoteCallFinished(Plasma::ServiceJob *job)
const SourceDict s = containerDict();
foreach (const QString &source, m_sources) {
if (!oldsources.contains(source) && !s.contains(source)) {
#ifndef NDEBUG
kDebug() << "new source = " << source;
#endif
emit sourceAdded(source);
}
}
@ -148,10 +152,14 @@ void RemoteDataEngine::remoteCallFinished(Plasma::ServiceJob *job)
m_pendingSources.clear();
} else if (job->operationName() == "GetSource") {
QString source = job->parameters().value("SourceName").toString();
#ifndef NDEBUG
kDebug() << "setting data for " << source;
#endif
bool newSource = !m_sources.contains(source);
if (job->result().type() == QVariant::Bool && job->result().toBool() == false) {
#ifndef NDEBUG
kDebug() << "there is no update";
#endif
if (newSource) {
// the source doesn't exist on the remote side!
removeSource(source);
@ -174,7 +182,9 @@ void RemoteDataEngine::remoteCallFinished(Plasma::ServiceJob *job)
}
} else {
QString source = job->parameters().value("SourceName").toString();
#ifndef NDEBUG
kDebug() << "setting serviceForSource for " << source;
#endif
QString resource = job->result().toString();
KUrl loc = m_location;
loc.setFileName(resource);
@ -182,7 +192,9 @@ void RemoteDataEngine::remoteCallFinished(Plasma::ServiceJob *job)
if (rs) {
rs->setLocation(loc);
} else {
#ifndef NDEBUG
kDebug() << "no such service?" << source;
#endif
}
}
}

View File

@ -42,7 +42,6 @@ public:
void setLocation(KUrl location);
protected:
void init();
QStringList sources() const;
bool updateSourceEvent(const QString &source);
bool sourceRequestEvent(const QString &source);

View File

@ -77,18 +77,24 @@ RemoteService::~RemoteService()
void RemoteService::slotReadyForRemoteAccess()
{
#ifndef NDEBUG
kDebug() << "AuthorizationManager is now ready for remote access!";
#endif
setLocation(m_location);
}
void RemoteService::setLocation(const KUrl &location)
{
#ifndef NDEBUG
kDebug() << "Setting RemoteService location to " << location.prettyUrl();
#endif
m_uuid = QUuid::createUuid().toString();
Credentials identity = AuthorizationManager::self()->d->myCredentials;
if (!identity.canSign()) {
#ifndef NDEBUG
kDebug() << "we can't sign? how did we get here?";
#endif
return;
}
@ -141,7 +147,9 @@ void RemoteService::callCompleted(Jolie::PendingCallWatcher *watcher)
Jolie::Message response = reply.reply();
if (response.operationName() == "startConnection") {
#ifndef NDEBUG
kDebug() << "Started connection: fetching .operations";
#endif
m_token = JolieMessage::field(JolieMessage::Field::TOKEN, response);
Jolie::Message getOpDesc(m_location.path(KUrl::RemoveTrailingSlash).remove(0, 1).toUtf8(),
"getOperations");
@ -152,13 +160,17 @@ void RemoteService::callCompleted(Jolie::PendingCallWatcher *watcher)
this, SLOT(callCompleted(Jolie::PendingCallWatcher*)));
} else if (response.operationName() == "getOperations") {
if (response.fault().name() == JolieMessage::Error::REQUIREPIN) {
#ifndef NDEBUG
kDebug() << "pin required, request auth interface";
#endif
ClientPinRequest *request = new ClientPinRequest(this);
connect(request, SIGNAL(changed(Plasma::ClientPinRequest*)),
this, SLOT(slotGotPin(Plasma::ClientPinRequest*)));
AuthorizationManager::self()->d->authorizationInterface->clientPinRequest(*request);
} else {
#ifndef NDEBUG
kDebug() << "RemoteService is now ready for use!";
#endif
m_operationsScheme = JolieMessage::field(JolieMessage::Field::OPERATIONSDESCRIPTION, response);
m_token = JolieMessage::field(JolieMessage::Field::TOKEN, response);
m_ready = true;
@ -176,10 +188,14 @@ void RemoteService::callCompleted(Jolie::PendingCallWatcher *watcher)
foreach (const QString &operation, operationNames()) {
if (enabledOperationsList.contains(operation) && !isOperationEnabled(operation)) {
#ifndef NDEBUG
kDebug() << "yeah, we're enabling the operation with the name " << operation;
#endif
setOperationEnabled(operation, true);
} else if (!enabledOperationsList.contains(operation) && isOperationEnabled(operation)) {
#ifndef NDEBUG
kDebug() << "we're disabling the operation with the name " << operation;
#endif
setOperationEnabled(operation, false);
}
}
@ -188,7 +204,9 @@ void RemoteService::callCompleted(Jolie::PendingCallWatcher *watcher)
m_busy = false;
slotFinished();
} else {
#ifndef NDEBUG
kDebug() << "How did we end up here?";
#endif
}
}
@ -233,15 +251,19 @@ void RemoteService::slotUpdateEnabledOperations()
connect(watcher, SIGNAL(finished(Jolie::PendingCallWatcher*)),
this, SLOT(callCompleted(Jolie::PendingCallWatcher*)));
} else {
#ifndef NDEBUG
kDebug() << "We would like to update enabled operations, but are still busy so let's wait for now.";
#endif
}
}
ServiceJob* RemoteService::createJob(const QString& operation,
QMap<QString,QVariant>& parameters)
QHash<QString,QVariant>& parameters)
{
if (!m_ready) {
#ifndef NDEBUG
kDebug() << "Use of this service hasn't checked for the serviceReady signal, which it should.";
#endif
}
ServiceJob *job = new RemoteServiceJob(m_location, destination(), operation, parameters, m_token, this);
@ -252,7 +274,9 @@ ServiceJob* RemoteService::createJob(const QString& operation,
void RemoteService::slotFinished()
{
if (!m_queue.isEmpty()) {
#ifndef NDEBUG
kDebug() << "Job finished, there are still service jobs in queue, starting next in queue.";
#endif
ServiceJob *job = m_queue.dequeue();
QTimer::singleShot(0, job, SLOT(slotStart()));
}
@ -264,7 +288,9 @@ Jolie::Message RemoteService::signMessage(const Jolie::Message &message) const
Credentials identity = AuthorizationManager::self()->d->myCredentials;
if (!identity.isValid()) {
#ifndef NDEBUG
kDebug() << "We don't have our identity yet, just drop this message";
#endif
return response;
}

View File

@ -53,7 +53,7 @@ class RemoteService : public Plasma::Service
protected:
ServiceJob* createJob(const QString& operation,
QMap<QString,QVariant>& parameters);
QHash<QString,QVariant>& parameters);
void registerOperationsScheme();
private Q_SLOTS:

View File

@ -42,7 +42,7 @@ namespace Plasma
RemoteServiceJob::RemoteServiceJob(KUrl location,
const QString& destination,
const QString& operation,
QMap<QString,QVariant>& parameters,
QHash<QString,QVariant>& parameters,
QByteArray initialToken,
RemoteService* parent)
: ServiceJob(destination, operation, parameters, parent),
@ -66,7 +66,9 @@ void RemoteServiceJob::start()
if (m_service->m_busy || !m_service->m_ready) {
//enqueue and wait
m_service->m_queue.enqueue(this);
#ifndef NDEBUG
kDebug() << "already busy... enqueue, queue contains " << m_service->m_queue.count();
#endif
return;
}
@ -121,7 +123,7 @@ void RemoteServiceJob::checkValidity()
d->parameters = m_service->parametersFromDescription(*m_delayedDesc);
} else {
KConfigGroup description = m_service->operationDescription(operationName());
QMapIterator<QString, QVariant> param(parameters());
QHashIterator<QString, QVariant> param(parameters());
while (param.hasNext()) {
param.next();
if (!description.hasKey(param.key())) {
@ -145,7 +147,9 @@ void RemoteServiceJob::callCompleted(Jolie::PendingCallWatcher *watcher)
//TODO:async
if (response.fault().isValid()) {
#ifndef NDEBUG
kDebug() << "fault: " << response.fault().name();
#endif
setError(-1);
setErrorText(JolieMessage::errorMessage(response.fault().name()));
emitResult();
@ -167,7 +171,9 @@ void RemoteServiceJob::callCompleted(Jolie::PendingCallWatcher *watcher)
void RemoteServiceJob::timeout()
{
m_service->m_busy = false;
#ifndef NDEBUG
kDebug() << "Service job timed out.";
#endif
setError(-1);
setErrorText(i18n("Timeout."));
m_service->m_queue.removeAll(this);

View File

@ -44,7 +44,7 @@ class RemoteServiceJob : public Plasma::ServiceJob
RemoteServiceJob(KUrl location,
const QString& destination,
const QString& operation,
QMap<QString,QVariant>& parameters,
QHash<QString,QVariant>& parameters,
QByteArray initialToken,
RemoteService *parent);
~RemoteServiceJob();

View File

@ -24,11 +24,13 @@
#include "service.h"
#include <QGraphicsWidget>
#include <QMap>
#include <QHash>
#include <QMultiHash>
#include <QWidget>
#include <QSet>
#include <kplugininfo.h>
#include <dnssd/publicservice.h>
#include <dnssd/servicebrowser.h>
@ -45,7 +47,7 @@ class NullServiceJob : public ServiceJob
{
public:
NullServiceJob(const QString &destination, const QString &operation, QObject *parent)
: ServiceJob(destination, operation, QMap<QString, QVariant>(), parent)
: ServiceJob(destination, operation, QHash<QString, QVariant>(), parent)
{
}
@ -66,7 +68,7 @@ public:
setName("NullService");
}
ServiceJob *createJob(const QString &operation, QMap<QString, QVariant> &)
ServiceJob *createJob(const QString &operation, QHash<QString, QVariant> &)
{
return new NullServiceJob(destination(), operation, this);
}
@ -90,14 +92,12 @@ public:
delete dummyConfig;
}
void jobFinished(KJob *job);
void associatedWidgetDestroyed(QObject *obj);
void associatedGraphicsWidgetDestroyed(QObject *obj);
void publish(AnnouncementMethods methods, const QString &name,
const PackageMetadata &metadata = PackageMetadata());
const KPluginInfo &metadata = KPluginInfo());
void unpublish();

View File

@ -24,7 +24,7 @@
#include <QString>
#include <QVariant>
#include <QMap>
#include <QHash>
namespace Plasma
{
@ -35,7 +35,7 @@ public:
ServiceJobPrivate(ServiceJob *owner,
const QString &dest,
const QString &op,
const QMap<QString, QVariant> &params);
const QHash<QString, QVariant> &params);
void preventAutoStart();
void autoStart();
@ -43,7 +43,7 @@ public:
ServiceJob *q;
QString destination;
QString operation;
QMap<QString, QVariant> parameters;
QHash<QString, QVariant> parameters;
QVariant result;
Credentials identity;
bool m_allowAutoStart;

View File

@ -18,6 +18,10 @@
#include "serviceprovider_p.h"
#include <QtCore/QBuffer>
#include <QtCore/QFile>
#include <QtCore/QUuid>
#include "authorizationrule_p.h"
#include "authorizationmanager_p.h"
#include "joliemessagehelper_p.h"
@ -32,9 +36,6 @@
#include <plasma/servicejob.h>
#include <plasma/private/servicejob_p.h>
#include <QtCore/QBuffer>
#include <QtCore/QFile>
#include <QtJolie/Server>
#ifdef ENABLE_REMOTE_WIDGETS
@ -56,7 +57,9 @@ ServiceProvider::ServiceProvider(const QString &name, Service *service)
m_providerName = name;
AuthorizationManager::self()->d->server->registerAdaptor(m_providerName.toUtf8(), this);
#ifndef NDEBUG
kDebug() << "registered service provider " << m_providerName;
#endif
}
ServiceProvider::~ServiceProvider()
@ -66,7 +69,9 @@ ServiceProvider::~ServiceProvider()
void ServiceProvider::startOperationCall(Jolie::Message message)
{
#ifndef NDEBUG
kDebug() << "starting operation call";
#endif
KConfigGroup description =
m_service->operationDescription(QString(JolieMessage::field(JolieMessage::Field::OPERATION, message)));
@ -74,7 +79,9 @@ void ServiceProvider::startOperationCall(Jolie::Message message)
//deserialize the parameters
QByteArray parametersByteArray;
parametersByteArray = JolieMessage::field(JolieMessage::Field::PARAMETERS, message);
#ifndef NDEBUG
kDebug() << "parameters byte array: " << parametersByteArray.toBase64();
#endif
QBuffer buffer(&parametersByteArray);
buffer.open(QIODevice::ReadOnly);
QDataStream in(&buffer);
@ -82,10 +89,14 @@ void ServiceProvider::startOperationCall(Jolie::Message message)
in >> parameters;
if (!description.isValid()) {
#ifndef NDEBUG
kDebug() << "invalid description.";
#endif
}
#ifndef NDEBUG
kDebug() << "====PARAMETERS====";
#endif
//write the parameters into the operation description
QMap<QString, QVariant>::const_iterator it = parameters.constBegin();
@ -93,7 +104,9 @@ void ServiceProvider::startOperationCall(Jolie::Message message)
for ( ; it != itEnd; ++it) {
const QString key = it.key();
const QVariant value = it.value();
#ifndef NDEBUG
kDebug() << "key = " << key << ", value = " << value;
#endif
description.writeEntry(key, value);
}
@ -101,13 +114,17 @@ void ServiceProvider::startOperationCall(Jolie::Message message)
ServiceJob *job = m_service->startOperationCall(description);
QString identityID = JolieMessage::field(JolieMessage::Field::IDENTITYID, message);
job->d->identity = AuthorizationManager::self()->d->getCredentials(identityID);
#ifndef NDEBUG
kDebug() << "adding into messagemap:" << ((QObject*)job);
#endif
m_messageMap[job] = message;
}
void ServiceProvider::sendOperations(Jolie::Message message)
{
#ifndef NDEBUG
kDebug() << "send operations.";
#endif
//kDebug() << printJolieMessage(message);
Jolie::Message response(message.resourcePath(), message.operationName(), message.id());
@ -116,10 +133,14 @@ void ServiceProvider::sendOperations(Jolie::Message message)
".operations");
if (path.isEmpty()) {
#ifndef NDEBUG
kDebug() << "Cannot find operations description:" << m_service->name() << ".operations";
#endif
response.setFault(Jolie::Fault("NoOperationsDescription"));
} else {
#ifndef NDEBUG
kDebug() << "file = " << path;
#endif
QFile file(path);
file.open(QIODevice::ReadOnly);
Jolie::Value value;
@ -131,21 +152,29 @@ void ServiceProvider::sendOperations(Jolie::Message message)
QByteArray id = JolieMessage::field(JolieMessage::Field::IDENTITYID, message);
QByteArray uuid = JolieMessage::field(JolieMessage::Field::UUID, message);
response = appendToken(response, id, uuid);
#ifndef NDEBUG
kDebug() << "caller = " << id.toBase64();
#endif
//hack around the not yet async service adaptor api in qtjolie
if (m_descriptorMap.contains(id + uuid)) {
#ifndef NDEBUG
kDebug() << "descriptor found, sending message";
#endif
AuthorizationManager::self()->d->server->sendReply(
m_descriptorMap.value(id + uuid), response);
} else {
#ifndef NDEBUG
kDebug() << "no valid entry in descriptormap.";
#endif
}
}
void ServiceProvider::sendEnabledOperations(Jolie::Message message)
{
#ifndef NDEBUG
kDebug() << "send enabled operations.";
#endif
Jolie::Message response(message.resourcePath(), message.operationName(), message.id());
QStringList enabledOperationsList;
@ -155,7 +184,9 @@ void ServiceProvider::sendEnabledOperations(Jolie::Message message)
}
}
#ifndef NDEBUG
kDebug() << "enabled operations: " << enabledOperationsList;
#endif
QByteArray enabledOperationsArray;
QDataStream out(&enabledOperationsArray, QIODevice::WriteOnly);
@ -168,15 +199,21 @@ void ServiceProvider::sendEnabledOperations(Jolie::Message message)
QByteArray id = JolieMessage::field(JolieMessage::Field::IDENTITYID, message);
QByteArray uuid = JolieMessage::field(JolieMessage::Field::UUID, message);
response = appendToken(response, id, uuid);
#ifndef NDEBUG
kDebug() << "caller = " << id.toBase64();
#endif
//hack around the not yet async service adaptor api in qtjolie
if (m_descriptorMap.contains(id + uuid)) {
#ifndef NDEBUG
kDebug() << "descriptor found, sending message";
#endif
AuthorizationManager::self()->d->server->sendReply(
m_descriptorMap.value(id + uuid), response);
} else {
#ifndef NDEBUG
kDebug() << "no valid entry in descriptormap.";
#endif
}
}
@ -191,7 +228,9 @@ void ServiceProvider::relay(Jolie::Server *server, int descriptor,
Q_UNUSED(server)
if (message.operationName() == "startConnection") {
#ifndef NDEBUG
kDebug() << "reset token";
#endif
//add the identity
Credentials identity;
QByteArray identityByteArray = JolieMessage::field(JolieMessage::Field::IDENTITY, message);
@ -223,19 +262,27 @@ void ServiceProvider::relay(Jolie::Server *server, int descriptor,
void ServiceProvider::operationCompleted(Plasma::ServiceJob *job)
{
#ifndef NDEBUG
kDebug() << "operation completed.";
#endif
if (!m_messageMap.contains(job)) {
#ifndef NDEBUG
kDebug() << "service not in map!";
#endif
return;
}
#ifndef NDEBUG
kDebug() << "found message in message map!";
#endif
Jolie::Message message = m_messageMap.take(job);
Jolie::Message response(message.resourcePath(), message.operationName(), message.id());
QVariant variantResult = job->result();
#ifndef NDEBUG
kDebug() << "got a result: " << variantResult;
#endif
QByteArray byteArrayResult;
QBuffer buffer(&byteArrayResult);
buffer.open(QIODevice::WriteOnly);
@ -255,11 +302,15 @@ void ServiceProvider::operationCompleted(Plasma::ServiceJob *job)
//hack around the not yet async service adaptor api in qtjolie
if (m_descriptorMap.contains(id + uuid)) {
#ifndef NDEBUG
kDebug() << "descriptor found, sending message";
#endif
AuthorizationManager::self()->d->server->sendReply(
m_descriptorMap.value(id + uuid), response);
} else {
#ifndef NDEBUG
kDebug() << "no valid entry in descriptormap.";
#endif
}
}
@ -273,13 +324,17 @@ void ServiceProvider::ruleChanged(Plasma::AuthorizationRule *rule)
bool matches = rule->d->matches(message.resourcePath(), id);
if (matches && rule->policy() == AuthorizationRule::PinRequired &&
JolieMessage::field(JolieMessage::Field::PIN, message) != rule->pin()) {
#ifndef NDEBUG
kDebug() << "we need a pin";
#endif
authorizationFailed(message, JolieMessage::Error::REQUIREPIN);
m_messagesPendingAuthorization.removeAt(i);
return;
/**
} else if (matches && rule->policy() == AuthorizationRule::PinRequired) {
#ifndef NDEBUG
kDebug() << "AUTHORIZATION: Service is freely accessable for verified caller.";
#endif
rule->setPolicy(AuthorizationRule::Allow);
authorizationSuccess(message);
//TODO: it might be nicer to do a removeAll once Jolie::Message implements ==
@ -287,13 +342,17 @@ void ServiceProvider::ruleChanged(Plasma::AuthorizationRule *rule)
return;
*/
} else if (matches && rule->policy() == AuthorizationRule::Allow) {
#ifndef NDEBUG
kDebug() << "AUTHORIZATION: Service is freely accessable for verified caller.";
#endif
authorizationSuccess(message);
//TODO: it might be nicer to do a removeAll once Jolie::Message implements ==
m_messagesPendingAuthorization.removeAt(i);
return;
} else if (matches && rule->policy() == AuthorizationRule::Deny) {
#ifndef NDEBUG
kDebug() << "AUTHORIZATION: Service is never accessable for verified caller.";
#endif
authorizationFailed(message, JolieMessage::Error::ACCESSDENIED);
m_messagesPendingAuthorization.removeAt(i);
return;
@ -307,13 +366,10 @@ Jolie::Message ServiceProvider::appendToken(Jolie::Message message,
const QByteArray &caller,
const QByteArray &uuid)
{
#ifdef ENABLE_REMOTE_WIDGETS
m_tokens[caller + uuid] = QCA::Random::randomArray(256).toByteArray();
#endif
m_tokens[caller + uuid] = QUuid::createUuid().toString().toAscii();
//kDebug() << "setting token: " << m_tokens[caller + uuid].toBase64()
//<< " for caller: " << caller.toBase64()
//<< " with uuid caller: " << uuid.toBase64();
Jolie::Value data = message.data();
data.children(JolieMessage::Field::TOKEN) << Jolie::Value(m_tokens[caller + uuid]);
message.setData(data);
@ -323,31 +379,45 @@ Jolie::Message ServiceProvider::appendToken(Jolie::Message message,
void ServiceProvider::authorize(const Jolie::Message &message, const QByteArray &validToken)
{
#ifndef NDEBUG
kDebug() << "VALIDATING MESSAGE:";
#endif
//kDebug() << JolieMessage::print(message);
//Authorization step 1: is the service accessable to all callers? In that case we can skip the
//verification of the signature
#ifndef NDEBUG
kDebug() << "STEP1";
#endif
AuthorizationRule *rule =
AuthorizationManager::self()->d->matchingRule(message.resourcePath(), Credentials());
if (rule && rule->policy() == AuthorizationRule::Allow) {
#ifndef NDEBUG
kDebug() << "AUTHORIZATION: Service is freely accessable.";
#endif
authorizationSuccess(message);
return;
} else if (rule && rule->policy() == AuthorizationRule::Deny) {
#ifndef NDEBUG
kDebug() << "AUTHORIZATION: Service is never accessable.";
#endif
authorizationFailed(message, JolieMessage::Error::ACCESSDENIED);
return;
}
//Authorization step 2: see if the token matches. If it doesn't we can't safely identify the
//caller and are finished.
#ifndef NDEBUG
kDebug() << "STEP2";
#endif
if (JolieMessage::field(JolieMessage::Field::TOKEN, message) != validToken && !validToken.isEmpty()) {
#ifndef NDEBUG
kDebug() << "AUTHORIZATION: Message token doesn't match.";
#endif
#ifndef NDEBUG
kDebug() << "expected: " << validToken.toBase64();
#endif
authorizationFailed(message, JolieMessage::Error::INVALIDTOKEN);
return;
}
@ -358,25 +428,35 @@ void ServiceProvider::authorize(const Jolie::Message &message, const QByteArray
JolieMessage::field(JolieMessage::Field::IDENTITYID, message));
if (!identity.isValid()) {
#ifndef NDEBUG
kDebug() << "no identity";
#endif
authorizationFailed(message, JolieMessage::Error::INVALIDTOKEN);
return;
}
#ifndef NDEBUG
kDebug() << "STEP3";
#endif
//Authorization step 3: see if we have the key and can validate the signature. If we can't,
//either the public key has changed, or somebody is doing something nasty, and we're finished.
if ((!identity.isValidSignature(signature, payload))) {
#ifndef NDEBUG
kDebug() << "AUTHORIZATION: signature invalid.";
#endif
authorizationFailed(message, JolieMessage::Error::ACCESSDENIED);
return;
}
#ifndef NDEBUG
kDebug() << "STEP4";
#endif
//Authorization step 4: if we have a valid signature, see if we've got a matching rule
rule = AuthorizationManager::self()->d->matchingRule(message.resourcePath(), identity);
if (rule && rule->policy() == AuthorizationRule::PinRequired) {
#ifndef NDEBUG
kDebug() << "we expect a pin!";
#endif
QByteArray pin = JolieMessage::field(JolieMessage::Field::PIN, message);
if (rule->pin() == QString(pin)) {
authorizationSuccess(message);
@ -387,17 +467,25 @@ void ServiceProvider::authorize(const Jolie::Message &message, const QByteArray
delete rule;
}
} else if (rule && rule->policy() == AuthorizationRule::Allow) {
#ifndef NDEBUG
kDebug() << "AUTHORIZATION: Service is freely accessable for validated sender.";
#endif
authorizationSuccess(message);
return;
} else if (rule && rule->policy() == AuthorizationRule::Deny) {
#ifndef NDEBUG
kDebug() << "AUTHORIZATION: Service is not accessable for validated sender.";
#endif
authorizationFailed(message, JolieMessage::Error::ACCESSDENIED);
return;
} else {
//- let the shell set the rule matching this request:
#ifndef NDEBUG
kDebug() << "STEP6";
#endif
#ifndef NDEBUG
kDebug() << "leave it up to the authorization interface";
#endif
m_messagesPendingAuthorization << message;
AuthorizationRule *newRule =
new AuthorizationRule(QString(message.resourcePath()), identity.id());
@ -410,7 +498,9 @@ void ServiceProvider::authorize(const Jolie::Message &message, const QByteArray
void ServiceProvider::authorizationSuccess(const Jolie::Message &message)
{
#ifndef NDEBUG
kDebug() << "message with operationName " << message.operationName() << " allowed!";
#endif
//would be lovely if this kind of stuff could be autogenerated code from xml like in dbus
//adaptors
@ -425,7 +515,9 @@ void ServiceProvider::authorizationSuccess(const Jolie::Message &message)
void ServiceProvider::authorizationFailed(const Jolie::Message &message, const QByteArray &error)
{
#ifndef NDEBUG
kDebug() << "message with operationName " << message.operationName() << " NOT allowed!";
#endif
Jolie::Message response(message.resourcePath(), message.operationName(), message.id());
response.setFault(Jolie::Fault(error));

View File

@ -43,7 +43,7 @@
StorageJob::StorageJob(const QString& destination,
const QString& operation,
const QMap<QString, QVariant>& parameters,
const QHash<QString, QVariant>& parameters,
QObject *parent)
: ServiceJob(destination, operation, parameters, parent),
m_clientName(destination)
@ -77,7 +77,7 @@ QString StorageJob::clientName() const
void StorageJob::start()
{
//FIXME: QHASH
QMap<QString, QVariant> params = parameters();
QHash<QString, QVariant> params = parameters();
QString valueGroup = params["group"].toString();
if (valueGroup.isEmpty()) {
@ -86,13 +86,13 @@ void StorageJob::start()
QWeakPointer<StorageJob> me(this);
if (operationName() == "save") {
QMetaObject::invokeMethod(Plasma::StorageThread::self(), "save", Qt::QueuedConnection, Q_ARG(QWeakPointer<StorageJob>, me), Q_ARG(const QVariantMap&, params));
QMetaObject::invokeMethod(Plasma::StorageThread::self(), "save", Qt::QueuedConnection, Q_ARG(QWeakPointer<StorageJob>, me), Q_ARG(const QVariantHash&, params));
} else if (operationName() == "retrieve") {
QMetaObject::invokeMethod(Plasma::StorageThread::self(), "retrieve", Qt::QueuedConnection, Q_ARG(QWeakPointer<StorageJob>, me), Q_ARG(const QVariantMap&, params));
QMetaObject::invokeMethod(Plasma::StorageThread::self(), "retrieve", Qt::QueuedConnection, Q_ARG(QWeakPointer<StorageJob>, me), Q_ARG(const QVariantHash&, params));
} else if (operationName() == "delete") {
QMetaObject::invokeMethod(Plasma::StorageThread::self(), "deleteEntry", Qt::QueuedConnection, Q_ARG(QWeakPointer<StorageJob>, me), Q_ARG(const QVariantMap&, params));
QMetaObject::invokeMethod(Plasma::StorageThread::self(), "deleteEntry", Qt::QueuedConnection, Q_ARG(QWeakPointer<StorageJob>, me), Q_ARG(const QVariantHash&, params));
} else if (operationName() == "expire") {
QMetaObject::invokeMethod(Plasma::StorageThread::self(), "expire", Qt::QueuedConnection, Q_ARG(QWeakPointer<StorageJob>, me), Q_ARG(const QVariantMap&, params));
QMetaObject::invokeMethod(Plasma::StorageThread::self(), "expire", Qt::QueuedConnection, Q_ARG(QWeakPointer<StorageJob>, me), Q_ARG(const QVariantHash&, params));
} else {
setError(true);
setResult(false);
@ -109,7 +109,7 @@ void StorageJob::resultSlot(StorageJob *job, const QVariant &result)
}
}
Plasma::ServiceJob* Storage::createJob(const QString &operation, QMap<QString, QVariant> &parameters)
Plasma::ServiceJob* Storage::createJob(const QString &operation, QHash<QString, QVariant> &parameters)
{
if (m_clientName.isEmpty()) {
return 0;

View File

@ -35,7 +35,7 @@ class StorageJob : public Plasma::ServiceJob
public:
StorageJob(const QString& destination,
const QString& operation,
const QMap<QString, QVariant>& parameters,
const QHash<QString, QVariant>& parameters,
QObject *parent = 0);
~StorageJob();
void setData(const QVariantHash &data);
@ -64,7 +64,7 @@ public:
~Storage();
protected:
Plasma::ServiceJob* createJob(const QString &operation, QMap<QString, QVariant> &parameters);
Plasma::ServiceJob* createJob(const QString &operation, QHash<QString, QVariant> &parameters);
private:
QString m_clientName;

View File

@ -273,7 +273,9 @@ void ToolTip::adjustPosition(const QSize &previous, const QSize &current)
int deltaY = 0;
if (d->direction == Plasma::Up) {
/*
#ifndef NDEBUG
kDebug() << "resizing from" << current << "to" << hint
#endif
<< "and moving from" << pos() << "to"
<< x() << y() + (current.height() - hint.height())
<< current.height() - hint.height();
@ -281,7 +283,9 @@ void ToolTip::adjustPosition(const QSize &previous, const QSize &current)
deltaY = previous.height() - current.height();
} else if (d->direction == Plasma::Left) {
/*
#ifndef NDEBUG
kDebug() << "vertical resizing from" << current << "to" << hint
#endif
<< "and moving from" << pos() << "to"
<< x() + (current.width() - hint.width()) << y()
<< current.width() - hint.width(); */

View File

@ -47,8 +47,6 @@ public:
void newRenderCompleted(const WallpaperRenderRequest &render, const QImage &image);
void setupScriptSupport();
static PackageStructure::Ptr s_packageStructure;
Wallpaper *q;
KPluginInfo wallpaperDescription;
Package *package;
@ -58,7 +56,8 @@ public:
Wallpaper::ResizeMethod lastResizeMethod;
QSizeF targetSize;
WallpaperScript *script;
QList<KUrl> pendingUrls;
QList<QAction*> contextActions;
bool cacheRendering : 1;
bool initialized : 1;
bool needsConfig : 1;

View File

@ -58,7 +58,9 @@ WallpaperRenderThread::WallpaperRenderThread(const WallpaperRenderRequest &reque
WallpaperRenderThread::~WallpaperRenderThread()
{
#ifndef NDEBUG
kDebug() << "rendering done";
#endif
m_abort = true;
wait();
--s_rendererCount;
@ -102,7 +104,9 @@ void WallpaperRenderThread::checkQueue()
#else
const int numProcs = 1;
#endif
#ifndef NDEBUG
kDebug() << "checking rendering against" << s_rendererCount << numProcs;
#endif
if (s_rendererCount < numProcs) {
WallpaperRenderThread *renderThread = new WallpaperRenderThread(s_renderQueue.dequeue());
renderThread->start();
@ -111,7 +115,9 @@ void WallpaperRenderThread::checkQueue()
void WallpaperRenderThread::run()
{
#ifndef NDEBUG
kDebug() << "rendering wallpaper" << m_request.file;
#endif
QImage result(m_request.size, QImage::Format_ARGB32_Premultiplied);
result.fill(m_request.color.rgba());
@ -120,7 +126,9 @@ void WallpaperRenderThread::run()
emit done(m_request, result);
}
#ifndef NDEBUG
kDebug() << "oh, fuck it";
#endif
deleteLater();
return;
}
@ -223,7 +231,9 @@ void WallpaperRenderThread::run()
QSvgRenderer svg(m_request.file);
if (m_abort) {
deleteLater();
#ifndef NDEBUG
kDebug() << "oh, fuck it 2";
#endif
return;
}
svg.render(&p);
@ -234,7 +244,9 @@ void WallpaperRenderThread::run()
if (m_abort) {
deleteLater();
#ifndef NDEBUG
kDebug() << "oh, fuck it 3";
#endif
return;
}
@ -243,7 +255,9 @@ void WallpaperRenderThread::run()
for (int y = pos.y(); y < m_request.size.height(); y += scaledSize.height()) {
p.drawImage(QPoint(x, y), img);
if (m_abort) {
#ifndef NDEBUG
kDebug() << "oh, fuck it 4";
#endif
deleteLater();
return;
}
@ -256,7 +270,9 @@ void WallpaperRenderThread::run()
// signal we're done
if (!m_abort) {
#ifndef NDEBUG
kDebug() << "*****************************************************";
#endif
emit done(m_request, result);
}

235
private/windowshadows.cpp Normal file
View File

@ -0,0 +1,235 @@
/*
* Copyright 2011 by Aaron Seigo <aseigo@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2,
* 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 "windowshadows_p.h"
#include <QWidget>
#include <QPainter>
#ifdef Q_WS_X11
#include <QX11Info>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <fixx11h.h>
#endif
#include <kglobal.h>
namespace Plasma
{
class WindowShadows::Private
{
public:
Private(WindowShadows *shadows)
: q(shadows),
m_managePixmaps(false)
{
}
~Private()
{
clearPixmaps();
}
void clearPixmaps();
void setupPixmaps();
void initPixmap(const QString &element);
void updateShadow(const QWidget *window);
void clearShadow(const QWidget *window);
void updateShadows();
void windowDestroyed(QObject *deletedObject);
WindowShadows *q;
QList<QPixmap> m_shadowPixmaps;
QVector<unsigned long> m_data;
QSet<const QWidget *> m_windows;
bool m_managePixmaps;
};
class WindowShadowsSingleton
{
public:
WindowShadows self;
};
K_GLOBAL_STATIC(WindowShadowsSingleton, privateWindowShadowsSelf)
WindowShadows *WindowShadows::self()
{
return &privateWindowShadowsSelf->self;
}
WindowShadows::WindowShadows(QObject *parent)
: Plasma::Svg(parent),
d(new Private(this))
{
setImagePath("dialogs/background");
connect(this, SIGNAL(repaintNeeded()), this, SLOT(updateShadows()));
}
void WindowShadows::addWindow(const QWidget *window)
{
if (!window || !window->isWindow()) {
return;
}
d->m_windows << window;
d->updateShadow(window);
connect(window, SIGNAL(destroyed(QObject*)), this, SLOT(windowDestroyed(QObject*)));
}
void WindowShadows::removeWindow(const QWidget *window)
{
if (!d->m_windows.contains(window)) {
return;
}
d->m_windows.remove(window);
disconnect(window, 0, this, 0);
d->clearShadow(window);
if (d->m_windows.isEmpty()) {
d->clearPixmaps();
}
}
void WindowShadows::Private::windowDestroyed(QObject *deletedObject)
{
m_windows.remove(static_cast<QWidget *>(deletedObject));
if (m_windows.isEmpty()) {
clearPixmaps();
}
}
void WindowShadows::Private::updateShadows()
{
setupPixmaps();
foreach (const QWidget *window, m_windows) {
updateShadow(window);
}
}
void WindowShadows::Private::initPixmap(const QString &element)
{
#ifdef Q_WS_X11
QPixmap pix = q->pixmap(element);
if (pix.handle() == 0) {
Pixmap xPix = XCreatePixmap(QX11Info::display(), QX11Info::appRootWindow(), pix.width(), pix.height(), 32);
QPixmap tempPix = QPixmap::fromX11Pixmap(xPix, QPixmap::ExplicitlyShared);
tempPix.fill(Qt::transparent);
QPainter p(&tempPix);
p.drawPixmap(QPoint(0, 0), pix);
m_shadowPixmaps << tempPix;
m_managePixmaps = true;
} else {
m_shadowPixmaps << pix;
}
#endif
}
void WindowShadows::Private::setupPixmaps()
{
clearPixmaps();
initPixmap("shadow-top");
initPixmap("shadow-topright");
initPixmap("shadow-right");
initPixmap("shadow-bottomright");
initPixmap("shadow-bottom");
initPixmap("shadow-bottomleft");
initPixmap("shadow-left");
initPixmap("shadow-topleft");
#ifdef Q_WS_X11
foreach (const QPixmap &pixmap, m_shadowPixmaps) {
m_data << pixmap.handle();
}
#endif
QSize marginHint = q->elementSize("shadow-hint-top-margin");
if (marginHint.isValid()) {
m_data << marginHint.height();
} else {
m_data << m_shadowPixmaps[0].height(); // top
}
marginHint = q->elementSize("shadow-hint-right-margin");
if (marginHint.isValid()) {
m_data << marginHint.width();
} else {
m_data << m_shadowPixmaps[2].width(); // right
}
marginHint = q->elementSize("shadow-hint-bottom-margin");
if (marginHint.isValid()) {
m_data << marginHint.height();
} else {
m_data << m_shadowPixmaps[4].height(); // bottom
}
marginHint = q->elementSize("shadow-hint-left-margin");
if (marginHint.isValid()) {
m_data << marginHint.width();
} else {
m_data << m_shadowPixmaps[6].width(); // left
}
}
void WindowShadows::Private::clearPixmaps()
{
#ifdef Q_WS_X11
if (m_managePixmaps) {
foreach (const QPixmap &pixmap, m_shadowPixmaps) {
XFreePixmap(QX11Info::display(), pixmap.handle());
}
m_managePixmaps = false;
}
#endif
m_shadowPixmaps.clear();
m_data.clear();
}
void WindowShadows::Private::updateShadow(const QWidget *window)
{
#ifdef Q_WS_X11
if (m_data.isEmpty()) {
setupPixmaps();
}
Display *dpy = QX11Info::display();
Atom atom = XInternAtom(dpy, "_KDE_NET_WM_SHADOW", False);
//kDebug() << "going to set the shadow of" << winId() << "to" << data;
XChangeProperty(dpy, window->winId(), atom, XA_CARDINAL, 32, PropModeReplace,
reinterpret_cast<const unsigned char *>(m_data.constData()), m_data.size());
#endif
}
void WindowShadows::Private::clearShadow(const QWidget *window)
{
#ifdef Q_WS_X11
Display *dpy = QX11Info::display();
Atom atom = XInternAtom(dpy, "_KDE_NET_WM_SHADOW", False);
XDeleteProperty(dpy, window->winId(), atom);
#endif
}
} // namespace Plasma
#include "windowshadows_p.moc"

54
private/windowshadows_p.h Normal file
View File

@ -0,0 +1,54 @@
/*
* Copyright 2011 by Aaron Seigo <aseigo@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2,
* 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_WINDOWSHADOWS_H
#define PLASMA_WINDOWSHADOWS_H
#include <QSet>
#include <plasma/svg.h>
namespace Plasma
{
class WindowShadows : Plasma::Svg
{
Q_OBJECT
public:
static WindowShadows *self();
explicit WindowShadows(QObject *parent = 0);
void addWindow(const QWidget *window);
void removeWindow(const QWidget *window);
private Q_SLOTS:
private:
class Private;
Private * const d;
Q_PRIVATE_SLOT(d, void updateShadows())
Q_PRIVATE_SLOT(d, void windowDestroyed(QObject *deletedObject))
};
} // namespace Plasma
#endif

View File

@ -19,20 +19,22 @@
#include "accessappletjob.h"
#include "service.h"
#include "servicejob.h"
#include "applet.h"
#include <qtimer.h>
#include <kdebug.h>
#include <kdesktopfile.h>
#include <kmessagebox.h>
#include <ktempdir.h>
#include <kzip.h>
#include "config-plasma.h"
#include <kzip.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <ktempdir.h>
#include <kdesktopfile.h>
#include "applet.h"
#include "package.h"
#include <qtimer.h>
#include "pluginloader.h"
#include "private/applet_p.h"
#include "service.h"
#include "servicejob.h"
namespace Plasma
{
@ -63,7 +65,9 @@ public:
void slotPackageDownloaded(Plasma::ServiceJob *job)
{
if (job->error()) {
#ifndef NDEBUG
kDebug() << "Plasmoid Access Job triggers an error.";
#endif
q->setError(job->error());
q->setErrorText(job->errorText());
}
@ -72,11 +76,13 @@ public:
//the fetched package. Just extract the archive somewhere in a temp directory.
if (job->result().type() == QVariant::String) {
QString pluginName = job->result().toString();
#ifndef NDEBUG
kDebug() << "Server responded with a pluginname, trying to load: " << pluginName;
#endif
applet = Applet::load(pluginName);
applet = PluginLoader::self()->loadApplet(pluginName);
if (applet) {
applet->d->remoteLocation = location.prettyUrl();
applet->d->remoteLocation = location;
} else {
q->setError(-1);
q->setErrorText(i18n("The \"%1\" widget is not installed.", pluginName));
@ -84,7 +90,9 @@ public:
q->emitResult();
} else {
#ifndef NDEBUG
kDebug() << "Server responded with a plasmoid package";
#endif
//read, and extract the plasmoid package to a temporary directory
QByteArray package = job->result().toByteArray();
QDataStream stream(&package, QIODevice::ReadOnly);
@ -129,7 +137,6 @@ public:
int answer = KMessageBox::createKMessageBox(dialog, KIcon(iconName), message,
QStringList(), QString(), 0,
KMessageBox::Dangerous);
//int answer = KMessageBox::questionYesNo(0, message, i18n("Remote Widget"));
if (answer!=KDialog::Yes) {
q->setError(-1);
@ -138,17 +145,9 @@ public:
return;
}
/**
QString metadataFilename = path + "/metadata.desktop";
KDesktopFile cfg(metadataFilename);
KConfigGroup config = cfg.desktopGroup();
config.writeEntry("EngineLocation", location.prettyUrl());
config.sync();
*/
applet = Applet::loadPlasmoid(path);
if (applet) {
applet->d->remoteLocation = location.prettyUrl();
applet->d->remoteLocation = location;
} else {
q->setError(-1);
}
@ -190,7 +189,9 @@ Applet *AccessAppletJob::applet() const
void AccessAppletJob::start()
{
#ifdef ENABLE_REMOTE_WIDGETS
#ifndef NDEBUG
kDebug() << "fetching a plasmoid from location = " << d->location.prettyUrl();
#endif
Service *service = Service::access(d->location);
connect(service, SIGNAL(serviceReady(Plasma::Service*)),
this, SLOT(slotServiceReady(Plasma::Service*)));

View File

@ -21,9 +21,9 @@
#include "private/accessmanager_p.h"
#include "authorizationmanager.h"
#include "authorizationmanager_p.h"
#include "service.h"
#include "serviceaccessjob.h"
#include "private/authorizationmanager_p.h"
#include "config-plasma.h"
@ -43,6 +43,75 @@
namespace Plasma
{
class RemoteObjectDescription::Private
{
public:
QString name;
QString description;
QString icon;
KUrl url;
};
RemoteObjectDescription::RemoteObjectDescription()
: d(new Private)
{
}
RemoteObjectDescription::RemoteObjectDescription(const RemoteObjectDescription &other)
: d(new Private(*other.d))
{
}
RemoteObjectDescription &RemoteObjectDescription::operator=(const RemoteObjectDescription &other)
{
*d = *other.d;
return *this;
}
void RemoteObjectDescription::setName(const QString &name)
{
d->name = name;
}
QString RemoteObjectDescription::name() const
{
return d->name;
}
void RemoteObjectDescription::setUrl(const KUrl &url)
{
d->url = url;
}
KUrl RemoteObjectDescription::url() const
{
return d->url;
}
void RemoteObjectDescription::setDescription(const QString &description)
{
d->description = description;
}
QString RemoteObjectDescription::description() const
{
return d->description;
}
void RemoteObjectDescription::setIcon(const QString &icon)
{
d->icon = icon;
}
QString RemoteObjectDescription::icon() const
{
return d->icon;
}
class AccessManagerSingleton
{
public:
@ -75,9 +144,11 @@ AccessAppletJob *AccessManager::accessRemoteApplet(const KUrl &location) const
KUrl resolvedLocation;
if (location.protocol() == "plasma+zeroconf") {
if (d->zeroconfServices.contains(location.host())) {
resolvedLocation = d->services[location.host()].remoteLocation();
resolvedLocation = d->services[location.host()].url();
} else {
#ifndef NDEBUG
kDebug() << "There's no zeroconf service with this name.";
#endif
}
} else {
resolvedLocation = location;
@ -89,7 +160,7 @@ AccessAppletJob *AccessManager::accessRemoteApplet(const KUrl &location) const
return job;
}
QList<PackageMetadata> AccessManager::remoteApplets() const
QList<RemoteObjectDescription> AccessManager::remoteApplets() const
{
return d->services.values();
}
@ -128,40 +199,60 @@ void AccessManagerPrivate::slotJobFinished(KJob *job)
void AccessManagerPrivate::slotAddService(DNSSD::RemoteService::Ptr service)
{
#ifndef NDEBUG
kDebug();
#endif
if (!service->resolve()) {
#ifndef NDEBUG
kDebug() << "Zeroconf service can't be resolved";
#endif
return;
}
if (!services.contains(service->serviceName())) {
PackageMetadata metadata;
RemoteObjectDescription metadata;
#ifndef NDEBUG
kDebug() << "textdata = " << service->textData();
#endif
#ifndef NDEBUG
kDebug() << "hostname: " << service->hostName();
#endif
QHostAddress address = DNSSD::ServiceBrowser::resolveHostName(service->hostName());
QString ip = address.toString();
#ifndef NDEBUG
kDebug() << "result for resolve = " << ip;
#endif
KUrl url(QString("plasma://%1:%2/%3").arg(ip)
.arg(service->port())
.arg(service->serviceName()));
if (!service->textData().isEmpty()) {
if (service->textData().isEmpty()) {
#ifndef NDEBUG
kDebug() << "no textdata?";
#endif
metadata.setName(service->serviceName());
metadata.setUrl(url);
} else {
#ifndef NDEBUG
kDebug() << "service has got textdata";
#endif
QMap<QString, QByteArray> textData = service->textData();
metadata.setName(textData["name"]);
metadata.setDescription(textData["description"]);
metadata.setIcon(textData["icon"]);
metadata.setRemoteLocation(url.prettyUrl());
} else {
kDebug() << "no textdata?";
metadata.setName(service->serviceName());
metadata.setRemoteLocation(url.prettyUrl());
metadata.setUrl(url);
}
kDebug() << "location = " << metadata.remoteLocation();
#ifndef NDEBUG
kDebug() << "location = " << metadata.url();
#endif
#ifndef NDEBUG
kDebug() << "name = " << metadata.name();
#endif
#ifndef NDEBUG
kDebug() << "description = " << metadata.name();
#endif
services[service->serviceName()] = metadata;
zeroconfServices[service->serviceName()] = service;
@ -171,7 +262,9 @@ void AccessManagerPrivate::slotAddService(DNSSD::RemoteService::Ptr service)
void AccessManagerPrivate::slotRemoveService(DNSSD::RemoteService::Ptr service)
{
#ifndef NDEBUG
kDebug();
#endif
emit q->remoteAppletUnannounced(services[service->serviceName()]);
services.remove(service->serviceName());
zeroconfServices.remove(service->serviceName());

View File

@ -21,7 +21,6 @@
#define PLASMA_ACCESSMANAGER_H
#include "accessappletjob.h"
#include "packagemetadata.h"
#include "plasma_export.h"
#include <QtCore/QList>
@ -50,6 +49,29 @@ class ServiceAccessJob;
*
* @since 4.4
*/
class PLASMA_EXPORT RemoteObjectDescription
{
public:
RemoteObjectDescription();
RemoteObjectDescription(const RemoteObjectDescription &other);
RemoteObjectDescription &operator=(const RemoteObjectDescription &other);
void setName(const QString &name);
QString name() const;
void setUrl(const KUrl &url);
KUrl url() const;
void setDescription(const QString &description);
QString description() const;
void setIcon(const QString &icon);
QString icon() const;
private:
class Private;
Private *d;
};
class PLASMA_EXPORT AccessManager : public QObject
{
@ -73,10 +95,10 @@ class PLASMA_EXPORT AccessManager : public QObject
/**
* @returns a list of applets that are announced on the network through zeroconf. Use the
* remoteLocation() function in PackageMetadata to obtain an url to pass to
* url() function in RemoteObjectDescription to obtain an url to pass to
* accessRemoteApplet in AccessManager if you want to access one of these applets.
*/
QList<PackageMetadata> remoteApplets() const;
QList<RemoteObjectDescription> remoteApplets() const;
/**
* @returns a list of supported protocols of urls that can be passed to accessRemoteApplet.
@ -92,12 +114,12 @@ class PLASMA_EXPORT AccessManager : public QObject
/**
* fires when a new applet is announced on the network.
*/
void remoteAppletAnnounced(Plasma::PackageMetadata metadata);
void remoteAppletAnnounced(const Plasma::RemoteObjectDescription &metadata);
/**
* fires when an announced applet disappears from the network.
*/
void remoteAppletUnannounced(Plasma::PackageMetadata metadata);
void remoteAppletUnannounced(const Plasma::RemoteObjectDescription &metadata);
private:
AccessManager();

View File

@ -18,19 +18,19 @@
*/
#include "authorizationmanager.h"
#include "private/authorizationmanager_p.h"
#include "authorizationmanager_p.h"
#include "authorizationinterface.h"
#include "authorizationrule.h"
#include "authorizationrule_p.h"
#include "denyallauthorization_p.h"
#include "credentials.h"
#include "pinpairingauthorization_p.h"
#include "service.h"
#include "servicejob.h"
#include "trustedonlyauthorization_p.h"
#include "private/authorizationrule_p.h"
#include "private/denyallauthorization_p.h"
#include "private/joliemessagehelper_p.h"
#include "private/pinpairingauthorization_p.h"
#include "private/trustedonlyauthorization_p.h"
#include <QtCore/QBuffer>
#include <QtCore/QMap>
@ -81,7 +81,9 @@ AuthorizationManager::~AuthorizationManager()
void AuthorizationManager::setAuthorizationPolicy(AuthorizationPolicy policy)
{
if (d->locked) {
#ifndef NDEBUG
kDebug() << "Can't change AuthorizationPolicy: interface locked.";
#endif
return;
}
@ -116,7 +118,9 @@ void AuthorizationManager::setAuthorizationPolicy(AuthorizationPolicy policy)
void AuthorizationManager::setAuthorizationInterface(AuthorizationInterface *interface)
{
if (d->authorizationInterface) {
#ifndef NDEBUG
kDebug() << "Can't change AuthorizationInterface: interface locked.";
#endif
return;
}
@ -166,7 +170,9 @@ void AuthorizationManagerPrivate::prepareForServicePublication()
void AuthorizationManagerPrivate::saveRules()
{
#ifndef NDEBUG
kDebug() << "SAVE RULES";
#endif
KTemporaryFile tempFile;
tempFile.open();
@ -176,7 +182,9 @@ void AuthorizationManagerPrivate::saveRules()
int i = 0;
foreach (AuthorizationRule *rule, rules) {
if (rule->persistence() == AuthorizationRule::Persistent) {
#ifndef NDEBUG
kDebug() << "adding rule " << i;
#endif
rulesGroup.group(QString::number(i)).writeEntry("CredentialsID", rule->credentials().id());
rulesGroup.group(QString::number(i)).writeEntry("serviceName", rule->serviceName());
rulesGroup.group(QString::number(i)).writeEntry("Policy", (uint)rule->policy());
@ -188,7 +196,9 @@ void AuthorizationManagerPrivate::saveRules()
rulesGroup.sync();
tempFile.close();
#ifndef NDEBUG
kDebug() << "tempfile = " << tempFile.fileName();
#endif
KAuth::Action action("org.kde.kcontrol.kcmremotewidgets.save");
action.addArgument("source", tempFile.fileName());
@ -196,7 +206,9 @@ void AuthorizationManagerPrivate::saveRules()
KAuth::ActionReply reply = action.execute();
if (reply.failed()) {
#ifndef NDEBUG
kDebug() << "KAuth failed.... YOU SUCK!";
#endif
}
}
@ -205,13 +217,17 @@ void AuthorizationManagerPrivate::slotWalletOpened()
QByteArray identity;
if (!wallet->readEntry("Credentials", identity)) {
#ifndef NDEBUG
kDebug() << "Existing identity found";
#endif
QDataStream stream(&identity, QIODevice::ReadOnly);
stream >> myCredentials;
}
if (!myCredentials.isValid()) {
#ifndef NDEBUG
kDebug() << "Creating a new identity";
#endif
myCredentials = Credentials::createCredentials(QHostInfo::localHostName());
QDataStream stream(&identity, QIODevice::WriteOnly);
stream << myCredentials;
@ -231,7 +247,9 @@ void AuthorizationManagerPrivate::slotLoadRules()
uint persistence = rulesConfig.group(groupName).readEntry("Persistence", 0);
//Credentials storedCredentials = identities[identityID];
if (serviceName.isEmpty()) {
#ifndef NDEBUG
kDebug() << "Invalid rule";
#endif
} else {
AuthorizationRule *rule = new AuthorizationRule(serviceName, identityID);
rule->setPolicy(static_cast<AuthorizationRule::Policy>(policy));
@ -262,9 +280,13 @@ AuthorizationRule *AuthorizationManagerPrivate::matchingRule(const QString &serv
}
if (!matchingRule) {
#ifndef NDEBUG
kDebug() << "no matching rule";
#endif
} else {
#ifndef NDEBUG
kDebug() << "matching rule found: " << matchingRule->description();
#endif
}
return matchingRule;
}
@ -283,7 +305,9 @@ void AuthorizationManagerPrivate::addCredentials(const Credentials &identity)
if (identities.contains(identity.id())) {
return;
} else if (identity.isValid()) {
#ifndef NDEBUG
kDebug() << "Adding a new identity for " << identity.id();
#endif
identities[identity.id()] = identity;
}
}

View File

@ -20,9 +20,9 @@
#include "authorizationrule.h"
#include "authorizationmanager.h"
#include "authorizationmanager_p.h"
#include "authorizationrule_p.h"
#include "credentials.h"
#include "private/authorizationmanager_p.h"
#include "private/authorizationrule_p.h"
#include <QtCore/QObject>
#include <QtCore/QTimer>

View File

@ -60,7 +60,9 @@ QString ClientPinRequest::description() const
void ClientPinRequest::setPin(const QString &pin)
{
#ifndef NDEBUG
kDebug() << "pin = " << pin;
#endif
d->pin = pin;
emit changed(this);
}

View File

@ -17,10 +17,9 @@
*/
#include "credentials.h"
#include "authorizationmanager.h"
#include "config-plasma.h"
#include <QCryptographicHash>
#include <QObject>
#ifdef ENABLE_REMOTE_WIDGETS
@ -30,6 +29,8 @@
#include <kdebug.h>
#include <kstandarddirs.h>
#include "authorizationmanager.h"
#define REQUIRED_FEATURES "rsa,sha1,pkey"
namespace Plasma {
@ -112,7 +113,7 @@ Credentials Credentials::createCredentials(const QString &name)
QCA::KeyGenerator generator;
QCA::PrivateKey key = generator.createRSA(2048);
QString pemKey(key.toPublicKey().toPEM());
QString id = QCA::Hash("sha1").hashToString(pemKey.toAscii());
QString id = QCryptographicHash::hash(pemKey.toAscii(), QCryptographicHash::Sha1);
return Credentials(id, name, key.toPEM(), true);
#else
return Credentials();
@ -132,7 +133,7 @@ TrustLevel Credentials::trustLevel() const
}
*/
//Trust no one ;)
return ValidCredentials;
return UnknownTrusted;
}
bool Credentials::isValid() const
@ -146,11 +147,13 @@ bool Credentials::isValid() const
if (d->publicKey.isNull()) {
return false;
} else {
QString id = QCA::Hash("sha1").hashToString(d->publicKey.toPEM().toAscii());
QString id = QCryptographicHash::hash(d->publicKey.toPEM().toAscii(), QCryptographicHash::Sha1);
return (id == d->id);
}
#else
#ifndef NDEBUG
kDebug() << "libplasma is compiled without support for remote widgets. Key invalid.";
#endif
return false;
#endif
}
@ -175,14 +178,18 @@ bool Credentials::isValidSignature(const QByteArray &signature, const QByteArray
if (d->publicKey.canVerify()) {
if (!isValid()) {
#ifndef NDEBUG
kDebug() << "Key is null?";
#endif
}
QCA::PublicKey publicKey = QCA::PublicKey::fromPEM(d->publicKey.toPEM());
publicKey.startVerify( QCA::EMSA3_MD5 );
publicKey.update(payload);
return ( publicKey.validSignature( signature ) );
} else {
#ifndef NDEBUG
kDebug() << "Can't verify?";
#endif
return false;
}
#else
@ -208,7 +215,9 @@ QByteArray Credentials::signMessage(const QByteArray &message)
{
#ifdef ENABLE_REMOTE_WIDGETS
if(!QCA::isSupported(REQUIRED_FEATURES)) {
#ifndef NDEBUG
kDebug() << "RSA not supported";
#endif
return QByteArray();
} else if (canSign()) {
//QCA::PrivateKey privateKey = QCA::PrivateKey::fromPEM(d->privateKey.toPEM());
@ -284,7 +293,9 @@ QDataStream &operator>>(QDataStream &in, Credentials &myObj)
}
if (conversionResult != QCA::ConvertGood) {
#ifndef NDEBUG
kDebug() << "Unsuccessfull conversion of key?";
#endif
}
#endif

View File

@ -38,13 +38,17 @@ DenyAllAuthorization::~DenyAllAuthorization()
void DenyAllAuthorization::clientPinRequest(ClientPinRequest &request)
{
#ifndef NDEBUG
kDebug();
#endif
request.setPin("");
}
void DenyAllAuthorization::authorizationRequest(AuthorizationRule &rule)
{
#ifndef NDEBUG
kDebug();
#endif
rule.setPolicy(AuthorizationRule::Deny);
rule.setTargets(AuthorizationRule::AllServices | AuthorizationRule::AllUsers);
}

View File

@ -42,14 +42,18 @@ PinPairingAuthorization::~PinPairingAuthorization()
void PinPairingAuthorization::clientPinRequest(ClientPinRequest &request)
{
#ifndef NDEBUG
kDebug();
#endif
new PinPairingDialog(request);
}
void PinPairingAuthorization::authorizationRequest(AuthorizationRule &rule)
{
#ifndef NDEBUG
kDebug();
if (rule.credentials().trustLevel() > TrustedCredentials) {
#endif
if (rule.credentials().trustLevel() > UnknownTrusted) {
rule.setPolicy(AuthorizationRule::Allow);
rule.setTargets(AuthorizationRule::AllServices);
} else {

Some files were not shown because too many files have changed in this diff Show More