From 99f7264aae46f444342ae97271b600fd6ee606f8 Mon Sep 17 00:00:00 2001 From: Ivailo Monev Date: Sun, 6 Jun 2021 20:53:22 +0300 Subject: [PATCH] generic: get rid of Kross for reference: https://github.com/fluxer/katana/issues/12 Signed-off-by: Ivailo Monev --- CMakeLists.txt | 1 - cmake/modules/FindKDE4Internal.cmake | 4 - includes/CMakeLists.txt | 28 - includes/Kross/Action | 1 - includes/Kross/ActionCollection | 1 - includes/Kross/ActionCollectionEditor | 1 - includes/Kross/ActionCollectionModel | 1 - includes/Kross/ActionCollectionProxyModel | 1 - includes/Kross/ActionCollectionView | 1 - includes/Kross/ChildrenInterface | 1 - includes/Kross/ErrorInterface | 1 - includes/Kross/Interpreter | 1 - includes/Kross/InterpreterInfo | 1 - includes/Kross/Manager | 1 - includes/Kross/MetaFunction | 1 - includes/Kross/MetaType | 1 - includes/Kross/MetaTypeHandler | 1 - includes/Kross/MetaTypeImpl | 1 - includes/Kross/MetaTypeVariant | 1 - includes/Kross/MetaTypeVoidStar | 1 - includes/Kross/Object | 1 - includes/Kross/Script | 1 - includes/Kross/ScriptingPlugin | 1 - includes/Kross/WrapperInterface | 1 - kdecore/kdebug.areas | 1 - kross/CMakeLists.txt | 9 - kross/console/CMakeLists.txt | 12 - kross/console/main.cpp | 133 ---- kross/core/CMakeLists.txt | 56 -- kross/core/action.cpp | 550 --------------- kross/core/action.h | 400 ----------- kross/core/actioncollection.cpp | 462 ------------ kross/core/actioncollection.h | 248 ------- kross/core/childreninterface.h | 130 ---- kross/core/errorinterface.h | 106 --- kross/core/interpreter.cpp | 177 ----- kross/core/interpreter.h | 221 ------ kross/core/krossconfig.cpp | 40 -- kross/core/krossconfig.h | 84 --- kross/core/manager.cpp | 335 --------- kross/core/manager.h | 272 ------- kross/core/metafunction.h | 143 ---- kross/core/metatype.h | 163 ----- kross/core/object.cpp | 60 -- kross/core/object.h | 123 ---- kross/core/script.cpp | 66 -- kross/core/script.h | 112 --- kross/core/wrapperinterface.h | 95 --- kross/modules/CMakeLists.txt | 37 - kross/modules/form.cpp | 817 ---------------------- kross/modules/form.h | 699 ------------------ kross/modules/translation.cpp | 104 --- kross/modules/translation.h | 72 -- kross/qts/CMakeLists.txt | 51 -- kross/qts/interpreter.cpp | 56 -- kross/qts/interpreter.h | 71 -- kross/qts/main.cpp | 100 --- kross/qts/plugin.cpp | 76 -- kross/qts/plugin.h | 89 --- kross/qts/script.cpp | 274 -------- kross/qts/script.h | 99 --- kross/qts/test.es | 122 ---- kross/qts/values_p.h | 304 -------- kross/test/CMakeLists.txt | 10 - kross/test/main.cpp | 192 ----- kross/test/profile.py | 23 - kross/test/testguiform.py | 116 --- kross/test/testguiform.rb | 9 - kross/test/testguiform.ui | 255 ------- kross/test/testguiqt.py | 106 --- kross/test/testguiqt.rb | 16 - kross/test/testguitk.py | 32 - kross/test/testkross.js | 10 - kross/test/testkross.py | 22 - kross/test/testobject.cpp | 373 ---------- kross/test/testobject.h | 310 -------- kross/test/unittest.es | 237 ------- kross/test/unittest.js | 452 ------------ kross/test/unittest.py | 359 ---------- kross/test/unittest.rb | 448 ------------ kross/ui/CMakeLists.txt | 43 -- kross/ui/model.cpp | 541 -------------- kross/ui/model.h | 144 ---- kross/ui/plugin.cpp | 266 ------- kross/ui/plugin.h | 126 ---- kross/ui/view.cpp | 561 --------------- kross/ui/view.h | 304 -------- 87 files changed, 11978 deletions(-) delete mode 100644 includes/Kross/Action delete mode 100644 includes/Kross/ActionCollection delete mode 100644 includes/Kross/ActionCollectionEditor delete mode 100644 includes/Kross/ActionCollectionModel delete mode 100644 includes/Kross/ActionCollectionProxyModel delete mode 100644 includes/Kross/ActionCollectionView delete mode 100644 includes/Kross/ChildrenInterface delete mode 100644 includes/Kross/ErrorInterface delete mode 100644 includes/Kross/Interpreter delete mode 100644 includes/Kross/InterpreterInfo delete mode 100644 includes/Kross/Manager delete mode 100644 includes/Kross/MetaFunction delete mode 100644 includes/Kross/MetaType delete mode 100644 includes/Kross/MetaTypeHandler delete mode 100644 includes/Kross/MetaTypeImpl delete mode 100644 includes/Kross/MetaTypeVariant delete mode 100644 includes/Kross/MetaTypeVoidStar delete mode 100644 includes/Kross/Object delete mode 100644 includes/Kross/Script delete mode 100644 includes/Kross/ScriptingPlugin delete mode 100644 includes/Kross/WrapperInterface delete mode 100644 kross/CMakeLists.txt delete mode 100644 kross/console/CMakeLists.txt delete mode 100644 kross/console/main.cpp delete mode 100644 kross/core/CMakeLists.txt delete mode 100644 kross/core/action.cpp delete mode 100644 kross/core/action.h delete mode 100644 kross/core/actioncollection.cpp delete mode 100644 kross/core/actioncollection.h delete mode 100644 kross/core/childreninterface.h delete mode 100644 kross/core/errorinterface.h delete mode 100644 kross/core/interpreter.cpp delete mode 100644 kross/core/interpreter.h delete mode 100644 kross/core/krossconfig.cpp delete mode 100644 kross/core/krossconfig.h delete mode 100644 kross/core/manager.cpp delete mode 100644 kross/core/manager.h delete mode 100644 kross/core/metafunction.h delete mode 100644 kross/core/metatype.h delete mode 100644 kross/core/object.cpp delete mode 100644 kross/core/object.h delete mode 100644 kross/core/script.cpp delete mode 100644 kross/core/script.h delete mode 100644 kross/core/wrapperinterface.h delete mode 100644 kross/modules/CMakeLists.txt delete mode 100644 kross/modules/form.cpp delete mode 100644 kross/modules/form.h delete mode 100644 kross/modules/translation.cpp delete mode 100644 kross/modules/translation.h delete mode 100644 kross/qts/CMakeLists.txt delete mode 100644 kross/qts/interpreter.cpp delete mode 100644 kross/qts/interpreter.h delete mode 100644 kross/qts/main.cpp delete mode 100644 kross/qts/plugin.cpp delete mode 100644 kross/qts/plugin.h delete mode 100644 kross/qts/script.cpp delete mode 100644 kross/qts/script.h delete mode 100644 kross/qts/test.es delete mode 100644 kross/qts/values_p.h delete mode 100644 kross/test/CMakeLists.txt delete mode 100644 kross/test/main.cpp delete mode 100755 kross/test/profile.py delete mode 100644 kross/test/testguiform.py delete mode 100644 kross/test/testguiform.rb delete mode 100644 kross/test/testguiform.ui delete mode 100644 kross/test/testguiqt.py delete mode 100644 kross/test/testguiqt.rb delete mode 100644 kross/test/testguitk.py delete mode 100644 kross/test/testkross.js delete mode 100644 kross/test/testkross.py delete mode 100644 kross/test/testobject.cpp delete mode 100644 kross/test/testobject.h delete mode 100644 kross/test/unittest.es delete mode 100644 kross/test/unittest.js delete mode 100644 kross/test/unittest.py delete mode 100644 kross/test/unittest.rb delete mode 100644 kross/ui/CMakeLists.txt delete mode 100644 kross/ui/model.cpp delete mode 100644 kross/ui/model.h delete mode 100644 kross/ui/plugin.cpp delete mode 100644 kross/ui/plugin.h delete mode 100644 kross/ui/view.cpp delete mode 100644 kross/ui/view.h diff --git a/CMakeLists.txt b/CMakeLists.txt index dd835309..35d5a2dd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -369,7 +369,6 @@ add_subdirectory( kioslave ) add_subdirectory( knotify ) add_subdirectory( kparts ) add_subdirectory( kpty ) -add_subdirectory( kross ) add_subdirectory( kunitconversion ) add_subdirectory( kutils ) add_subdirectory( licenses ) diff --git a/cmake/modules/FindKDE4Internal.cmake b/cmake/modules/FindKDE4Internal.cmake index 7d92dd16..0bc43c24 100644 --- a/cmake/modules/FindKDE4Internal.cmake +++ b/cmake/modules/FindKDE4Internal.cmake @@ -58,8 +58,6 @@ # KDE4_THREADWEAVER_LIBS - the threadweaver library and all depending libraries # KDE4_SOLID_LIBS - the solid library and all depending libraries # KDE4_KNOTIFYCONFIG_LIBS - the knotify config library and all depending libraries -# KDE4_KROSSCORE_LIBS - the kross core library and all depending libraries -# KDE4_KROSSUI_LIBS - the kross ui library which includes core and all depending libraries # KDE4_KTEXTEDITOR_LIBS - the ktexteditor library and all depending libraries # KDE4_PLASMA_LIBS - the plasma library and all depending librairies # KDE4_KUNITCONVERSION_LIBS - the kunitconversion library and all depending libraries @@ -301,8 +299,6 @@ set(_kde_libraries kparts kprintutils kpty - krosscore - krossui ktexteditor kunitconversion plasma diff --git a/includes/CMakeLists.txt b/includes/CMakeLists.txt index ed770eac..48f7a571 100644 --- a/includes/CMakeLists.txt +++ b/includes/CMakeLists.txt @@ -523,34 +523,6 @@ install( ) -install( - FILES - Kross/Action - Kross/ActionCollection - Kross/ActionCollectionEditor - Kross/ActionCollectionModel - Kross/ActionCollectionProxyModel - Kross/ActionCollectionView - Kross/ChildrenInterface - Kross/ErrorInterface - Kross/Interpreter - Kross/InterpreterInfo - Kross/Manager - Kross/MetaFunction - Kross/MetaType - Kross/MetaTypeHandler - Kross/MetaTypeImpl - Kross/MetaTypeVariant - Kross/MetaTypeVoidStar - Kross/Object - Kross/Script - Kross/ScriptingPlugin - Kross/WrapperInterface - DESTINATION ${KDE4_INCLUDE_INSTALL_DIR}/KDE/Kross - COMPONENT Devel -) - - install( FILES KSettings/Dialog diff --git a/includes/Kross/Action b/includes/Kross/Action deleted file mode 100644 index a530bd1d..00000000 --- a/includes/Kross/Action +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/action.h" diff --git a/includes/Kross/ActionCollection b/includes/Kross/ActionCollection deleted file mode 100644 index 39c96588..00000000 --- a/includes/Kross/ActionCollection +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/actioncollection.h" diff --git a/includes/Kross/ActionCollectionEditor b/includes/Kross/ActionCollectionEditor deleted file mode 100644 index 421b6dd4..00000000 --- a/includes/Kross/ActionCollectionEditor +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/ui/view.h" diff --git a/includes/Kross/ActionCollectionModel b/includes/Kross/ActionCollectionModel deleted file mode 100644 index 9bcab079..00000000 --- a/includes/Kross/ActionCollectionModel +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/ui/model.h" diff --git a/includes/Kross/ActionCollectionProxyModel b/includes/Kross/ActionCollectionProxyModel deleted file mode 100644 index 421b6dd4..00000000 --- a/includes/Kross/ActionCollectionProxyModel +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/ui/view.h" diff --git a/includes/Kross/ActionCollectionView b/includes/Kross/ActionCollectionView deleted file mode 100644 index 421b6dd4..00000000 --- a/includes/Kross/ActionCollectionView +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/ui/view.h" diff --git a/includes/Kross/ChildrenInterface b/includes/Kross/ChildrenInterface deleted file mode 100644 index 11c71203..00000000 --- a/includes/Kross/ChildrenInterface +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/childreninterface.h" diff --git a/includes/Kross/ErrorInterface b/includes/Kross/ErrorInterface deleted file mode 100644 index e7a84003..00000000 --- a/includes/Kross/ErrorInterface +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/errorinterface.h" diff --git a/includes/Kross/Interpreter b/includes/Kross/Interpreter deleted file mode 100644 index 5d68c55a..00000000 --- a/includes/Kross/Interpreter +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/interpreter.h" diff --git a/includes/Kross/InterpreterInfo b/includes/Kross/InterpreterInfo deleted file mode 100644 index 5d68c55a..00000000 --- a/includes/Kross/InterpreterInfo +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/interpreter.h" diff --git a/includes/Kross/Manager b/includes/Kross/Manager deleted file mode 100644 index e57eceaf..00000000 --- a/includes/Kross/Manager +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/manager.h" diff --git a/includes/Kross/MetaFunction b/includes/Kross/MetaFunction deleted file mode 100644 index ca738940..00000000 --- a/includes/Kross/MetaFunction +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/metafunction.h" diff --git a/includes/Kross/MetaType b/includes/Kross/MetaType deleted file mode 100644 index d9b2348f..00000000 --- a/includes/Kross/MetaType +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/metatype.h" diff --git a/includes/Kross/MetaTypeHandler b/includes/Kross/MetaTypeHandler deleted file mode 100644 index d9b2348f..00000000 --- a/includes/Kross/MetaTypeHandler +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/metatype.h" diff --git a/includes/Kross/MetaTypeImpl b/includes/Kross/MetaTypeImpl deleted file mode 100644 index d9b2348f..00000000 --- a/includes/Kross/MetaTypeImpl +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/metatype.h" diff --git a/includes/Kross/MetaTypeVariant b/includes/Kross/MetaTypeVariant deleted file mode 100644 index d9b2348f..00000000 --- a/includes/Kross/MetaTypeVariant +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/metatype.h" diff --git a/includes/Kross/MetaTypeVoidStar b/includes/Kross/MetaTypeVoidStar deleted file mode 100644 index d9b2348f..00000000 --- a/includes/Kross/MetaTypeVoidStar +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/metatype.h" diff --git a/includes/Kross/Object b/includes/Kross/Object deleted file mode 100644 index ee55a1e2..00000000 --- a/includes/Kross/Object +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/object.h" diff --git a/includes/Kross/Script b/includes/Kross/Script deleted file mode 100644 index df2c6046..00000000 --- a/includes/Kross/Script +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/script.h" diff --git a/includes/Kross/ScriptingPlugin b/includes/Kross/ScriptingPlugin deleted file mode 100644 index 4a03da8d..00000000 --- a/includes/Kross/ScriptingPlugin +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/ui/plugin.h" diff --git a/includes/Kross/WrapperInterface b/includes/Kross/WrapperInterface deleted file mode 100644 index 379de524..00000000 --- a/includes/Kross/WrapperInterface +++ /dev/null @@ -1 +0,0 @@ -#include "../kross/core/wrapperinterface.h" diff --git a/kdecore/kdebug.areas b/kdecore/kdebug.areas index 27cc7bba..92ccbf1e 100644 --- a/kdecore/kdebug.areas +++ b/kdecore/kdebug.areas @@ -35,7 +35,6 @@ 297 kdeui (KNotificationRestrictions) 299 kdeui (KNotification) 399 kimgio -410 kross (kdelibs) 500 kdeprint 700 kutils (KSettings::Dialog) 701 kutils (KSettings::Dispatcher) diff --git a/kross/CMakeLists.txt b/kross/CMakeLists.txt deleted file mode 100644 index 0a2bd599..00000000 --- a/kross/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -add_subdirectory(core) -add_subdirectory(ui) -add_subdirectory(modules) -add_subdirectory(console) -add_subdirectory(qts) - -if(ENABLE_TESTING) - add_subdirectory(test) -endif() diff --git a/kross/console/CMakeLists.txt b/kross/console/CMakeLists.txt deleted file mode 100644 index a1ca2987..00000000 --- a/kross/console/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -include_directories( - ${CMAKE_SOURCE_DIR}/kross - ${KDE4_KDECORE_INCLUDES} - ${KDE4_KDEUI_INCLUDES} - ${KDE4_KIO_INCLUDES} -) - -add_executable(kross main.cpp) - -target_link_libraries(kross ${KDE4_KDEUI_LIBS} krosscore) - -install(TARGETS kross ${INSTALL_TARGETS_DEFAULT_ARGS}) diff --git a/kross/console/main.cpp b/kross/console/main.cpp deleted file mode 100644 index c18e3437..00000000 --- a/kross/console/main.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/*************************************************************************** - * main.cpp - * This file is part of the KDE project - * copyright (C)2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -// for std namespace -#include - -// Qt - -#include - -// KDE -#include -#include -#include -#include - -// Kross -#include "../core/manager.h" -#include "../core/action.h" -#include "../core/interpreter.h" - -#define ERROR_OK 0 -#define ERROR_HELP -1 -#define ERROR_NOSUCHFILE -2 -#define ERROR_OPENFAILED -3 -#define ERROR_NOINTERPRETER -4 -#define ERROR_EXCEPTION -6 - -KApplication* app = 0; - -int runScriptFile(const QString& scriptfile) -{ - // Read the scriptfile - QFile f(scriptfile); - if(! f.exists()) { - std::cerr << "No such scriptfile: " << scriptfile.toLatin1().data() << std::endl; - return ERROR_NOSUCHFILE; - } - if(! f.open(QIODevice::ReadOnly)) { - std::cerr << "Failed to open scriptfile: " << scriptfile.toLatin1().data() << std::endl; - return ERROR_OPENFAILED; - } - QByteArray scriptcode = f.readAll(); - f.close(); - - // Determinate the matching interpreter - Kross::InterpreterInfo* interpreterinfo = Kross::Manager::self().interpreterInfo( Kross::Manager::self().interpreternameForFile(scriptfile) ); - if(! interpreterinfo) { - std::cerr << "No interpreter for file: " << scriptfile.toLatin1().data() << std::endl; - return ERROR_NOINTERPRETER; - } - - // First we need a Action and fill it. - Kross::Action* action = new Kross::Action(0 /*no parent*/, KUrl(scriptfile)); - action->setInterpreter( interpreterinfo->interpreterName() ); - action->setCode(scriptcode); - - // Now execute the Action. - action->trigger(); - - if(action->hadError()) { - // We had an exception. - std::cerr << QString("%2\n%1").arg(action->errorTrace()).arg(action->errorMessage()).toLatin1().data() << std::endl; - delete action; - return ERROR_EXCEPTION; - } - - delete action; - return ERROR_OK; -} - -int main(int argc, char **argv) -{ - int result = ERROR_OK; - - KAboutData about("kross", - "kdelibs4", - ki18n("Kross"), - "0.1", - ki18n("KDE application to run Kross scripts."), - KAboutData::License_LGPL, - ki18n("(C) 2006 Sebastian Sauer"), - ki18n("Run Kross scripts."), - "http://kross.dipe.org", - "kross@dipe.org"); - about.addAuthor(ki18n("Sebastian Sauer"), ki18n("Author"), "mail@dipe.org"); - - // Initialize command line args - KCmdLineArgs::init(argc, argv, &about); - // Tell which options are supported and parse them. - KCmdLineOptions options; - options.add("+file", ki18n("Scriptfile")); - - KCmdLineArgs::addCmdLineOptions(options); - KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); - - // If no options are defined. - if(args->count() < 1) { - std::cout << "Syntax: " << KCmdLineArgs::appName().toLocal8Bit().constData() << " scriptfile1 [scriptfile2] [scriptfile3] ..." << std::endl; - return ERROR_HELP; - } - - // Create KApplication instance. - app = new KApplication(); - - // Each argument is a scriptfile to open - for(int i = 0; i < args->count(); i++) { - result = runScriptFile(args->arg(i)); - if(result != ERROR_OK) - break; - } - - // Free the KApplication instance and exit the program. - delete app; - Kross::Manager::self().deleteModules(); - return result; -} diff --git a/kross/core/CMakeLists.txt b/kross/core/CMakeLists.txt deleted file mode 100644 index 8440fe8f..00000000 --- a/kross/core/CMakeLists.txt +++ /dev/null @@ -1,56 +0,0 @@ -include_directories( - ${CMAKE_SOURCE_DIR} - ${KDE4_KDECORE_INCLUDES} - ${KDE4_KDEUI_INCLUDES} -) - -set(krosscore_LIB_SRCS - krossconfig.cpp - interpreter.cpp - script.cpp - action.cpp - actioncollection.cpp - manager.cpp - object.cpp -) - -add_library(krosscore ${LIBRARY_TYPE} ${krosscore_LIB_SRCS}) - -target_link_libraries(krosscore PUBLIC - ${KDE4_KDECORE_LIBS} - ${KDE4_KDEUI_LIBS} - ${QT_QTSCRIPT_LIBRARY} - ${QT_QTXML_LIBRARY} -) - -set_target_properties(krosscore PROPERTIES - VERSION ${GENERIC_LIB_VERSION} - SOVERSION ${GENERIC_LIB_SOVERSION} -) - -install( - TARGETS krosscore - EXPORT kdelibsLibraryTargets - ${INSTALL_TARGETS_DEFAULT_ARGS} -) - -generate_export_header(krosscore BASE_NAME KROSS) - -install( - FILES - ${CMAKE_CURRENT_BINARY_DIR}/kross_export.h - krossconfig.h - errorinterface.h - childreninterface.h - wrapperinterface.h - metatype.h - metafunction.h - interpreter.h - script.h - action.h - actioncollection.h - manager.h - object.h - DESTINATION ${KDE4_INCLUDE_INSTALL_DIR}/kross/core - COMPONENT Devel -) diff --git a/kross/core/action.cpp b/kross/core/action.cpp deleted file mode 100644 index 163bae64..00000000 --- a/kross/core/action.cpp +++ /dev/null @@ -1,550 +0,0 @@ -/*************************************************************************** - * action.cpp - * This file is part of the KDE project - * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "action.h" -#include "actioncollection.h" -#include "interpreter.h" -#include "script.h" -#include "manager.h" -#include "wrapperinterface.h" - -#include -#include - -#include -#include -#include - -using namespace Kross; - -namespace Kross { - - /// \internal d-pointer class. - class Action::Private - { - public: - - /** - * The \a Script instance the \a Action uses if initialized. It will - * be NULL as long as we didn't initialized it what will be done on - * demand. - */ - Script* script; - - /** - * The version number this \a Action has. Those version number got - * used internaly to deal with different releases of scripts. - */ - int version; - - /** - * The optional description to provide some more details about the - * Action to the user. - */ - QString description; - - /** - * The name of the icon. - */ - QString iconname; - - /** - * The scripting code. - */ - QByteArray code; - - /** - * The name of the interpreter. This could be something - * like for example "python" for the python binding. - */ - QString interpretername; - - /** - * The name of the scriptfile that should be executed. Those - * scriptfile will be readed and the content will be used to - * set the scripting code and, if not defined, the used - * interpreter. - */ - QString scriptfile; - - /** - * The path list where the \a Script may be located. - * \todo after BIC break: don't keep it all the time, - * as it is now passed to [to|from]DomElement - */ - QStringList searchpath; - - /** - * Map of options that overwritte the \a InterpreterInfo::Option::Map - * standard options. - */ - QMap< QString, QVariant > options; - - Private() : script(0), version(0) {} - }; - -} - -enum InitOptions{Enable=1}; -void static init(Action* th, const QString& name, int options=0) -{ - th->setEnabled(options&Enable); - th->setObjectName(name); - #ifdef KROSS_ACTION_DEBUG - krossdebug( QString("Action::Action(QObject*,QString,QDir) Ctor name='%1'").arg(th->objectName()) ); - #endif - QObject::connect(th, SIGNAL(triggered(bool)), th, SLOT(slotTriggered())); -} - -Action::Action(QObject* parent, const QString& name, const QDir& packagepath) - : QAction(parent) - , QScriptable() - , ChildrenInterface() - , ErrorInterface() - , d( new Private() ) -{ - init(this,name); - d->searchpath=QStringList(packagepath.absolutePath()); -} - -Action::Action(QObject* parent, const QUrl& url) - : QAction(parent) - , ChildrenInterface() - , ErrorInterface() - , d( new Private() ) -{ - init(this,url.path(),Enable); - QFileInfo fi( url.toLocalFile() ); - setText( fi.fileName() ); - setIconName( KMimeType::iconNameForUrl(url) ); - setFile( url.toLocalFile() ); -} - -Action::~Action() -{ - #ifdef KROSS_ACTION_DEBUG - krossdebug( QString("Action::~Action() Dtor name='%1'").arg(objectName()) ); - #endif - finalize(); - ActionCollection *coll = qobject_cast(parent()); - if ( coll ) { - coll->removeAction(this); - } - delete d; -} - - -void Action::fromDomElement(const QDomElement& element) -{ - fromDomElement(element, d->searchpath); -} - -void Action::fromDomElement(const QDomElement& element, const QStringList& searchPath) -{ - if( element.isNull() ) - return; - - QString file = element.attribute("file"); - if( ! file.isEmpty() ) { - if( QFileInfo(file).exists() ) { - setFile(file); - } - else { - foreach (const QString& packagepath, searchPath) { - QFileInfo fi(QDir(packagepath), file); - if( fi.exists() ) { - setFile( fi.absoluteFilePath() ); - break; - } - } - } - } - - d->version = QVariant( element.attribute("version",QString(d->version)) ).toInt(); - - setText( i18n( element.attribute("text").toUtf8() ) ); - setDescription( i18n( element.attribute("comment").toUtf8() ) ); - setEnabled( true ); - setInterpreter( element.attribute("interpreter") ); - setEnabled( QVariant(element.attribute("enabled","true")).toBool() && isEnabled() ); - - QString icon = element.attribute("icon"); - if( icon.isEmpty() && ! d->scriptfile.isNull() ) - icon = KMimeType::iconNameForUrl( KUrl(d->scriptfile) ); - setIconName( icon ); - - const QString code = element.attribute("code"); - if( ! code.isNull() ) - setCode(code.toUtf8()); - - for(QDomNode node = element.firstChild(); ! node.isNull(); node = node.nextSibling()) { - QDomElement e = node.toElement(); - if( ! e.isNull() ) { - if( e.tagName() == "property" ) { - const QString n = e.attribute("name", QString()); - if( ! n.isNull() ) { - #ifdef KROSS_ACTION_DEBUG - krossdebug(QString("Action::readDomElement: Setting property name=%1 value=%2").arg(n).arg(e.text())); - #endif - setProperty(n.toLatin1().constData(), QVariant(e.text())); - } - } - } - } -} - -QDomElement Action::toDomElement() const -{ - return toDomElement(QStringList()); -} - -QDomElement Action::toDomElement(const QStringList& searchPath) const -{ - QDomDocument doc; - QDomElement e = doc.createElement("script"); - e.setAttribute("name", objectName()); - if( d->version > 0 ) - e.setAttribute("version", QString(d->version)); - if( ! text().isNull() ) - e.setAttribute("text", text()); - if( ! description().isNull() ) - e.setAttribute("comment", description()); - if( ! iconName().isNull() ) - e.setAttribute("icon", iconName()); - if( ! isEnabled() ) - e.setAttribute("enabled", "false"); - if( ! interpreter().isNull() ) - e.setAttribute("interpreter", interpreter()); - - - QString fileName=file(); - if (!searchPath.isEmpty()) { - //fileName=QDir(searchPath.first()).relativeFilePath(fileName); //prefer absname if it is short? - foreach(const QString& packagepath, searchPath) { - QString nfn=QDir(packagepath).relativeFilePath(file()); - if (nfn.length() props=dynamicPropertyNames(); - foreach(const QByteArray& prop, props) { - QDomElement p = doc.createElement("property"); - p.setAttribute("name", QString::fromLatin1(prop)); - p.appendChild(doc.createTextNode(property(prop.constData()).toString())); - e.appendChild(p); - } - /* - else if( ! code().isNull() ) { - e.setAttribute("code", code()); - } - */ - - return e; -} - -Kross::Script* Action::script() const -{ - return d->script; -} - -QString Action::name() const -{ - return objectName(); -} - -int Action::version() const -{ - return d->version; -} - -QString Action::description() const -{ - return d->description; -} - -void Action::setDescription(const QString& description) -{ - d->description = description; - emit dataChanged(this); - emit updated(); -} - -QString Action::iconName() const -{ - return d->iconname; -} - -void Action::setIconName(const QString& iconname) -{ - setIcon( KIcon(iconname) ); - d->iconname = iconname; - emit dataChanged(this); - emit updated(); -} - -bool Action::isEnabled() const -{ - return QAction::isEnabled(); -} - -void Action::setEnabled(bool enabled) -{ - QAction::setEnabled(enabled); - emit dataChanged(this); - emit updated(); -} - -QByteArray Action::code() const -{ - return d->code; -} - -void Action::setCode(const QByteArray& code) -{ - if( d->code != code ) { - finalize(); - d->code = code; - emit dataChanged(this); - emit updated(); - } -} - -QString Action::interpreter() const -{ - return d->interpretername; -} - -void Action::setInterpreter(const QString& interpretername) -{ - if( d->interpretername != interpretername ) { - finalize(); - d->interpretername = interpretername; - setEnabled( Manager::self().interpreters().contains(interpretername) ); - if (!isEnabled()) - krosswarning("Action::setInterpreter: interpreter not found: "+interpretername); - emit dataChanged(this); - emit updated(); - } -} - -QString Action::file() const -{ - return d->scriptfile; -} - -bool Action::setFile(const QString& scriptfile) -{ - if( d->scriptfile != scriptfile ) { - finalize(); - if ( scriptfile.isNull() ) { - if( ! d->scriptfile.isNull() ) - d->interpretername.clear(); - d->scriptfile.clear(); - d->searchpath.clear(); - } - else { - d->scriptfile = scriptfile; - d->interpretername = Manager::self().interpreternameForFile(scriptfile); - if( d->interpretername.isNull() ) - return false; - } - } - return true; -} - -QString Action::currentPath() const -{ - return file().isEmpty()?QString():QFileInfo(file()).absolutePath();//obey Qt docs and don't cheat -} - -QVariantMap Action::options() const -{ - return d->options; -} - -void Action::addQObject(QObject* obj, const QString &name) -{ - this->addObject(obj, name); -} - -QObject* Action::qobject(const QString &name) const -{ - return this->object(name); -} - -QStringList Action::qobjectNames() const -{ - return this->objects().keys(); -} - -QVariant Action::option(const QString& name, const QVariant& defaultvalue) -{ - if(d->options.contains(name)) - return d->options[name]; - InterpreterInfo* info = Manager::self().interpreterInfo( d->interpretername ); - return info ? info->optionValue(name, defaultvalue) : defaultvalue; -} - -bool Action::setOption(const QString& name, const QVariant& value) -{ - InterpreterInfo* info = Manager::self().interpreterInfo( d->interpretername ); - if(info) { - if(info->hasOption(name)) { - d->options.insert(name, value); - return true; - } else krosswarning( QString("Kross::Action::setOption(%1, %2): No such option").arg(name).arg(value.toString()) ); - } else krosswarning( QString("Kross::Action::setOption(%1, %2): No such interpreterinfo").arg(name).arg(value.toString()) ); - return false; -} - -QStringList Action::functionNames() -{ - if(! d->script) { - if(! initialize()) - return QStringList(); - } - return d->script->functionNames(); -} - -QVariant Action::callFunction(const QString& name, const QVariantList& args) -{ - if(! d->script) { - if(! initialize()) - return QVariant(); - } - return d->script->callFunction(name, args); -} - -QVariant Action::evaluate(const QByteArray& code) -{ - if(! d->script) { - if(! initialize()) - return QVariant(); - } - return d->script->evaluate(code); -} - -bool Action::initialize() -{ - finalize(); - - if( ! d->scriptfile.isNull() ) { - QFile f( d->scriptfile ); - if( ! f.exists() ) { - setError(i18n("Scriptfile \"%1\" does not exist.", d->scriptfile)); - return false; - } - if( d->interpretername.isNull() ) { - setError(i18n("Failed to determine interpreter for scriptfile \"%1\"", d->scriptfile)); - return false; - } - if( ! f.open(QIODevice::ReadOnly) ) { - setError(i18n("Failed to open scriptfile \"%1\"", d->scriptfile)); - return false; - } - d->code = f.readAll(); - f.close(); - } - - Interpreter* interpreter = Manager::self().interpreter(d->interpretername); - if( ! interpreter ) { - InterpreterInfo* info = Manager::self().interpreterInfo(d->interpretername); - if( info ) - setError(i18n("Failed to load interpreter \"%1\"", d->interpretername)); - else - setError(i18n("No such interpreter \"%1\"", d->interpretername)); - return false; - } - - d->script = interpreter->createScript(this); - if( ! d->script ) { - setError(i18n("Failed to create script for interpreter \"%1\"", d->interpretername)); - return false; - } - - if( d->script->hadError() ) { - setError(d->script); - finalize(); - return false; - } - - clearError(); // clear old exception - return true; -} - -void Action::finalize() -{ - if( d->script ) - emit finalized(this); - delete d->script; - d->script = 0; -} - -bool Action::isFinalized() const -{ - return d->script == 0; -} - -void Action::slotTriggered() -{ - #ifdef KROSS_ACTION_DEBUG - krossdebug( QString("Action::slotTriggered() name=%1").arg(objectName()) ); - #endif - - emit started(this); - - if( ! d->script ) { - if( ! initialize() ) - Q_ASSERT( hadError() ); - } - - if( hadError() ) { - #ifdef KROSS_ACTION_DEBUG - krossdebug( QString("Action::slotTriggered() on init, errorMessage=%2").arg(errorMessage()) ); - #endif - } - else { - d->script->execute(); - if( d->script->hadError() ) { - #ifdef KROSS_ACTION_DEBUG - krossdebug( QString("Action::slotTriggered() after exec, errorMessage=%2").arg(errorMessage()) ); - #endif - setError(d->script); - //emit finished(this); - finalize(); - //return; - } - } - - emit finished(this); -} - -// -------- - -// interface files -WrapperInterface::~WrapperInterface() -{ -} - -#include "moc_action.cpp" diff --git a/kross/core/action.h b/kross/core/action.h deleted file mode 100644 index 0f5d73fc..00000000 --- a/kross/core/action.h +++ /dev/null @@ -1,400 +0,0 @@ -/*************************************************************************** - * action.h - * This file is part of the KDE project - * copyright (C)2004-2007 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_ACTION_H -#define KROSS_ACTION_H - -#include -#include -#include -#include -#include -#include -#include - -#include "errorinterface.h" -#include "childreninterface.h" - -namespace Kross { - - class Script; - - /** - * The Action class is an abstract container to deal with scripts - * like a single standalone script file. Each action holds a reference - * to the matching @a Kross::Interpreter created @a Kross::Script - * instance. - * - * The \a Manager takes care of handling the \a Action instances - * application by providing access to \a ActionCollection containers - * for those \a Action instances. - * - * Once you've such a Action instance you're able to perform actions - * with it like executing scripting code. - * - * Following sample shows "Hello World." executed with the python - * interpreter: - * \code - * # Create a new Kross::Action instance. - * Kross::Action* action = new Kross::Action(0,"MyFirstScript"); - * # Set the interpreter we like to use. This could be e.g. "python", "ruby" or "kjs". - * action->setInterpreter("python"); - * # Set the scripting code. - * action->setCode("print \"Hello World.\""); - * # Execute the scripting code. - * action->trigger(); - * \endcode - * - * Following sample demonstrates how to execute an external python script - * file. The script file itself is named "mytest.py" and contains: - * \code - * # this function got called from within C++ - * def myfunction(args): - * print "Arguments are: %s" % args - * # Import the published QObject's - * import MyFirstQObject, MySecondQObject - * # Call a slot MyFirstQObject provides. - * MyFirstQObject.someSlot("Some string") - * # Set a property MySecondQObject provides. - * MySecondQObject.someProperty = "Other string" - * \endcode - * Then you are able to load the script file, publish QObject instances - * and let the script do whatever it likes to do: - * \code - * # Publish a QObject instance for all Kross::Action instances. - * Kross::Manager::self().addObject(myqobject1, "MyFirstQObject") - * # Create a new Kross::Action instance. - * Kross::Action* action = new Kross::Action(0,"MySecondScript"); - * # Publish a QObject instance only for the Kross::Action instance. - * action->addObject(myqobject2, "MySecondQObject"); - * # Set the script file we like to execute. - * action->setFile("/home/myuser/mytest.py"); - * # Execute the script file. - * action->trigger(); - * # Call the "myfunction" defined in the "mytest.py" python script. - * QVariant result = action->callFunction("myfunction", QVariantList()<<"Arg"); - * \endcode - */ - class KROSS_EXPORT Action - : public QAction - , public QScriptable - , public ChildrenInterface - , public ErrorInterface - { - Q_OBJECT - - public: - - /** - * Constructor. - * - * \param parent The parent QObject this \a Action is a child of. - * \param name The unique name this Action has. It's used - * e.g. at the \a Manager to identify the Action. The - * name is accessible via \a QObject::objectName . - * \deprecated since 4.3: pass search path to fromDomElement() and toDomElement() - */ - Action(QObject* parent, const QString& name, const QDir& packagepath = QDir()); //BIC may be removed in favour of the next c'tor - - /** - * Constructor. - * - * \param parent The parent QObject this \a Action is a child of. - * \param url The URL should point to a valid scripting file. - * This \a Action will be filled with the content of the - * file (e.g. the file is read and \a code should return - * its content and it's also tried to determine the - * \a interpreter ). Remember to use QUrl c'tor explicitly. - * The name will be set to url.path() - */ - Action(QObject* parent, const QUrl& url); - - /** - * Destructor. - */ - virtual ~Action(); - - /** - * Method to read settings from the QDomElement \p element that - * contains details about e.g. the displayed text, the file to - * execute or the used interpreter. - * \todo BIC merge - */ - void fromDomElement(const QDomElement& element); - - /** - * Method to read settings from the QDomElement \p element that - * contains details about e.g. the displayed text, the file to - * execute or the used interpreter. - * - * \param searchPath List of directories where to search the script if its path is relative - * First item is given the highest priority. - */ - void fromDomElement(const QDomElement& element, const QStringList& searchPath/* = QStringList()*/); - - /** - * \return a QDomElement that contains the settings like e.g. the - * displayed text, the file to execute or the used interpreter - * of this \a Action instance. - */ - QDomElement toDomElement() const; - - /** - * \return a QDomElement that contains the settings like e.g. the - * displayed text, the file to execute or the used interpreter - * of this \a Action instance. - * \param searchPath if given, find the closest directory containing the scriptfile - * and write relative filepath - */ - QDomElement toDomElement(const QStringList& searchPath/* = QStringList()*/) const; - - /** - * Initialize the \a Script instance. - * - * Normally there is no need to call this function directly because - * if will be called internally if needed (e.g. on \a execute ). - * - * \return true if the initialization was successful else - * false is returned. - */ - bool initialize(); - - /** - * Finalize the \a Script instance and frees any cached or still - * running executions. Normally there is no need to call this - * function directly because the \a Action will take care - * of calling it if needed. - */ - void finalize(); - - /** - * \return true if the action is finalized, which means the - * action is currently not running. - */ - bool isFinalized() const; - - /** - * \return the \a Kross::Script implementation used by the scripting - * backend. This returns NULL until the action got triggered or if - * there was an error before that. - * - * Normaly it shouldn't be necessary to deal with the scripting backend - * depending instance of a \a Kross::Script implementation since this - * \a Action class already decorates all the things needed. It - * may however be useful to provide additional interpreter dependent - * functionality. - */ - Script* script() const; - - public Q_SLOTS: - - /** - * \return the objectName for this Action. - */ - QString name() const; - - /** - * \return the version number this Action has. - * Per default 0 is returned. - */ - int version() const; - - /** - * \return the optional description for this Action. - */ - QString description() const; - - /** - * Set the optional description for this Action. - */ - void setDescription(const QString& description); - - /** - * Return the name of the icon. - */ - QString iconName() const; - - /** - * Set the name of the icon to \p iconname . - */ - void setIconName(const QString& iconname); - - /** - * Return true if this Action is enabled else false is returned. - */ - bool isEnabled() const; - - /** - * Set the enable state of this Action to \p enabled . - */ - void setEnabled(bool enabled); - - /** - * \return the script file that should be executed. - */ - QString file() const; - - /** - * Set the script file that should be executed. - */ - bool setFile(const QString& scriptfile); - - /** - * \return the scriptcode this Action holds. - */ - QByteArray code() const; - - /** - * Set the scriptcode \p code this Action should execute. - */ - void setCode(const QByteArray& code); - - /** - * \return the name of the interpreter. Could be for - * example "python" or "ruby". - */ - QString interpreter() const; - - /** - * Set the name of the interpreter (javascript, python or ruby). - */ - void setInterpreter(const QString& interpretername); - - /** - * \return the current path the script is running in or - * an empty string if there is no current path defined. - */ - QString currentPath() const; - - /** - * Add a QObject instance to the action. This instance will - * be published to scripts. - */ - void addQObject(QObject* obj, const QString &name = QString()); - - /** - * \return the QObject with the object name \p name . - */ - QObject* qobject(const QString &name) const; - - /** - * \return a list of QObject object names. - */ - QStringList qobjectNames() const; - - /** - * \return a map of options this \a Action defines. - * The options are returned call-by-ref, so you are able to - * manipulate them. - */ - QVariantMap options() const; - - /** - * \return the value of the option defined with \p name . - * If there doesn't exist an option with such a name, - * the \p defaultvalue is returned. - */ - QVariant option(const QString& name, const QVariant& defaultvalue = QVariant()); - - /** - * Set the \a Interpreter::Option value. - */ - bool setOption(const QString& name, const QVariant& value); - - /** - * \return the list of functionnames. - */ - QStringList functionNames(); - - /** - * Call a function in the script. - * - * \param name The name of the function which should be called. - * \param args The optional list of arguments. - */ - QVariant callFunction(const QString& name, const QVariantList& args = QVariantList()); - - /** - * Evaluate some scripting code. - * - * Example how this can be used: - * \code - * Kross::Action* a = new Kross::Action(0, "MyScript"); - * a->setInterpreter("python"); - * a->setCode("def myFunc(x): return x"); - * a->trigger(); - * int three = a->evaluate("1+2").toInt(); // returns 3 - * int nine = a->evaluate("myFunc(9)").toInt(); // returns 9 - * \endcode - * - * \param code The scripting code to evaluate. - * \return The return value of the evaluation. - */ - QVariant evaluate(const QByteArray& code); - - Q_SIGNALS: - - /** - * This signal is emitted if the content of the Action - * was changed. The \a ActionCollection instances this Action - * is a child of are connected with this signal to fire up - * their own updated signal if an Action of them was updated. - */ - void updated(); - - /// This signal is emitted when the data of the Action is changed - void dataChanged(Action*); - - /** - * This signal is emitted before the script got executed. - */ - void started(Kross::Action*); - - /** - * This signal is emitted after the script got executed. - */ - void finished(Kross::Action*); - - /** - * This signal is emitted once a script finalized. - */ - void finalized(Kross::Action*); - - private Q_SLOTS: - - /** - * This private slot is connected with the \a QAction::triggered - * signal. To execute the script just emit that signal and this - * slot tries to execute the script. - */ - void slotTriggered(); - - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; - -} - -Q_DECLARE_METATYPE(Kross::Action*) - -#endif - diff --git a/kross/core/actioncollection.cpp b/kross/core/actioncollection.cpp deleted file mode 100644 index a66901b0..00000000 --- a/kross/core/actioncollection.cpp +++ /dev/null @@ -1,462 +0,0 @@ -/*************************************************************************** - * actioncollection.cpp - * This file is part of the KDE project - * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "actioncollection.h" -#include "action.h" -#include "manager.h" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -using namespace Kross; - -namespace Kross { - - /// \internal d-pointer class. - class ActionCollection::Private - { - public: - QPointer parent; - QHash< QString, QPointer > collections; - QStringList collectionnames; - - QList< Action* > actionList; - QHash< QString, Action* > actionMap; - - QString text; - QString description; - QString iconname; - bool enabled; - bool blockupdated; - - Private(ActionCollection* const p) : parent(p) {} - }; - -} - -ActionCollection::ActionCollection(const QString& name, ActionCollection* parent) - : QObject(0) - , d( new Private(0) ) -{ - setObjectName(name); - d->text = name; - d->enabled = true; - d->blockupdated = false; - - setParentCollection(parent); -} - -ActionCollection::~ActionCollection() -{ - if ( d->parent ) { - emit d->parent->collectionToBeRemoved(this, d->parent); - d->parent->unregisterCollection( objectName() ); - emit d->parent->collectionRemoved( this, d->parent ); - } - delete d; -} - -QString ActionCollection::name() const { return objectName(); } - -QString ActionCollection::text() const { return d->text; } -void ActionCollection::setText(const QString& text) { d->text = text; emit dataChanged(this); emitUpdated(); } - -QString ActionCollection::description() const { return d->description; } -void ActionCollection::setDescription(const QString& description) { d->description = description; emit dataChanged(this); emitUpdated(); } - -QString ActionCollection::iconName() const { return d->iconname; } -void ActionCollection::setIconName(const QString& iconname) { d->iconname = iconname; emit dataChanged(this); } -QIcon ActionCollection::icon() const { return KIcon(d->iconname); } - -bool ActionCollection::isEnabled() const { return d->enabled; } -void ActionCollection::setEnabled(bool enabled) { d->enabled = enabled; emit dataChanged(this); emitUpdated(); } - -ActionCollection* ActionCollection::parentCollection() const -{ - return d->parent; -} - -void ActionCollection::setParentCollection( ActionCollection *parent ) -{ - if ( d->parent ) { - emit d->parent->collectionToBeRemoved(this, d->parent); - d->parent->unregisterCollection( objectName() ); - setParent( 0 ); - emit d->parent->collectionRemoved( this, d->parent ); - d->parent = 0; - } - setParent(0); - if ( parent ) { - emit parent->collectionToBeInserted(this, parent); - setParent( parent ); - d->parent = parent; - parent->registerCollection( this ); - emit parent->collectionInserted( this, parent ); - } - emitUpdated(); -} - -bool ActionCollection::hasCollection(const QString& name) const -{ - return d->collections.contains(name); -} - -ActionCollection* ActionCollection::collection(const QString& name) const -{ - return d->collections.contains(name) ? d->collections[name] : QPointer(0); -} - -QStringList ActionCollection::collections() const -{ - return d->collectionnames; -} - -void ActionCollection::registerCollection(ActionCollection* collection) -{ - Q_ASSERT(collection); - const QString name = collection->objectName(); - //Q_ASSERT( !name.isNull() ); - if (!d->collections.contains(name)) - { - d->collections.insert(name, collection); - d->collectionnames.append(name); - } - connectSignals(collection, true); - emitUpdated(); -} - -void ActionCollection::unregisterCollection(const QString& name) -{ - if( ! d->collections.contains(name) ) - return; - ActionCollection* collection = d->collections[name]; - d->collectionnames.removeAll(name); - d->collections.remove(name); - connectSignals(collection, false); - emitUpdated(); -} - -QList ActionCollection::actions() const -{ - return d->actionList; -} - -Action* ActionCollection::action(const QString& name) const -{ - return d->actionMap.contains(name) ? d->actionMap[name] : 0; -} - -void ActionCollection::addAction(Action* action) -{ - Q_ASSERT( action && ! action->objectName().isEmpty() ); - addAction(action->objectName(), action); -} - -void ActionCollection::addAction(const QString& name, Action* action) -{ - Q_ASSERT( action && ! name.isEmpty() ); - emit actionToBeInserted(action, this); - if( d->actionMap.contains(name) ) - d->actionList.removeAll( d->actionMap[name] ); - d->actionMap.insert(name, action); - d->actionList.append(action); - action->setParent(this); // in case it is not set - connectSignals(action, true); - emit actionInserted(action, this); - emitUpdated(); -} - -void ActionCollection::removeAction(const QString& name) -{ - if( ! d->actionMap.contains(name) ) - return; - Action* action = d->actionMap[name]; - connectSignals(action, false); - emit actionToBeRemoved(action, this); - d->actionList.removeAll(action); - d->actionMap.remove(name); - //krossdebug( QString("ActionCollection::removeAction: %1 %2").arg(action->name()).arg(action->parent()->objectName()) ); - action->setParent( 0 ); - emit actionRemoved(action, this); - emitUpdated(); -} - -void ActionCollection::removeAction(Action* action) -{ - Q_ASSERT( action && ! action->objectName().isEmpty() ); - if( ! d->actionMap.contains(action->objectName()) ) { - Q_ASSERT( ! d->actionList.contains(action) ); - return; - } - removeAction( action->objectName() ); -} - -void ActionCollection::connectSignals(Action *action, bool conn) -{ - if ( conn ) { - connect(action, SIGNAL(dataChanged(Action*)), this, SIGNAL(dataChanged(Action*))); - connect(action, SIGNAL(updated()), this, SLOT(emitUpdated())); - } else { - disconnect(action, SIGNAL(dataChanged(Action*)), this, SIGNAL(dataChanged(Action*))); - disconnect(action, SIGNAL(updated()), this, SLOT(emitUpdated())); - } -} - -void ActionCollection::connectSignals(ActionCollection *collection, bool conn) -{ - if ( conn ) { - connect(collection, SIGNAL(dataChanged(Action*)), this, SIGNAL(dataChanged(Action*))); - connect(collection, SIGNAL(dataChanged(ActionCollection*)), this, SIGNAL(dataChanged(ActionCollection*))); - - connect(collection, SIGNAL(collectionToBeInserted(ActionCollection*,ActionCollection*)), this, SIGNAL(collectionToBeInserted(ActionCollection*,ActionCollection*))); - connect(collection, SIGNAL(collectionInserted(ActionCollection*,ActionCollection*)), this, SIGNAL(collectionInserted(ActionCollection*,ActionCollection*))); - connect(collection, SIGNAL(collectionToBeRemoved(ActionCollection*,ActionCollection*)), this, SIGNAL(collectionToBeRemoved(ActionCollection*,ActionCollection*))); - connect(collection, SIGNAL(collectionRemoved(ActionCollection*,ActionCollection*)), this, SIGNAL(collectionRemoved(ActionCollection*,ActionCollection*))); - - connect(collection, SIGNAL(actionToBeInserted(Action*,ActionCollection*)), this, SIGNAL(actionToBeInserted(Action*,ActionCollection*))); - connect(collection, SIGNAL(actionInserted(Action*,ActionCollection*)), this, SIGNAL(actionInserted(Action*,ActionCollection*))); - connect(collection, SIGNAL(actionToBeRemoved(Action*,ActionCollection*)), this, SIGNAL(actionToBeRemoved(Action*,ActionCollection*))); - connect(collection, SIGNAL(actionRemoved(Action*,ActionCollection*)), this, SIGNAL(actionRemoved(Action*,ActionCollection*))); - connect(collection, SIGNAL(updated()), this, SLOT(emitUpdated())); - } else { - disconnect(collection, SIGNAL(dataChanged(ActionCollection*)), this, SIGNAL(dataChanged(ActionCollection*))); - - disconnect(collection, SIGNAL(collectionToBeInserted(ActionCollection*,ActionCollection*)), this, SIGNAL(collectionToBeInserted(ActionCollection*,ActionCollection*))); - disconnect(collection, SIGNAL(collectionInserted(ActionCollection*,ActionCollection*)), this, SIGNAL(collectionInserted(ActionCollection*,ActionCollection*))); - disconnect(collection, SIGNAL(collectionToBeRemoved(ActionCollection*,ActionCollection*)), this, SIGNAL(collectionToBeRemoved(ActionCollection*,ActionCollection*))); - disconnect(collection, SIGNAL(collectionRemoved(ActionCollection*,ActionCollection*)), this, SIGNAL(collectionRemoved(ActionCollection*,ActionCollection*))); - - disconnect(collection, SIGNAL(actionToBeInserted(Action*,ActionCollection*)), this, SIGNAL(actionToBeInserted(Action*,ActionCollection*))); - disconnect(collection, SIGNAL(actionInserted(Action*,ActionCollection*)), this, SIGNAL(actionInserted(Action*,ActionCollection*))); - disconnect(collection, SIGNAL(actionToBeRemoved(Action*,ActionCollection*)), this, SIGNAL(actionToBeRemoved(Action*,ActionCollection*))); - disconnect(collection, SIGNAL(actionRemoved(Action*,ActionCollection*)), this, SIGNAL(actionRemoved(Action*,ActionCollection*))); - disconnect(collection, SIGNAL(updated()), this, SLOT(emitUpdated())); - } -} - -void ActionCollection::emitUpdated() -{ - if (!d->blockupdated) emit updated(); -} - -/********************************************************************* - * Unserialize from XML / QIODevice / file / resource to child - * ActionCollection's and Action's this ActionCollection has. - */ - -bool ActionCollection::readXml(const QDomElement& element, const QDir& directory) -{ - return readXml(element, QStringList(directory.absolutePath())); -} - -bool ActionCollection::readXml(const QDomElement& element, const QStringList& searchPath) -{ - #ifdef KROSS_ACTIONCOLLECTION_DEBUG - krossdebug( QString("ActionCollection::readXml tagName=\"%1\"").arg(element.tagName()) ); - #endif - - d->blockupdated = true; // block updated() signals and emit it only once if everything is done - bool ok = true; - QDomNodeList list = element.childNodes(); - const int size = list.size(); - for(int i = 0; i < size; ++i) { - QDomElement elem = list.item(i).toElement(); - if( elem.isNull() ) continue; - - #ifdef KROSS_ACTIONCOLLECTION_DEBUG - krossdebug( QString(" ActionCollection::readXml child=%1 tagName=\"%2\"").arg(i).arg(elem.tagName()) ); - #endif - - if( elem.tagName() == "collection") { - const QString name = elem.attribute("name"); - const QByteArray text = elem.attribute("text").toUtf8(); - const QByteArray description = elem.attribute("comment").toUtf8(); - const QString iconname = elem.attribute("icon"); - bool enabled = QVariant(elem.attribute("enabled","true")).toBool(); - ActionCollection* c = d->collections.contains(name) ? d->collections[name] : QPointer(0); - if( ! c ) - c = new ActionCollection(name, this); - - c->setText( text.isEmpty() ? name : i18n( text ) ); - c->setDescription( description.isEmpty() ? c->text() : i18n( description ) ); - c->setIconName( iconname ); - - if( ! enabled ) - c->setEnabled(false); - if( ! c->readXml(elem, searchPath) ) - ok = false; - } - else if( elem.tagName() == "script") { - QString name = elem.attribute("name"); - Action* a = dynamic_cast< Action* >( action(name) ); - if( a ) { - #ifdef KROSS_ACTIONCOLLECTION_DEBUG - krossdebug( QString(" ActionCollection::readXml Updating Action \"%1\"").arg(a->objectName()) ); - #endif - } - else { - #ifdef KROSS_ACTIONCOLLECTION_DEBUG - krossdebug( QString(" ActionCollection::readXml Creating Action \"%1\"").arg(name) ); - #endif - - a = new Action(this, name); - addAction(name, a); - connect(a, SIGNAL(started(Kross::Action*)), &Manager::self(), SIGNAL(started(Kross::Action*)) ); - connect(a, SIGNAL(finished(Kross::Action*)), &Manager::self(), SIGNAL(finished(Kross::Action*))); - } - a->fromDomElement(elem, searchPath); - } - //else if( ! fromXml(elem) ) ok = false; - } - - d->blockupdated = false; // unblock signals - emitUpdated(); - return ok; -} - -bool ActionCollection::readXml(QIODevice* device, const QDir& directory) -{ - return readXml(device, QStringList(directory.absolutePath())); -} - -bool ActionCollection::readXml(QIODevice* device, const QStringList& searchPath) -{ - QString errMsg; - int errLine, errCol; - QDomDocument document; - bool ok = document.setContent(device, false, &errMsg, &errLine, &errCol); - if( ! ok ) { - #ifdef KROSS_ACTIONCOLLECTION_DEBUG - krosswarning( QString("ActionCollection::readXml Error at line %1 in col %2: %3").arg(errLine).arg(errCol).arg(errMsg) ); - #endif - return false; - } - return readXml(document.documentElement(), searchPath); -} - -bool ActionCollection::readXmlFile(const QString& file) -{ - #ifdef KROSS_ACTIONCOLLECTION_DEBUG - krossdebug( QString("ActionCollection::readXmlFile file=\"%1\"").arg(file) ); - #endif - - QFile f(file); - if( ! f.open(QIODevice::ReadOnly) ) { - #ifdef KROSS_ACTIONCOLLECTION_DEBUG - krosswarning( QString("ActionCollection::readXmlFile reading file \"%1\" failed.").arg(file) ); - #endif - return false; - } - bool ok = readXml(&f, QFileInfo(file).dir()); - f.close(); - - #ifdef KROSS_ACTIONCOLLECTION_DEBUG - if( ! ok ) - krosswarning( QString("ActionCollection::readXmlFile parsing XML content of file \"%1\" failed.").arg(file) ); - #endif - return ok; -} - -/********************************************************************* - * Serialize from child ActionCollection's and Action's this - * ActionCollection has to XML / QIODevice / file / resource. - */ - -QDomElement ActionCollection::writeXml() -{ - return writeXml(QStringList()); -} - -QDomElement ActionCollection::writeXml(const QStringList& searchPath) -{ - #ifdef KROSS_ACTIONCOLLECTION_DEBUG - krossdebug( QString("ActionCollection::writeXml collection.objectName=\"%1\"").arg(objectName()) ); - #endif - - QDomDocument document; - QDomElement element = document.createElement("collection"); - if( ! objectName().isNull() ) - element.setAttribute("name", objectName()); - if( ! text().isNull() && text() != objectName() ) - element.setAttribute("text", text()); - if( ! d->description.isNull() ) - element.setAttribute("comment", d->description); - if( ! d->iconname.isNull() ) - element.setAttribute("icon", d->iconname); - if( ! d->enabled ) - element.setAttribute("enabled", d->enabled); - - foreach(Action* a, actions()) { - Q_ASSERT(a); - #ifdef KROSS_ACTIONCOLLECTION_DEBUG - krossdebug( QString(" ActionCollection::writeXml action.objectName=\"%1\" action.file=\"%2\"").arg(a->objectName()).arg(a->file()) ); - #endif - QDomElement e = a->toDomElement(searchPath); - if( ! e.isNull() ) - element.appendChild(e); - } - - foreach(const QString &name, d->collectionnames) { - ActionCollection* c = d->collections[name]; - if( ! c ) continue; - QDomElement e = c->writeXml(searchPath); - if( ! e.isNull() ) - element.appendChild(e); - } - - return element; -} - -bool ActionCollection::writeXml(QIODevice* device, int indent) -{ - return writeXml(device, indent, QStringList()); -} - -bool ActionCollection::writeXml(QIODevice* device, int indent, const QStringList& searchPath) -{ - QDomDocument document; - QDomElement root = document.createElement("KrossScripting"); - - foreach(Action* a, actions()) { - QDomElement e = a->toDomElement(searchPath); - if( ! e.isNull() ) - root.appendChild(e); - } - - foreach(const QString &name, d->collectionnames) { - ActionCollection* c = d->collections[name]; - if( ! c ) continue; - QDomElement e = c->writeXml(searchPath); - if( ! e.isNull() ) - root.appendChild(e); - } - - document.appendChild(root); - return device->write( document.toByteArray(indent) ) != -1; -} - -#include "moc_actioncollection.cpp" diff --git a/kross/core/actioncollection.h b/kross/core/actioncollection.h deleted file mode 100644 index 71371b6f..00000000 --- a/kross/core/actioncollection.h +++ /dev/null @@ -1,248 +0,0 @@ -/*************************************************************************** - * actioncollection.h - * This file is part of the KDE project - * copyright (C)2004-2007 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_ACTIONCOLLECTION_H -#define KROSS_ACTIONCOLLECTION_H - -#include "krossconfig.h" -#include "action.h" - -#include -#include - -#include -#include - -namespace Kross { - - /** - * The ActionCollection class manages collections of \a Action instances. - * An ActionCollection can have both actions and other collections as children. - * Child actions can be accessed using actions() which returns a list of Action pointers. - * Child collections can be accessed using collections() which returns a list of collection names. - * The collection can then be accessed with collection(name). - * To add a child action, call addAction(), and to remove an action: removeAction(). - * To add a child collection, call setParentCollection(parent) in the collection you want to add to parent. - * To remove a collection call setParentCollection(0). - * NOTE: Do not use setParent(). - */ - class KROSS_EXPORT ActionCollection : public QObject - { - Q_OBJECT - - public: - - /** - * Constructor. - * - * \param name The objectName the ActionCollection has. - * \param parent The parent ActionCollection this - * ActionCollection will be child of. If parent is not - * NULL, this \a ActionCollection instance will register - * itself as child of the parent \p parent by using the - * \a setParentCollection method. - */ - explicit ActionCollection(const QString& name, ActionCollection* parent = 0); - - /** - * Destructor. - */ - virtual ~ActionCollection(); - - /** - * \return the objectName for this ActionCollection. - */ - QString name() const; - - /** - * \return the display text - */ - QString text() const; - - /** - * Set the display text to \p text . - */ - void setText(const QString& text); - - /** - * \return the optional description for this ActionCollection. - */ - QString description() const; - - /** - * Set the optional description for this ActionCollection. - */ - void setDescription(const QString& description); - - /** - * \return the name of the icon. - */ - QString iconName() const; - - /** - * Set the name of the icon to \p iconname . - */ - void setIconName(const QString& iconname); - - /** - * \return the icon defined with \p setIconName() . - */ - QIcon icon() const; - - /** - * Return the enable this ActionCollection has. - */ - bool isEnabled() const; - - /** - * Enable or disable this ActionCollection. - */ - void setEnabled(bool enabled); - - /** - * \return the parent \a ActionCollection instance this - * \collection is child of or NULL if this collection - * does not have a parent. - */ - ActionCollection* parentCollection() const; - /// Set the parent to @p parent. NOTE: Do not use setParent(). - void setParentCollection( ActionCollection *parent ); - /** - * \return true if this collection has a child \a ActionCollection - * instance which objectName is \p name . - */ - bool hasCollection(const QString& name) const; - - /** - * \return the \a ActionCollection instance which objectName is - * \p name or NULL if there exists no such \a ActionCollection . - */ - ActionCollection* collection(const QString& name) const; - - /** - * \return a list of names of child \a ActionCollection instances - * this collection has - */ - QStringList collections() const; - - QList actions() const; - - /** - * \return action with given name or 0 if it wasn't found - */ - Action* action(const QString& name) const; - void addAction(Action* action); - void addAction(const QString& name, Action* action); - void removeAction(const QString& name); - void removeAction(Action* action); - - /** - * Load child \a Action and \a ActionCollection instances this - * collection has from the \p element . - * - * \param element The QDomElement that contains the XML. - * \param directory The current directory used for relative paths - * defined within a script-tag for the file-attribute. If the - * directory is QDir() relative paths are not resolved. - * \return true on success else false. - */ - bool readXml(const QDomElement& element, const QDir& directory = QDir()); - bool readXml(const QDomElement& element, const QStringList& searchPath/* = QStringList()*/); - - /** - * Read XML from the QIODevice \p device . - */ - bool readXml(QIODevice* device, const QDir& directory = QDir()); - bool readXml(QIODevice* device, const QStringList& searchPath/* = QStringList()*/); - - /** - * Read the XML from the file \p file . - * - * \param file The existing XML file that should be read. - * \return true if reading was successful else false. - */ - bool readXmlFile(const QString& file); - - /** - * \return a QDomElement that represents the child \a Action - * and \a ActionCollection instances this collection has. - */ - QDomElement writeXml(); - QDomElement writeXml(const QStringList& searchPath/* = QStringList()*/); - - - /** - * Write XML to the QIODevice \p device and use a space-idention - * of \p indent for the XML. - */ - bool writeXml(QIODevice* device, int indent = 2); - bool writeXml(QIODevice* device, int indent/* = 2*/, const QStringList& searchPath/* = QStringList()*/); - - - Q_SIGNALS: - - /** - * This signal is emitted if the content of the ActionCollection - * was changed. - */ - void updated(); - - /// This signal is emitted when the data of a child action is changed - void dataChanged(Action*); - /// This signal is emitted when the data of the ActionCollection is changed - void dataChanged(ActionCollection*); - - /// This signal is emitted just before @p child is added to @p parent - void collectionToBeInserted(ActionCollection* child, ActionCollection* parent); - /// This signal is emitted after @p child has been added to @p parent - void collectionInserted(ActionCollection* child, ActionCollection* parent); - /// This signal is emitted before @p child is removed from @p parent - void collectionToBeRemoved(ActionCollection* child, ActionCollection* parent); - /// This signal is emitted after @p child has been removed from @p parent - void collectionRemoved(ActionCollection* child, ActionCollection* parent); - - /// This signal is emitted just before @p child is added to @p parent - void actionToBeInserted(Action* child, ActionCollection* parent); - /// This signal is emitted after @p child has been added to @p parent - void actionInserted(Action* child, ActionCollection* parent); - /// This signal is emitted before @p child is removed from @p parent - void actionToBeRemoved(Action* child, ActionCollection* parent); - /// This signal is emitted after @p child has been removed from @p parent - void actionRemoved(Action* child, ActionCollection* parent); - - protected: - void registerCollection(ActionCollection* collection); - void unregisterCollection(const QString& name); - void connectSignals(ActionCollection* collection, bool conn); - void connectSignals(Action* collection, bool conn); - - private Q_SLOTS: - void emitUpdated(); - - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; - -} - -#endif - diff --git a/kross/core/childreninterface.h b/kross/core/childreninterface.h deleted file mode 100644 index cf599f46..00000000 --- a/kross/core/childreninterface.h +++ /dev/null @@ -1,130 +0,0 @@ -/*************************************************************************** - * childreninterface.h - * This file is part of the KDE project - * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_CHILDRENINTERFACE_H -#define KROSS_CHILDRENINTERFACE_H - - -#include -#include - -#include "krossconfig.h" - -namespace Kross { - - /** - * Interface for managing \a Object collections. - * - * The \a Manager as well as the \a Action class inherit this interface - * to allow to attach QObject to a global or a local context related - * instances that should be published to the scripting code. - */ - class KROSS_EXPORT ChildrenInterface - { - public: - - /** - * Additional options that could be defined for a QObject instance. - */ - enum Options { - NoOption = 0x00, ///< No additional options. This is the default. - AutoConnectSignals = 0x01, ///< auto connect signals with scripting functions. - - //TODO probably add more options like; - //ScriptableSlots = 0x01, ///< Publish slots that have Q_SCRIPTABLE defined. - //NonScriptableSlots = 0x02, ///< Publish slots that don't have Q_SCRIPTABLE defined. - //PrivateSlots = 0x04, ///< Publish private slots. - //ProtectedSlots = 0x08, ///< Publish protected slots. - //PublicSlots = 0x10, ///< Publish public slots. - //AllSlots = ScriptableSlots|NonScriptableSlots|PrivateSlots|ProtectedSlots|PublicSlots, - //ScriptableSignals = 0x100, ///< Publish signals that have Q_SCRIPTABLE defined. - //NonScriptableSignals = 0x200, ///< Publish signals that don't have Q_SCRIPTABLE defined. - //PrivateSignals = 0x400, ///< Publish private signals. - //ProtectedSignals = 0x800, ///< Publish protected signals. - //PublicSignals = 0x1000, ///< Publish public signals. - //AllSignals = ScriptableSignals|NonScriptableSignals|PrivateSignals|ProtectedSignals|PublicSignals, - //ScriptableProperties = 0x10000, ///< Publish properties that have Q_SCRIPTABLE defined. - //NonScriptableProperties = 0x20000, ///< Publish properties that don't have Q_SCRIPTABLE defined. - //AllProperties = ScriptableProperties|NonScriptableProperties, - //GetParentObject = 0x100000, ///< Provide access to the parent QObject the QObject has. - //SetParentObject = 0x200000, ///< Be able to set the parent QObject the QObject has. - //ChildObjects = 0x400000, ///< Provide access to the child QObject's the QObject has. - //AllObjects = GetParentObject|SetParentObject|ChildObjects - - LastOption = 0x1000000 - }; - - /** - * Add a QObject to the list of children. - * \param object The QObject instance that should be added to the list of children. - * \param name The name the QObject should be known under. If not defined, the - * QObject's objectName is used. - * \param options Additional optional options for the QObject. - */ - void addObject(QObject* object, const QString& name = QString(), Options options = NoOption) { - QString n = name.isNull() ? object->objectName() : name; - m_objects.insert(n, object); - if( options != NoOption ) - m_options.insert(n, options); - } - - /** - * \return true if there exist a QObject with the \p name else false is returned. - */ - bool hasObject(const QString& name) const { - return m_objects.contains(name); - } - - /** - * \return the QObject with \p name or NULL if there exist no such object. - */ - QObject* object(const QString& name) const { - return m_objects.contains(name) ? m_objects.value(name) : 0; - } - - /** - * \return the map of QObject instances. - */ - QHash< QString, QObject* > objects() const { - return m_objects; - } - - /** - * \return true if the QObject with \p name was added with autoConnect enabled. - */ - Options objectOption(const QString& name) const { - return m_options.contains(name) ? m_options.value(name) : NoOption; - } - - /** - * \return the map of options. - */ - QHash< QString, Options > objectOptions() const { - return m_options; - } - - private: - QHash< QString, QObject* > m_objects; - QHash< QString, Options > m_options; - }; - -} - -#endif - diff --git a/kross/core/errorinterface.h b/kross/core/errorinterface.h deleted file mode 100644 index ea02162a..00000000 --- a/kross/core/errorinterface.h +++ /dev/null @@ -1,106 +0,0 @@ -/*************************************************************************** - * errorinterface.h - * This file is part of the KDE project - * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_ERRORINTERFACE_H -#define KROSS_ERRORINTERFACE_H - -#include "krossconfig.h" - -#include - -namespace Kross { - - /** - * Interface for error-handling. - */ - class KROSS_EXPORT ErrorInterface - { - public: - - /** - * Constructor. - * - * \param error The error message. - * \param lineno The liner number in the scripting - * code where this exception got thrown. - */ - ErrorInterface() {} - - /** - * \return true if there was an error else false is returned. - */ - bool hadError() const { return ! m_error.isNull(); } - - /** - * \return the trace message. - */ - const QString errorMessage() const { return m_error; } - - /** - * \return the error message. - */ - const QString errorTrace() const { return m_trace; } - - /** - * \return the line number in the scripting code where the - * exception got thrown or -1 if there was no line number defined. - */ - long errorLineNo() const { return m_lineno; } - - /** - * Set the error message. - */ - void setError(const QString& errormessage, const QString& tracemessage = QString(), long lineno = -1) { - m_error = errormessage; - m_trace = tracemessage; - m_lineno = lineno; - krosswarning( QString::fromLatin1("Error error=%1 lineno=%2 trace=\n%3").arg(m_error).arg(m_lineno).arg(m_trace) ); - } - - /** - * Set the error message. - */ - void setError(ErrorInterface* error) { - m_error = error->errorMessage(); - m_trace = error->errorTrace(); - m_lineno = error->errorLineNo(); - } - - /** - * Clear the error. - */ - void clearError() { - m_error.clear(); - m_trace.clear(); - m_lineno = -1; - } - - private: - /// The error message. - QString m_error; - /// The trace message. - QString m_trace; - /// The line number where the exception got thrown - long m_lineno; - }; - -} - -#endif - diff --git a/kross/core/interpreter.cpp b/kross/core/interpreter.cpp deleted file mode 100644 index 64db03c4..00000000 --- a/kross/core/interpreter.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/*************************************************************************** - * interpreter.cpp - * This file is part of the KDE project - * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "interpreter.h" -#include "script.h" -#include "action.h" -#include "manager.h" - -extern "C" -{ - typedef void* (*def_interpreter_func)(int version, Kross::InterpreterInfo*); -} - -using namespace Kross; - -/************************************************************************* - * InterpreterInfo - */ - -namespace Kross { - - /// \internal d-pointer class. - class InterpreterInfo::Private - { - public: - /// The name the interpreter has. Could be something like "python". - QString interpretername; - /// The function-pointer to the module factory function. - void* funcPtr; - /// The file wildcard used to determinate extensions. - QString wildcard; - /// List of mimetypes this interpreter supports. - QStringList mimetypes; - /// A map with options. - Option::Map options; - /// The \a Interpreter instance. - Interpreter* interpreter; - }; - -} - -InterpreterInfo::InterpreterInfo(const QString& interpretername, void* funcPtr, const QString& wildcard, const QStringList& mimetypes, const Option::Map& options) - : d( new Private() ) -{ - d->interpretername = interpretername; - d->funcPtr = funcPtr; - d->wildcard = wildcard; - d->mimetypes = mimetypes; - d->options = options; - d->interpreter = 0; -} - -InterpreterInfo::~InterpreterInfo() -{ - delete d->interpreter; - d->interpreter = 0; - delete d; -} - -const QString InterpreterInfo::interpreterName() const -{ - return d->interpretername; -} - -const QString InterpreterInfo::wildcard() const -{ - return d->wildcard; -} - -const QStringList InterpreterInfo::mimeTypes() const -{ - return d->mimetypes; -} - -bool InterpreterInfo::hasOption(const QString& name) const -{ - return d->options.contains(name); -} - -InterpreterInfo::Option* InterpreterInfo::option(const QString& name) const -{ - return d->options.contains(name) ? d->options[name] : 0; -} - -InterpreterInfo::Option::Map& InterpreterInfo::options() -{ - return d->options; -} - -const QVariant InterpreterInfo::optionValue(const QString& name, const QVariant& defaultvalue) const -{ - return d->options.contains(name) ? d->options[name]->value : defaultvalue; -} - -Interpreter* InterpreterInfo::interpreter() -{ - if(d->interpreter) // buffered - return d->interpreter; - - //#ifdef KROSS_INTERPRETER_DEBUG - krossdebug( QString("Loading the interpreter library for %1").arg(d->interpretername) ); - //#endif - - // Get the extern "C" krosspython_instance function. - def_interpreter_func interpreter_func = (def_interpreter_func) d->funcPtr; - - // and execute the extern krosspython_instance function. - d->interpreter = interpreter_func - ? (Interpreter*) (interpreter_func)(KROSS_VERSION, this) - : 0; - - if(! d->interpreter) { - //#ifdef KROSS_INTERPRETER_DEBUG - krosswarning("Incompatible interpreter library."); - //#endif - } - else { - // Job done. The library is loaded and our Interpreter* points - // to the external Kross::Python::Interpreter* instance. - //#ifdef KROSS_INTERPRETER_DEBUG - krossdebug("Successfully loaded Interpreter instance from library."); - //#endif - } - - return d->interpreter; -} - -/************************************************************************* - * Interpreter - */ - -namespace Kross { - - /// \internal d-pointer class. - class Interpreter::Private - { - public: - InterpreterInfo* interpreterinfo; - Private(InterpreterInfo* info) : interpreterinfo(info) {} - }; - -} - -Interpreter::Interpreter(InterpreterInfo* info) - : QObject() - , ErrorInterface() - , d( new Private(info) ) -{ -} - -Interpreter::~Interpreter() -{ - delete d; -} - -InterpreterInfo* Interpreter::interpreterInfo() const -{ - return d->interpreterinfo; -} - -#include "moc_interpreter.cpp" diff --git a/kross/core/interpreter.h b/kross/core/interpreter.h deleted file mode 100644 index 720f57e3..00000000 --- a/kross/core/interpreter.h +++ /dev/null @@ -1,221 +0,0 @@ -/*************************************************************************** - * interpreter.h - * This file is part of the KDE project - * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_INTERPRETER_H -#define KROSS_INTERPRETER_H - -#include "errorinterface.h" - -#include -#include -#include -#include - -namespace Kross { - - // Forward declaration. - class Manager; - class Action; - class Script; - class Interpreter; - - /** - * The InterpreterInfo class provides abstract information about - * a \a Interpreter before the interpreter-backend itself is - * loaded. - */ - class KROSS_EXPORT InterpreterInfo - { - public: - - /** - * Each interpreter is able to define options we could - * use to manipulate the interpreter behaviour. - */ - class Option - { - public: - - /** - * Map of options. - */ - typedef QMap< QString, Option* > Map; - - /** - * Constructor. - * - * \param comment A localized comment that describes - * the option. - * \param value The QVariant value this option has. - */ - Option(const QString& comment, const QVariant& value) - : comment(comment), value(value) {} - - /// A description of the option. - QString comment; - - /// The value the option has. - QVariant value; - }; - - /** - * Constructor. - * - * \param interpretername The name of the interpreter. The name is - * used internaly as unique identifier for the interpreter and - * could be for example "python", "ruby" or "javascript". - * \param funcPtr A pointer to the entry function within the - * library. The entry function each interpreter-backend does - * provide looks like this; - * \code - * typedef void* (*def_interpreter_func)(int version, Kross::InterpreterInfo*); - * \endcode - * The def_interpreter_func function will be used by Kross to load - * the interpreter's library. The passed version is used to be able - * to versioning details and we use the KROSS_VERSION defined within - * the krossconfig.h file here. - * \param wildcard File wildcard that identifies a by the interpreter - * supported scripting files. As example Python does define here - * "*.py" while Java does define "*.java *.class". - * \param mimetypes The file mimetype that identifies a by the interpreter - * supported scripting files. As example Python does define "text/x-python" - * here while Ruby defines "application/x-ruby" and Java "application/java". - * \param options The optional list of options supported by the interpreter - * to configure the backend. - */ - InterpreterInfo(const QString& interpretername, void* funcPtr, const QString& wildcard, const QStringList& mimetypes, const Option::Map& options = Option::Map()); - - /** - * Destructor. - */ - ~InterpreterInfo(); - - /** - * \return the name of the interpreter. For example "python" or "kjs". - */ - const QString interpreterName() const; - - /** - * \return the file-wildcard used to determinate by this interpreter - * used scriptingfiles. Those filter will be used e.g. with - * KGlobal::dirs()->findAllResources() as filtermask. For example - * python just defines it as "*py". - */ - const QString wildcard() const; - - /** - * List of mimetypes this interpreter supports. - * \return QStringList with mimetypes like "application/javascript". - */ - const QStringList mimeTypes() const; - - /** - * \return true if an \a Option with that \p key exists else false. - */ - bool hasOption(const QString& name) const; - - /** - * \return the option defined with \p name . - */ - Option* option(const QString& name) const; - - /** - * \return the reference to the intenal used map with all options. - */ - Option::Map& options(); - - /** - * \return the value of the option defined with \p name . If there - * doesn't exists an option with such a name, the \p defaultvalue - * is returned. - */ - const QVariant optionValue(const QString& name, const QVariant& defaultvalue = QVariant()) const; - - /** - * \return the \a Interpreter instance this \a InterpreterInfo - * is the describer for. If the interpreter that implements the - * scripting backend isn't loaded yet, this method will trigger - * the loading of the interpreter's library. Note that this - * method may return NULL if there is no library for that - * interpreter installed or if the library is incompatible. - */ - Interpreter* interpreter(); - - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; - - /** - * Base class for interpreter implementations. - * - * Each scripting backend needs to inherit its own - * interpreter and implement it. - * - * The Interpreter will be managed by the \a Manager - * class and does provide a factory method to create - * \a Script implementations. - */ - class KROSS_EXPORT Interpreter : public QObject, public ErrorInterface - { - Q_OBJECT - public: - - /** - * Constructor. - * - * \param info is the \a InterpreterInfo instance - * that describes this interpreter. - */ - explicit Interpreter(InterpreterInfo* info); - - /** - * Destructor. - */ - virtual ~Interpreter(); - - /** - * \return the \a InterpreterInfo that represents - * this \a Interpreter . - */ - InterpreterInfo* interpreterInfo() const; - - /** - * Create and return a new interpreter dependent - * \a Script instance. - * - * \param Action The \a Action - * to use for the \a Script instance. - * \return The from \a Script inherited instance. - */ - virtual Script* createScript(Action* Action) = 0; - - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; - -} - -#endif - diff --git a/kross/core/krossconfig.cpp b/kross/core/krossconfig.cpp deleted file mode 100644 index 5e1fe98f..00000000 --- a/kross/core/krossconfig.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/*************************************************************************** - * krossconfig.h - * This file is part of the KDE project - * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "krossconfig.h" - -#ifdef KROSS_DEBUG_ENABLED - -#include - -using namespace Kross; - -void Kross::krossdebug(const QString &s) -{ - //kDebug(410) << s; - qDebug() << "Kross:" << s; -} - -void Kross::krosswarning(const QString &s) -{ - //kWarning(410) << s; - qWarning() << "Kross:" << s; -} - -#endif diff --git a/kross/core/krossconfig.h b/kross/core/krossconfig.h deleted file mode 100644 index dc587671..00000000 --- a/kross/core/krossconfig.h +++ /dev/null @@ -1,84 +0,0 @@ -/*************************************************************************** - * krossconfig.h - * This file is part of the KDE project - * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_MAIN_KROSSCONFIG_H -#define KROSS_MAIN_KROSSCONFIG_H - -#include "kross/core/kross_export.h" - -#include -#include - -namespace Kross { - - // Debugging enabled. Comment the line out to disable all kind of debugging. - #define KROSS_DEBUG_ENABLED - - #ifdef KROSS_DEBUG_ENABLED - - /** - * Debugging function. - */ - KROSS_EXPORT void krossdebug(const QString &s); - - /** - * Warning function. - */ - KROSS_EXPORT void krosswarning(const QString &s); - - #else - // Define these to an empty statement if debugging is disabled. - #define krossdebug(x) - #define krosswarning(x) - #endif - - // Some more debug switches. - //#define KROSS_OBJECT_METACALL_DEBUG - //#define KROSS_METATYPE_DEBUG - //#define KROSS_INTERPRETER_DEBUG - //#define KROSS_ACTION_DEBUG - //#define KROSS_ACTIONCOLLECTION_DEBUG - - // The version number of Kross. For example the interpreters use - // it do be sure there are linked against the correct core version - // and if the numbers don't match, the interpreter is not loaded. - #define KROSS_VERSION 12 - - // The export macro for interpreter plugins. - #define KROSS_EXPORT_INTERPRETER( InterpreterImpl ) \ - extern "C" { \ - Q_DECL_EXPORT void* krossinterpreter(int version, Kross::InterpreterInfo* info) { \ - if(version != KROSS_VERSION) { \ - Kross::krosswarning(QString("Interpreter skipped cause provided version %1 does not match expected version %2.").arg(version).arg(KROSS_VERSION)); \ - return 0; \ - } \ - return new InterpreterImpl(info); \ - } \ - } - - // The name of the interpreter's library. Those library got loaded - // dynamically during runtime. Comment out to disable compiling of - // the interpreter-plugin or to hardcode the location of the lib - // like I did at the following line. - #define KROSS_QTSCRIPT_LIBRARY "krossqts" - -} - -#endif - diff --git a/kross/core/manager.cpp b/kross/core/manager.cpp deleted file mode 100644 index dbd877c7..00000000 --- a/kross/core/manager.cpp +++ /dev/null @@ -1,335 +0,0 @@ -/*************************************************************************** - * manager.cpp - * This file is part of the KDE project - * copyright (C)2004-2007 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "manager.h" -#include "interpreter.h" -#include "action.h" -#include "actioncollection.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -extern "C" -{ - typedef QObject* (*def_module_func)(); -} - -using namespace Kross; - -namespace Kross { - - /// @internal - class Manager::Private - { - public: - /// List of \a InterpreterInfo instances. - QHash< QString, InterpreterInfo* > interpreterinfos; - - /// List of the interpreter names. - QStringList interpreters; - - /// Loaded modules. - QHash< QString, QPointer > modules; - - /// The collection of \a Action instances. - ActionCollection* collection; - - /// List with custom handlers for metatypes. - QHash wrappers; - - /// Strict type handling enabled or disabled. - bool strictTypesEnabled; - }; - -} - -Q_GLOBAL_STATIC(Manager, _self) - -Manager& Manager::self() -{ - return *_self(); -} - -void* loadLibrary(const char* libname, const char* functionname) -{ - QLibrary lib(libname); - lib.setLoadHints( QLibrary::ExportExternalSymbolsHint ); - if( ! lib.load() ) { - const QString err = QString("Error: %1").arg(lib.errorString()); - - //TODO move that functionality out of Kross since we like to be Qt-only - foreach(const QString &dir, KStandardDirs().resourceDirs("module")) { - lib.setFileName( QFileInfo(dir, libname).filePath() ); - lib.setLoadHints( QLibrary::ExportExternalSymbolsHint ); - if( lib.load() ) - break; - } - - /* - if( ! lib.isLoaded() ) { - foreach(const QString& path, QCoreApplication::instance()->libraryPaths()) { - lib.setFileName( QFileInfo(path, libname).filePath() ); - lib.setLoadHints( QLibrary::ExportExternalSymbolsHint ); - if( lib.load() ) - break; - } - } - */ - - if( ! lib.isLoaded() ) { - #ifdef KROSS_INTERPRETER_DEBUG - if( strcmp(functionname, "krossinterpreter") == 0 ) - krossdebug( QString("Kross Interpreter '%1' not available: %2").arg(libname).arg(err) ); - else if( strcmp(functionname, "krossmodule") == 0 ) - krossdebug( QString("Kross Module '%1' not available: %2").arg(libname).arg(err) ); - else - krosswarning( QString("Failed to load unknown type of '%1' library: %2").arg(libname).arg(err) ); - #endif - return 0; - } - } - void* funcPtr = lib.resolve(functionname); - Q_ASSERT(funcPtr); - return funcPtr; -} - -Manager::Manager() - : QObject() - , QScriptable() - , ChildrenInterface() - , d( new Private() ) -{ - d->strictTypesEnabled = true; - setObjectName("Kross"); - d->collection = new ActionCollection("main"); - -#ifdef KROSS_QTSCRIPT_LIBRARY - if( void* funcPtr = loadLibrary(KROSS_QTSCRIPT_LIBRARY, "krossinterpreter") ) { - d->interpreterinfos.insert("qtscript", - new InterpreterInfo("qtscript", - funcPtr, // library - "*.es", // file filter-wildcard - QStringList() << "application/ecmascript" // mimetypes - ) - ); - } - if( void* funcPtr = loadLibrary(KROSS_QTSCRIPT_LIBRARY, "krossinterpreter") ) { - d->interpreterinfos.insert("javascript", - new InterpreterInfo("javascript", - funcPtr, // library - "*.js", // file filter-wildcard - QStringList() << "application/javascript" // mimetypes - ) - ); - } -#endif - - // fill the list of supported interpreternames. - QHash::Iterator it( d->interpreterinfos.begin() ); - for(; it != d->interpreterinfos.end(); ++it) - if( it.value() ) - d->interpreters << it.key(); - d->interpreters.sort(); - - // publish ourself. - ChildrenInterface::addObject(this, "Kross"); -} - -Manager::~Manager() -{ - qDeleteAll(d->wrappers); - qDeleteAll(d->interpreterinfos); - qDeleteAll(d->modules); - delete d->collection; - delete d; -} - -QHash< QString, InterpreterInfo* > Manager::interpreterInfos() const -{ - return d->interpreterinfos; -} - -bool Manager::hasInterpreterInfo(const QString& interpretername) const -{ - return d->interpreterinfos.contains(interpretername) && d->interpreterinfos[interpretername]; -} - -InterpreterInfo* Manager::interpreterInfo(const QString& interpretername) const -{ - return hasInterpreterInfo(interpretername) ? d->interpreterinfos[interpretername] : 0; -} - -const QString Manager::interpreternameForFile(const QString& file) -{ - QRegExp rx; - rx.setPatternSyntax(QRegExp::Wildcard); - for(QHash::Iterator it = d->interpreterinfos.begin(); it != d->interpreterinfos.end(); ++it) { - if( ! it.value() ) - continue; - foreach(const QString &wildcard, it.value()->wildcard().split(' ', QString::SkipEmptyParts)) { - rx.setPattern( wildcard ); - if( rx.exactMatch(file) ) - return it.value()->interpreterName(); - } - } - return QString(); -} - -Interpreter* Manager::interpreter(const QString& interpretername) const -{ - if( ! hasInterpreterInfo(interpretername) ) { - krosswarning( QString("No such interpreter '%1'").arg(interpretername) ); - return 0; - } - return d->interpreterinfos[interpretername]->interpreter(); -} - -QStringList Manager::interpreters() const -{ - return d->interpreters; -} - -ActionCollection* Manager::actionCollection() const -{ - return d->collection; -} - -bool Manager::hasAction(const QString& name) -{ - return findChild< Action* >(name) != 0L; -} - -QObject* Manager::action(const QString& name) -{ - Action* action = findChild< Action* >(name); - if(! action) { - action = new Action(this, name); -#if 0 - d->actioncollection->insert(action); //FIXME should we really remember the action? -#endif - } - return action; -} - -QObject* Manager::module(const QString& modulename) -{ - if( d->modules.contains(modulename) ) { - QObject* obj = d->modules[modulename]; - if( obj ) - return obj; - } - - if( modulename.isEmpty() || modulename.contains( QRegExp("[^a-zA-Z0-9]") ) ) { - krosswarning( QString("Invalid module name '%1'").arg(modulename) ); - return 0; - } - - QByteArray libraryname = QString("krossmodule%1").arg(modulename).toLower().toLatin1(); - - if( void* funcPtr = loadLibrary(libraryname, "krossmodule") ) { - def_module_func func = (def_module_func) funcPtr; - Q_ASSERT( func ); - QObject* module = (QObject*) (func)(); // call the function - Q_ASSERT( module ); - //krossdebug( QString("Manager::module Module successfully loaded: modulename=%1 module.objectName=%2 module.className=%3").arg(modulename).arg(module->objectName()).arg(module->metaObject()->className()) ); - d->modules.insert(modulename, module); - return module; - } - else { - krosswarning( QString("Failed to load module '%1'").arg(modulename) ); - } - return 0; -} - -void Manager::deleteModules() -{ - qDeleteAll(d->modules); - d->modules.clear(); -} - -bool Manager::executeScriptFile(const QUrl& file) -{ - krossdebug( QString("Manager::executeScriptFile() file='%1'").arg(file.toString()) ); - Action* action = new Action(0 /*no parent*/, file); - action->trigger(); - bool ok = ! action->hadError(); - delete action; //action->delayedDestruct(); - return ok; -} - -void Manager::addQObject(QObject* obj, const QString &name) -{ - this->addObject(obj, name); -} - -QObject* Manager::qobject(const QString &name) const -{ - return this->object(name); -} - -QStringList Manager::qobjectNames() const -{ - return this->objects().keys(); -} - -MetaTypeHandler* Manager::metaTypeHandler(const QByteArray& typeName) const -{ - return d->wrappers.contains(typeName) ? d->wrappers[typeName] : 0; -} - -void Manager::registerMetaTypeHandler(const QByteArray& typeName, MetaTypeHandler::FunctionPtr* handler) -{ - d->wrappers.insert(typeName, new MetaTypeHandler(handler)); -} - -void Manager::registerMetaTypeHandler(const QByteArray& typeName, MetaTypeHandler::FunctionPtr2* handler) -{ - d->wrappers.insert(typeName, new MetaTypeHandler(handler)); -} - -void Manager::registerMetaTypeHandler(const QByteArray& typeName, MetaTypeHandler* handler) -{ - d->wrappers.insert(typeName, handler); -} - -bool Manager::strictTypesEnabled() const -{ - return d->strictTypesEnabled; -} - -void Manager::setStrictTypesEnabled(bool enabled) -{ - d->strictTypesEnabled = enabled; -} - -bool Manager::hasHandlerAssigned(const QByteArray& typeName) const -{ - return d->wrappers.contains(typeName); -} - -#include "moc_manager.cpp" diff --git a/kross/core/manager.h b/kross/core/manager.h deleted file mode 100644 index 94990c63..00000000 --- a/kross/core/manager.h +++ /dev/null @@ -1,272 +0,0 @@ -/*************************************************************************** - * manager.h - * This file is part of the KDE project - * copyright (C)2004-2007 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_MANAGER_H -#define KROSS_MANAGER_H - -#include -#include -#include -#include -#include - -#include "krossconfig.h" -#include "childreninterface.h" -#include "metatype.h" - -namespace Kross { - - // Forward declarations. - class Interpreter; - class Action; - class ActionCollection; - class InterpreterInfo; - - /** - * The Manager class is a singleton that provides the main entry - * point to deal with the Kross Scripting Framework. - * - * Use \a Interpreter to just work with some implementated - * interpreter like python or ruby. While \a Action implements - * a flexible abstract container to deal with single script files. - */ - class KROSS_EXPORT Manager - : public QObject - , public QScriptable - , public ChildrenInterface - { - Q_OBJECT - - public: - - /** - * Return the Manager instance. Always use this - * function to access the Manager singleton. - */ - static Manager& self(); - - /** - * \return a map with \a InterpreterInfo* instances - * used to describe interpreters. - */ - QHash interpreterInfos() const; - - /** - * \return true if there exists an interpreter with the - * name \p interpretername else false. - */ - bool hasInterpreterInfo(const QString& interpretername) const; - - /** - * \return the \a InterpreterInfo* matching to the defined - * \p interpretername or NULL if there does not exists such - * a interpreter. - */ - InterpreterInfo* interpreterInfo(const QString& interpretername) const; - - /** - * Return the name of the \a Interpreter that feels responsible - * for the defined \p file . - * - * \param file The filename we should try to determinate the - * interpretername for. - * \return The name of the \a Interpreter which will be used - * to execute the file or QString() if we failed to determinate - * a matching interpreter for the file. - */ - const QString interpreternameForFile(const QString& file); - - /** - * Return the \a Interpreter instance defined by - * the interpretername. - * - * \param interpretername The name of the interpreter. - * e.g. "python" or "kjs". - * \return The Interpreter instance or NULL if there does not exists - * an interpreter with such an interpretername. - */ - Interpreter* interpreter(const QString& interpretername) const; - - /** - * \return the root \a ActionCollection instance. Each collection - * could have children of other collections and/or - * \a Action instances. - */ - ActionCollection* actionCollection() const; - - /** - * \return the \a MetaTypeHandler instance for custom types - * of type \p typeName . - * - * \since 4.2 - */ - MetaTypeHandler* metaTypeHandler(const QByteArray& typeName) const; - - /** - * Register a handler for custom types. - * - * See also the \a WrapperInterface class. - * - * \param typeName The custom type the handler should handle. - * \param handler Function that should be called to handle - * a custom type. - * - * \since 4.2 - */ - void registerMetaTypeHandler(const QByteArray& typeName, MetaTypeHandler::FunctionPtr* handler); - - /** - * Register a handler for custom types. - * - * See also the \a WrapperInterface class. - * - * \param typeName The custom type the handler should handle. - * \param handler Function that should be called to handle - * a custom type. - * - * \since 4.2 - */ - void registerMetaTypeHandler(const QByteArray& typeName, MetaTypeHandler::FunctionPtr2* handler); - - /** - * Register a handler for custom types. - * - * See also the \a WrapperInterface class. - * - * \param typeName The custom type the handler should handle. - * \param handler Function that should be called to handle - * a custom type. - * - * \since 4.2 - */ - void registerMetaTypeHandler(const QByteArray& typeName, MetaTypeHandler* handler); - - /** - * Returns true if strict type handling is enabled. - * - * \since 4.2 - */ - bool strictTypesEnabled() const; - - /** - * Enable more strict type handling. If enabled then scripting-backends don't - * handle unknown pointer-types where no MetaTypeHandler was registered for. - * If disabled, such unknown types will be reinterpret_cast to QObject* what - * allows to also handle unknown QObject's but will also result in a crash - * if the unknown type isn't a QObject. Per default strict type handling is - * enabled. - * - * \since 4.2 - */ - void setStrictTypesEnabled(bool enabled); - - /** - * \return whether \p typeName has a handler assigned or not. - */ - bool hasHandlerAssigned(const QByteArray& typeName) const; - public Q_SLOTS: - - /** - * \return a list of names of all supported scripting interpreters. - * The list may contain for example "python", "ruby" and "kjs" depending - * on what interpreter-plugins are installed. - */ - QStringList interpreters() const; - - /** - * \return true if there exists a \a Action QObject instance - * which is child of this \a Manager instance and is defined as \p name - * else false is returned. - */ - bool hasAction(const QString& name); - - /** - * \return the \a Action QObject instance defined with \p name which is - * child of this \a Manager instance. If there exists no such \a Action - * yet, create one. - */ - QObject* action(const QString& name); - - /** - * Load and return an external module. Modules are dynamic loadable - * plugins which could be loaded on demand to provide additional - * functionality. - * - * \param modulename The name of the module we should try to load. - * \return The QObject instance that repesents the module or NULL - * if loading failed. - */ - QObject* module(const QString& modulename); - - /** - * External modules are dynamically loadable and are normally deleted - * when the kross library is unloaded. - * Applications may choose to call deleteModules() instead to control - * deletion of the modules at another time. - */ - void deleteModules(); - - /** - * Execute a script file. - * \param file The script file that should be executed. - */ - bool executeScriptFile(const QUrl& file = QUrl()); - - void addQObject(QObject* obj, const QString &name = QString()); - QObject* qobject(const QString &name) const; - QStringList qobjectNames() const; - - Q_SIGNALS: - - /** - * This signal is emitted when the execution of a script is started. - */ - void started(Kross::Action*); - - /** - * This signal is emitted when the execution of a script is finished. - */ - void finished(Kross::Action*); - - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - - public: - - /** - * The constructor. Use \a self() to access the Manager - * singleton instance and don't call this direct. - */ - explicit Manager(); - - /** - * Destructor. - */ - virtual ~Manager(); - }; - -} - -Q_DECLARE_METATYPE(Kross::Manager*) - -#endif - diff --git a/kross/core/metafunction.h b/kross/core/metafunction.h deleted file mode 100644 index 53469529..00000000 --- a/kross/core/metafunction.h +++ /dev/null @@ -1,143 +0,0 @@ -/*************************************************************************** - * metafunction.h - * This file is part of the KDE project - * copyright (C)2005-2006 Ian Reinhart Geiser - * copyright (C)2005-2006 Matt Broadstone - * copyright (C)2005-2006 Richard J. Moore - * copyright (C)2005-2006 Erik L. Bunce - * copyright (C)2005-2007 by Sebastian Sauer - * - * 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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_METAFUNCTION_H -#define KROSS_METAFUNCTION_H - -#include -#include -#include -#include - -namespace Kross { - - /** - * The MetaFunction class implements a QObject to provide an adaptor - * between Qt signals+slots and scripting functions. - * - * For example the Kross::PythonFunction and the Kross::RubyFunction - * classes located in kdebindings inherit this class to connect a - * QObject signal together with a callable python or ruby method. - */ - class MetaFunction : public QObject - { - public: - - /** - * Constructor. - * - * \param sender The QObject instance that sends the signal. - * \param signal The signature of the signal the QObject emits. - * \param callable The callable python function that should - * be executed if the QObject emits the signal. - */ - MetaFunction(QObject* sender, const QByteArray& signal) - : QObject(), m_sender(sender), m_signature(QMetaObject::normalizedSignature(signal)) - { - //krossdebug(QString("MetaFunction sender=\"%1\" signal=\"%2\"").arg(sender->objectName()).arg(m_signature.constData())); - const uint signatureSize = m_signature.size() + 1; - - // content - m_data[0] = 1; // revision - m_data[1] = 0; // classname - m_data[2] = 0; // classinfo - m_data[3] = 0; // classinfo - m_data[4] = 1; // methods - m_data[5] = 15; // methods - m_data[6] = 0; // properties - m_data[7] = 0; // properties - m_data[8] = 0; // enums/sets - m_data[9] = 0; // enums/sets - - // slots - m_data[15] = 15; // signature start - m_data[16] = 15 + signatureSize; // parameters start - m_data[17] = 15 + signatureSize; // type start - m_data[18] = 15 + signatureSize; // tag start - m_data[19] = 0x0a; // flags - m_data[20] = 0; // eod - - // data - m_stringData = QByteArray("ScriptFunction\0", 15); - m_stringData += m_signature; - m_stringData += QByteArray("\0\0", 2); - - // static metaobject - staticMetaObject.d.superdata = &QObject::staticMetaObject; - staticMetaObject.d.stringdata = m_stringData.data(); - staticMetaObject.d.data = m_data; - staticMetaObject.d.extradata = 0; - } - - /** - * Destructor. - */ - virtual ~MetaFunction() {} - - /** - * The static \a QMetaObject instance that provides the - * QMeta-information for this QObject class. - */ - QMetaObject staticMetaObject; - - /** - * \return the dynamic build \a QMetaObject instance - * for this QObject instance. - */ - const QMetaObject *metaObject() const { - return &staticMetaObject; - } - - /** - * Try to cast this QObject instance into the class with - * name \p _clname and return the casted pointer or NULL - * if casting failed. - */ - void *qt_metacast(const char *_clname) { - if (! _clname) - return 0; - if (! strcmp(_clname, m_stringData)) - return static_cast( const_cast< MetaFunction* >(this) ); - return QObject::qt_metacast(_clname); - } - - /** - * This method got called if a method this QObject instance - * defines should be invoked. - */ - int qt_metacall(QMetaObject::Call _c, int _id, void **_a) = 0; - - protected: - /// The sender QObject. - QPointer m_sender; - /// The signature. - QByteArray m_signature; - /// The stringdata. - QByteArray m_stringData; - /// The data array. - uint m_data[21]; - }; - -} - -#endif diff --git a/kross/core/metatype.h b/kross/core/metatype.h deleted file mode 100644 index b50cab48..00000000 --- a/kross/core/metatype.h +++ /dev/null @@ -1,163 +0,0 @@ -/*************************************************************************** - * metatype.h - * This file is part of the KDE project - * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_METATYPE_H -#define KROSS_METATYPE_H - -#include "krossconfig.h" -//#include "object.h" - - -#include -#include -#include - -#include - -//#include -//#include -//#include - -namespace Kross { - - /** - * Base class for metatype-implementations. - */ - class MetaType - { - public: - virtual ~MetaType() {} - - virtual int typeId() = 0; - //virtual QObject* toObject() = 0; - //virtual QVariant toVariant() = 0; - virtual void* toVoidStar() = 0; - }; - - /** - * Metatypes which are registered in the QMetaType system. - */ - template - class MetaTypeImpl : public MetaType - { - public: - MetaTypeImpl(const METATYPE& v) : m_variant(v) { - #ifdef KROSS_METATYPE_DEBUG - krossdebug( QString("MetaTypeImpl Ctor typeid=%1 typename=%2").arg(qMetaTypeId()).arg(typeid(METATYPE).name()) ); - #endif - } - virtual ~MetaTypeImpl() { - #ifdef KROSS_METATYPE_DEBUG - krossdebug( QString("MetaTypeImpl Dtor typeid=%1 typename=%2").arg(qMetaTypeId()).arg(typeid(METATYPE).name()) ); - #endif - } - - virtual int typeId() { return qMetaTypeId(); } - //virtual QVariant toVariant() { return QVariant(typeId(), m_variant); } - virtual void* toVoidStar() { return (void*) &m_variant; } - - private: - METATYPE m_variant; - }; - - /** - * Metatypes which are listened in QVariant::Type. - */ - template - class MetaTypeVariant : public MetaType - { - public: - MetaTypeVariant(const VARIANTTYPE& v) : m_value(v) { - #ifdef KROSS_METATYPE_DEBUG - krossdebug( QString("MetaTypeVariant Ctor value=%1 typename=%2").arg(qVariantFromValue(m_value).toString()).arg(qVariantFromValue(m_value).typeName()) ); - #endif - } - virtual ~MetaTypeVariant() { - #ifdef KROSS_METATYPE_DEBUG - krossdebug( QString("MetaTypeVariant Dtor value=%1 typename=%2").arg(qVariantFromValue(m_value).toString()).arg(qVariantFromValue(m_value).typeName()) ); - #endif - } - - virtual int typeId() { return qVariantFromValue(m_value).type(); } - //virtual QVariant toVariant() { return qVariantFromValue(m_value); } - virtual void* toVoidStar() { return (void*) &m_value; } - - private: - VARIANTTYPE m_value; - }; - - /** - * Metatype for generic VoidStar pointers. - */ - class MetaTypeVoidStar : public MetaType - { - public: - MetaTypeVoidStar(int typeId, void* ptr, bool owner) : m_typeId(typeId), m_ptr(ptr), m_owner(owner) { - #ifdef KROSS_METATYPE_DEBUG - krossdebug( QString("MetaTypeVoidStar Ctor typeid=%1 typename=%2 owner=%3").arg(m_typeId).arg(typeid(m_ptr).name()).arg(m_owner) ); - #endif - } - virtual ~MetaTypeVoidStar() { - #ifdef KROSS_METATYPE_DEBUG - krossdebug( QString("MetaTypeVoidStar Ctor typeid=%1 typename=%2 owner=%3").arg(m_typeId).arg(typeid(m_ptr).name()).arg(m_owner) ); - #endif - if( m_owner ) - QMetaType::destroy(m_typeId, m_ptr); - } - virtual int typeId() { return m_typeId; } - virtual void* toVoidStar() { return (void*) &m_ptr; /*return m_ptr;*/ } - - private: - int m_typeId; - void* m_ptr; - bool m_owner; - }; - - /** - * Base class for metatype-handlers as used returned by - * the Kross::Manager::metaTypeHandler() method. - * - * \since 4.2 - */ - class KROSS_EXPORT MetaTypeHandler - { - public: - typedef QVariant (FunctionPtr) (void*); - typedef QVariant (FunctionPtr2) (MetaTypeHandler* handler, void*); - - explicit MetaTypeHandler() : m_func1(0), m_func2(0) {} - explicit MetaTypeHandler(FunctionPtr *func) : m_func1(func), m_func2(0) {} - explicit MetaTypeHandler(FunctionPtr2 *func) : m_func1(0), m_func2(func) {} - virtual ~MetaTypeHandler() {} - - /** - * This got called by the scripting-backend if the type-handler - * is called to translate a void-star pointer to a QVariant. - */ - virtual QVariant callHandler(void* ptr) { - return m_func1 ? m_func1(ptr) : m_func2 ? m_func2(this, ptr) : QVariant(); - } - - private: - FunctionPtr *m_func1; - FunctionPtr2 *m_func2; - }; -} - -#endif diff --git a/kross/core/object.cpp b/kross/core/object.cpp deleted file mode 100644 index fe298243..00000000 --- a/kross/core/object.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/*************************************************************************** - * object.cpp - * This file is part of the KDE project - * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "object.h" - -using namespace Kross; - -class Object::Private -{ - public: -}; - -Object::Object() - : QSharedData() - , ErrorInterface() - , d(new Private) -{ -} - -Object::Object(const Object &other) - : QSharedData() - , ErrorInterface() - , d(new Private) -{ - Q_UNUSED(other); -} - -Object::~Object() -{ - delete d; -} - -QVariant Object::callMethod(const QString& name, const QVariantList& args) -{ - Q_UNUSED(name); - Q_UNUSED(args); - return QVariant(); -} - -QStringList Object::methodNames() -{ - return QStringList(); -} - diff --git a/kross/core/object.h b/kross/core/object.h deleted file mode 100644 index a86fc8e8..00000000 --- a/kross/core/object.h +++ /dev/null @@ -1,123 +0,0 @@ -/*************************************************************************** - * object.h - * This file is part of the KDE project - * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_OBJECT_H -#define KROSS_OBJECT_H - -#include -#include -#include -#include -#include - -#include "krossconfig.h" -#include "errorinterface.h" - -#include - -namespace Kross { - - /** - * The class Object does provide us scripting objects like - * class instances to the C++ world. - * - * This class implementates reference counting for shared - * objects. So, no need to take care of freeing objects. - * - * Sample that does use the \a Object functionality to - * pass a Javascript classinstance to C++ code which then - * calls a method the classinstance provides. - * \code - * class MyObject : public QObject - * { - * public Q_SLOTS: - * QVariant myFunction(Kross::Object::Ptr obj) { - * QVariantList args; - * return obj->callMethod("myMethod", args); - * } - * }; - * \endcode - * \code - * function MyClass(result) { - * this.myMethod = function() { - * return result; - * } - * } - * var myclass = new MyClass("my string"); - * var r = MyObject.myFunction(myclass); - * print(r); // prints "my string" - * \endcode - * - * \since 4.1 - */ - class KROSS_EXPORT Object : public QSharedData, public ErrorInterface - { - public: - - /** - * Shared pointer to implement reference-counting. - */ - typedef KSharedPtr Ptr; - - /** - * Default constructor. - */ - explicit Object(); - - /** - * Copy constructor. - */ - Object(const Object &other); - - /** - * Destructor. - */ - virtual ~Object(); - - /** - * Pass a call to the object and evaluated it. - * - * \param name Each call has a name that says what - * should be called. - * \param args The optional list of arguments - * passed to the call. - * \return The call-result as QVariant. - */ - virtual QVariant callMethod(const QString& name, - const QVariantList& args = QVariantList()); - - /** - * Return a list of supported callable objects. - * - * \return List of supported calls. - */ - virtual QStringList methodNames(); - - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; -} - -Q_DECLARE_METATYPE(Kross::Object::Ptr) - -#endif - diff --git a/kross/core/script.cpp b/kross/core/script.cpp deleted file mode 100644 index 912fb7c0..00000000 --- a/kross/core/script.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/*************************************************************************** - * script.cpp - * This file is part of the KDE project - * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "script.h" -#include "interpreter.h" -#include "action.h" -#include "krossconfig.h" - -using namespace Kross; - -namespace Kross { - - /// \internal d-pointer class. - class Script::Private - { - public: - /// The \a Interpreter used to create this Script instance. - Interpreter* interpreter; - /// The \a Action associated with this Script. - Action* action; - }; - -} - -Script::Script(Interpreter* interpreter, Action* action) - : QObject() - , ErrorInterface() - , d( new Private() ) -{ - //setObjectName( action->objectName() ); - d->interpreter = interpreter; - d->action = action; -} - -Script::~Script() -{ - delete d; -} - -Interpreter* Script::interpreter() const -{ - return d->interpreter; -} - -Action* Script::action() const -{ - return d->action; -} - -#include "moc_script.cpp" diff --git a/kross/core/script.h b/kross/core/script.h deleted file mode 100644 index 5edd90df..00000000 --- a/kross/core/script.h +++ /dev/null @@ -1,112 +0,0 @@ -/*************************************************************************** - * script.h - * This file is part of the KDE project - * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_SCRIPT_H -#define KROSS_SCRIPT_H - -#include "errorinterface.h" - -#include -#include -#include - -namespace Kross { - - // Forward declarations. - class Interpreter; - class Action; - - /** - * Base class for interpreter dependent functionality - * each script provides. - * - * Each \a Action holds a pointer to a class - * that implements the \a Script functionality for the - * defined \a Interpreter . - */ - class KROSS_EXPORT Script : public QObject, public ErrorInterface - { - Q_OBJECT - public: - - /** - * Constructor. - * - * \param interpreter The \a Interpreter instance that - * was used to created this \a Script instance. - * \param Action The \a Action instance this script is - * associated with. - */ - Script(Interpreter* interpreter, Action* action); - - /** - * Destructor. - */ - virtual ~Script(); - - public Q_SLOTS: - - /** - * \return the \a Interpreter instance that was used to created - * this \a Script . - */ - Interpreter* interpreter() const; - - /** - * \return the \a Action instance associated with this \a Script . - */ - Action* action() const; - - /** - * Execute the script. - */ - virtual void execute() = 0; - - /** - * \return the list of functionnames. - */ - virtual QStringList functionNames() = 0; - - /** - * Call a function in the script. - * - * \param name The name of the function which should be called. - * \param args The optional list of arguments. - */ - virtual QVariant callFunction(const QString& name, const QVariantList& args = QVariantList()) = 0; - - /** - * Evaluate some scripting code. - * - * \param code The scripting code to evaluate. - * \return The return value of the evaluation. - */ - virtual QVariant evaluate(const QByteArray& code) = 0; - - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; - -} - -#endif - diff --git a/kross/core/wrapperinterface.h b/kross/core/wrapperinterface.h deleted file mode 100644 index 430b9729..00000000 --- a/kross/core/wrapperinterface.h +++ /dev/null @@ -1,95 +0,0 @@ -/*************************************************************************** - * wrapperinterface.h - * This file is part of the KDE project - * copyright (C)2008 by Sebastian Sauer - * - * 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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_WRAPPERINTERFACE_H -#define KROSS_WRAPPERINTERFACE_H - -#include "krossconfig.h" - -namespace Kross { - - /** - * Wrapper-class used to provide handlers for custom types. - * - * Custom types are types other than QObject*, QWidget* or one - * of the base types supported by QVariant. By using the - * Kross::registerMetaTypeHandler() method such custom handlers - * can be registered and used to either translate various - * types to a by QVariant supported type or by providing on - * the fly an own wrapper class that inherits from QObject - * and does provide access to the functionality of the - * wrapped custom type. - * - * Following sample demonstrates the usage by registering - * a handler for the type "TestObject*". Once such a type - * got returned by a C++ class, the handler got called. If - * we return a QObject that implements the WrapperInterface, - * what is not needed, then the wrappedObject() method will - * be used to translate the wrapper back to the wrapped - * object if a C++ function got called and the wrapper is - * passed as argument. - * - * \code - * // This is our wrapper class we are using to e.g. provide - * // additional functionality on the fly or to provide access - * // to a C++ type that does not inherit from QObject. - * class MyWrapper : public QObject, public Kross::WrapperInterface { - * public: - * MyWrapper(QObject* obj) : QObject(obj) {} - * void* wrappedObject() const { return parent(); } - * }; - * // This function will be called by Kross if a type named - * // "TestObject*" got returned by a C++ method. - * QVariant TestObjectHandler(void* ptr) - * { - * TestObject* obj = static_cast(ptr); - * MyWrapper* w = new MyWrapper(obj); - * QVariant r; - * r.setValue( (QObject*)w ); - * return r; - * } - * // and somewhere else we finally register our function. - * Kross::Manager::self().registerMetaTypeHandler("TestObject*", TestObjectHandler); - * \endcode - * - * \since 4.2 - */ - class KROSS_EXPORT WrapperInterface - { - public: - - /** - * Destructor. - */ - virtual ~WrapperInterface(); - - /** - * This method got called by Kross if the wrapper-instance - * got passed to a C++ slot. It is recommed to return here - * the wrapped instance, but you don't need to. - */ - virtual void* wrappedObject() const = 0; - - //void wrapperConstructed() {} - //void wrapperDestroyed() {} - }; - -} - -#endif diff --git a/kross/modules/CMakeLists.txt b/kross/modules/CMakeLists.txt deleted file mode 100644 index ac36bdae..00000000 --- a/kross/modules/CMakeLists.txt +++ /dev/null @@ -1,37 +0,0 @@ -include_directories( - ${CMAKE_SOURCE_DIR} - ${KDE4_KDECORE_INCLUDES} - ${KDE4_KDEUI_INCLUDES} - ${KDE4_KIO_INCLUDES} - ${CMAKE_SOURCE_DIR}/kfile - # for the export headers - ${CMAKE_BINARY_DIR}/kross - ${CMAKE_BINARY_DIR}/kfile -) - -if(QT_QTDESIGNER_FOUND) - ############################################ - # the forms module - - kde4_add_plugin(krossmoduleforms form.cpp) - - target_link_libraries(krossmoduleforms - ${QT_QTUITOOLS_LIBRARY} - ${KDE4_KPARTS_LIBS} - ${KDE4_KFILE_LIBS} - krosscore - ) - install(TARGETS krossmoduleforms DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) -endif() - -############################################ -# the kdetranslation module - -kde4_add_plugin(krossmodulekdetranslation translation.cpp) - -target_link_libraries(krossmodulekdetranslation - ${KDE4_KPARTS_LIBS} - ${KDE4_CORE_LIBS} - krosscore -) -install(TARGETS krossmodulekdetranslation DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) diff --git a/kross/modules/form.cpp b/kross/modules/form.cpp deleted file mode 100644 index 540f3ce9..00000000 --- a/kross/modules/form.cpp +++ /dev/null @@ -1,817 +0,0 @@ -/*************************************************************************** - * form.cpp - * This file is part of the KDE project - * copyright (C)2006-2007 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "core/kross_export.h" -#include "form.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -extern "C" -{ - KROSS_EXPORT QObject* krossmodule() - { - return new Kross::FormModule(); - } -} - -using namespace Kross; - -/********************************************************************************* - * FormList - */ - -FormListView::FormListView(QWidget* parent) : QListWidget(parent) {} -FormListView::~FormListView() {} -void FormListView::clear() { QListWidget::clear(); } -void FormListView::remove(int index) { delete QListWidget::item(index); } -void FormListView::addItem(const QString& text) { QListWidget::addItem(text); } -int FormListView::count() { return QListWidget::count(); } -int FormListView::current() { return QListWidget::currentRow(); } -void FormListView::setCurrent(int row) { QListWidget::setCurrentRow(row); } -QString FormListView::text(int row) { - QListWidgetItem *item = QListWidget::item(row); - return item ? item->text() : QString(); -} - -/********************************************************************************* - * FormFileWidget - */ - -namespace Kross { - - /// \internal d-pointer class. - class FormFileWidget::Private - { - public: - KFileWidget* filewidget; - QString filename; - }; - -} - -FormFileWidget::FormFileWidget(QWidget* parent, const QString& startDirOrVariable) - : QWidget(parent), d(new Private()) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setSpacing(0); - layout->setMargin(0); - setLayout(layout); - - d->filewidget = new KFileWidget(KUrl(startDirOrVariable), this); - layout->addWidget( d->filewidget ); - //QMetaObject::invokeMethod(d->filewidget, "toggleSpeedbar", Q_ARG(bool,false)); - //KFileDialog::setMode( KFile::File | KFile::LocalOnly ); - - // slotOk() emits accepted, accept() emits fileSelected() - QObject::connect(d->filewidget, SIGNAL(fileSelected(QString)), this, SLOT(slotFileSelected(QString))); - - QObject::connect(d->filewidget, SIGNAL(fileSelected(QString)), this, SIGNAL(fileSelected(QString))); - QObject::connect(d->filewidget, SIGNAL(fileHighlighted(QString)), this, SIGNAL(fileHighlighted(QString))); - QObject::connect(d->filewidget, SIGNAL(selectionChanged()), this, SIGNAL(selectionChanged())); - QObject::connect(d->filewidget, SIGNAL(filterChanged(QString)), this, SIGNAL(filterChanged(QString))); - -// d->impl->setOperationMode(d->mode); -// if( d->mimeFilter.count() > 0 ) -// d->impl->setMimeFilter(d->mimeFilter); -// else if( ! d->filter.isEmpty() ) -// d->impl->setFilter(d->filter); - - if( parent && parent->layout() ) - parent->layout()->addWidget(this); - setMinimumSize( QSize(480,360) ); -} - -FormFileWidget::~FormFileWidget() -{ - delete d; -} - -void FormFileWidget::setMode(const QString& mode) -{ - QMetaEnum e = metaObject()->enumerator( metaObject()->indexOfEnumerator("Mode") ); - KFileWidget::OperationMode m = (KFileWidget::OperationMode) e.keysToValue( mode.toLatin1() ); - d->filewidget->setOperationMode(m); -} - -QString FormFileWidget::currentFilter() const -{ - return d->filewidget->currentFilter(); -} - -void FormFileWidget::setFilter(const QString &filter) -{ - QString f = filter; - f.replace(QRegExp("([^\\\\]{1,1})/"), "\\1\\/"); // escape '/' chars else KFileDialog assumes they are mimetypes :-/ - d->filewidget->setFilter(f); -} - -QString FormFileWidget::currentMimeFilter() const -{ - return d->filewidget->currentMimeFilter(); -} - -void FormFileWidget::setMimeFilter(const QStringList& filter) -{ - d->filewidget->setMimeFilter(filter); -} - -void FormFileWidget::slotFileSelected( const QString & fn ) -{ - //kDebug()<filename = fn; -} - -QString FormFileWidget::selectedFile() const -{ - if ( d->filewidget->operationMode() != KFileWidget::Saving ) { - d->filewidget->accept(); - } else { - //kDebug()<filename<filewidget->operationMode(); - if ( d->filename.isEmpty() ) { - // make KFileWidget create an url for us (including extension if necessary) - QObject::connect(d->filewidget, SIGNAL(accepted()), d->filewidget, SLOT(accept())); - d->filewidget->slotOk(); - QObject::disconnect(d->filewidget, SIGNAL(accepted()), d->filewidget, SLOT(accept())); - } - } - //kDebug()<filename; - KUrl url( d->filename ); - return url.path(); // strip file:// at least python chokes on it -} - -/********************************************************************************* - * FormProgressDialog - */ - -namespace Kross { - /// \internal d-pointer class. - class FormProgressDialog::Private - { - public: - QTextBrowser* browser; - QProgressBar* bar; - bool gotCanceled; - QTime time; - void update() { - if( time.elapsed() >= 1000 ) { - time.restart(); - qApp->processEvents(); - } - } - }; -} - -FormProgressDialog::FormProgressDialog(const QString& caption, const QString& labelText) : KPageDialog(), d(new Private) -{ - d->gotCanceled = false; - d->time.start(); - - setCaption(caption); - KDialog::setButtons(KDialog::Ok|KDialog::Cancel); - setFaceType(KPageDialog::Plain); - enableButton(KDialog::Ok, false); - //setWindowModality(Qt::WindowModal); - setModal(false); //true); - setMinimumWidth(540); - setMinimumHeight(400); - - QWidget* widget = new QWidget( mainWidget() ); - KPageWidgetItem* item = KPageDialog::addPage(widget, QString()); - item->setHeader(labelText); - //item->setIcon( KIcon(iconname) ); - widget = item->widget(); - QVBoxLayout* layout = new QVBoxLayout(widget); - layout->setMargin(0); - widget->setLayout(layout); - - d->browser = new QTextBrowser(this); - d->browser->setHtml(labelText); - layout->addWidget(d->browser); - - d->bar = new QProgressBar(this); - //d->bar->setFormat("%v"); - d->bar->setVisible(false); - layout->addWidget(d->bar); - - setSizePolicy( QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding) ); - show(); - qApp->processEvents(); -} - -FormProgressDialog::~FormProgressDialog() -{ - delete d; -} - -void FormProgressDialog::setValue(int progress) -{ - if( progress < 0 ) { - if( d->bar->isVisible() ) { - d->bar->setVisible(false); - d->bar->setValue(0); - qApp->processEvents(); - } - return; - } - if( ! d->bar->isVisible() ) - d->bar->setVisible(true); - d->bar->setValue(progress); - d->update(); -} - -void FormProgressDialog::setRange(int minimum, int maximum) -{ - d->bar->setRange(minimum, maximum); -} - -void FormProgressDialog::setText(const QString& text) -{ - d->browser->setHtml(text); - d->update(); -} - -void FormProgressDialog::addText(const QString& text) -{ - QTextCursor cursor( d->browser->document()->end() ); - cursor.movePosition(QTextCursor::End); - cursor.insertBlock(); - cursor.insertHtml(text); - d->browser->moveCursor(QTextCursor::End); - d->browser->ensureCursorVisible(); - d->update(); -} - -void FormProgressDialog::done(int r) -{ - if( r == Rejected && ! d->gotCanceled ) { - if( KMessageBox::messageBox(this, KMessageBox::WarningContinueCancel, i18n("Cancel?")) == KMessageBox::Continue ) { - d->gotCanceled = true; - enableButton(KDialog::Cancel, false); - emit canceled(); - } - return; - } - KPageDialog::done(r); -} - -int FormProgressDialog::exec() -{ - enableButton(KDialog::Ok, true); - enableButton(KDialog::Cancel, false); - if( d->bar->isVisible() ) - d->bar->setValue( d->bar->maximum() ); - return KDialog::exec(); -} - -bool FormProgressDialog::isCanceled() -{ - return d->gotCanceled; -} - -/********************************************************************************* - * FormDialog - */ - -namespace Kross { - - /// \internal d-pointer class. - class FormDialog::Private - { - public: - KDialog::ButtonCode buttoncode; - QHash items; - }; - -} - -FormDialog::FormDialog(const QString& caption) - : KPageDialog( /*0, Qt::WShowModal | Qt::WDestructiveClose*/ ) - , d( new Private() ) -{ - setCaption(caption); - KDialog::setButtons(KDialog::Ok); - setSizePolicy( QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding) ); - - connect(this, SIGNAL(currentPageChanged(KPageWidgetItem*,KPageWidgetItem*)), - this, SLOT(slotCurrentPageChanged(KPageWidgetItem*))); -} - -FormDialog::~FormDialog() -{ - kWarning()<<"dtor"; - delete d; -} - -bool FormDialog::setButtons(const QString& buttons) -{ - int i = metaObject()->indexOfEnumerator("ButtonCode"); - Q_ASSERT( i >= 0 ); - QMetaEnum e = metaObject()->enumerator(i); - int v = e.keysToValue( buttons.toUtf8() ); - if( v < 0 ) - return false; - KDialog::setButtons( (KDialog::ButtonCode) v ); - return true; -} - -bool FormDialog::setButtonText(const QString& button, const QString& text) -{ - int i = metaObject()->indexOfEnumerator("ButtonCode"); - Q_ASSERT( i >= 0 ); - QMetaEnum e = metaObject()->enumerator(i); - int v = e.keysToValue( button.toUtf8() ); - if( v < 0 ) - return false; - KDialog::setButtonText( (KDialog::ButtonCode) v, text); - return true; -} - -bool FormDialog::setFaceType(const QString& facetype) -{ - int i = KPageView::staticMetaObject.indexOfEnumerator("FaceType"); - Q_ASSERT( i >= 0 ); - QMetaEnum e = KPageView::staticMetaObject.enumerator(i); - int v = e.keysToValue( facetype.toUtf8() ); - if( v < 0 ) - return false; - KPageDialog::setFaceType( (KPageDialog::FaceType) v ); - return true; -} - -QString FormDialog::currentPage() const -{ - KPageWidgetItem* item = KPageDialog::currentPage(); - return item ? item->name() : QString(); -} - -bool FormDialog::setCurrentPage(const QString& name) -{ - if( ! d->items.contains(name) ) - return false; - KPageDialog::setCurrentPage( d->items[name] ); - return true; -} - -QWidget* FormDialog::page(const QString& name) const -{ - return d->items.contains(name) ? d->items[name]->widget() : 0; -} - -//shared by FormDialog and FormAssistant -static KPageWidgetItem* formAddPage(KPageDialog* dialog, const QString& name, const QString& header, const QString& iconname) -{ - QWidget* widget = new QWidget( dialog->mainWidget() ); - QVBoxLayout* boxlayout = new QVBoxLayout(widget); - boxlayout->setSpacing(0); - boxlayout->setMargin(0); - widget->setLayout(boxlayout); - - KPageWidgetItem* item = dialog->addPage(widget, name); - item->setHeader(header.isNull() ? name : header); - if( ! iconname.isEmpty() ) - item->setIcon( KIcon(iconname) ); - //d->items.insert(name, item); - - return item; -} - -QWidget* FormDialog::addPage(const QString& name, const QString& header, const QString& iconname) -{ - return d->items.insert(name, formAddPage((KPageDialog*)this,name,header,iconname)).value()->widget(); -} - -void FormDialog::setMainWidget(QWidget *newMainWidget) -{ - KDialog::setMainWidget(newMainWidget); -} - -QString FormDialog::result() -{ - int i = metaObject()->indexOfEnumerator("ButtonCode"); - if( i < 0 ) { - kWarning() << "Kross::FormDialog::setButtons No such enumerator \"ButtonCode\""; - return QString(); - } - QMetaEnum e = metaObject()->enumerator(i); - return e.valueToKey(d->buttoncode); -} - -void FormDialog::slotButtonClicked(int button) -{ - d->buttoncode = (KDialog::ButtonCode) button; - KDialog::slotButtonClicked(button); -} - -void FormDialog::slotCurrentPageChanged(KPageWidgetItem* current) -{ - Q_UNUSED(current); - //kDebug() << "FormDialog::slotCurrentPageChanged current=" << current->name(); - //foreach(QWidget* widget, current->widget()->findChildren< QWidget* >("")) widget->setFocus(); -} - - -namespace Kross { - /// \internal d-pointer class. - class FormAssistant::Private - { - public: - KDialog::ButtonCode buttoncode; - QHash items; - }; -} -FormAssistant::FormAssistant(const QString& caption) - : KAssistantDialog( /*0, Qt::WShowModal | Qt::WDestructiveClose*/ ) - , d( new Private() ) -{ - setCaption(caption); - setSizePolicy( QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding) ); - - connect(this, SIGNAL(currentPageChanged(KPageWidgetItem*,KPageWidgetItem*)), - this, SLOT(slotCurrentPageChanged(KPageWidgetItem*))); - /* unlike boost qt does not support defining of slot call order! - connect(this, SIGNAL(user2Clicked()), this, SIGNAL (nextClicked())); - connect(this, SIGNAL(user3Clicked()), this, SIGNAL (backClicked())); - */ -} - -FormAssistant::~FormAssistant() -{ - delete d; -} - -void FormAssistant::showHelpButton(bool show) -{ - showButton(KDialog::Help, show); -} - -void FormAssistant::back() -{ - emit backClicked(); - KAssistantDialog::back(); -} -void FormAssistant::next() -{ - emit nextClicked(); - KAssistantDialog::next(); -} - -QString FormAssistant::currentPage() const -{ - KPageWidgetItem* item = KPageDialog::currentPage(); - return item ? item->name() : QString(); -} - -bool FormAssistant::setCurrentPage(const QString& name) -{ - if( ! d->items.contains(name) ) - return false; - KPageDialog::setCurrentPage( d->items[name] ); - return true; -} - -QWidget* FormAssistant::page(const QString& name) const -{ - return d->items.contains(name) ? d->items[name]->widget() : 0; -} - -QWidget* FormAssistant::addPage(const QString& name, const QString& header, const QString& iconname) -{ - return d->items.insert(name, formAddPage((KPageDialog*)this,name,header,iconname)).value()->widget(); -} - -bool FormAssistant::isAppropriate (const QString& name) const -{ - return d->items.contains(name) && KAssistantDialog::isAppropriate(d->items[name]); -} -void FormAssistant::setAppropriate (const QString& name, bool appropriate) -{ - if (!d->items.contains(name)) - return; - - KAssistantDialog::setAppropriate(d->items[name],appropriate); -} -bool FormAssistant::isValid (const QString& name) const -{ - return d->items.contains(name) && KAssistantDialog::isValid(d->items[name]); -} -void FormAssistant::setValid (const QString& name, bool enable) -{ - if (!d->items.contains(name)) - return; - - KAssistantDialog::setValid(d->items[name],enable); -} - -QString FormAssistant::result() -{ - int i = metaObject()->indexOfEnumerator("AssistantButtonCode"); - if( i < 0 ) { - kWarning() << "Kross::FormAssistant::setButtons No such enumerator \"AssistantButtonCode\""; - return QString(); - } - QMetaEnum e = metaObject()->enumerator(i); - return e.valueToKey(FormAssistant::AssistantButtonCode(int(d->buttoncode))); -} - -void FormAssistant::slotButtonClicked(int button) -{ - d->buttoncode = (KDialog::ButtonCode) button; - KDialog::slotButtonClicked(button); -} - -void FormAssistant::slotCurrentPageChanged(KPageWidgetItem* current) -{ - Q_UNUSED(current); - //kDebug() << "FormAssistant::slotCurrentPageChanged current=" << current->name(); - //foreach(QWidget* widget, current->widget()->findChildren< QWidget* >("")) widget->setFocus(); -} - -/********************************************************************************* - * FormModule - */ - -namespace Kross { - - /// \internal extension of the QUiLoader class. - class UiLoader : public QUiLoader - { - public: - UiLoader() : QUiLoader() {} - virtual ~UiLoader() {} - - /* - virtual QAction* createAction(QObject* parent = 0, const QString& name = QString()) - { - } - - virtual QActionGroup* createActionGroup(QObject* parent = 0, const QString& name = QString()) - { - } - - virtual QLayout* createLayout(const QString& className, QObject* parent = 0, const QString& name = QString()) - { - } - - virtual QWidget* createWidget(const QString& className, QWidget* parent = 0, const QString& name = QString()) - { - } - */ - }; - - /// \internal d-pointer class. - class FormModule::Private - { - public: - }; - -} - -FormModule::FormModule() - : QObject() - , d( new Private() ) -{ -} - -FormModule::~FormModule() -{ - delete d; -} - -QWidget* FormModule::activeModalWidget() -{ - return QApplication::activeModalWidget(); -} - -QWidget* FormModule::activeWindow() -{ - return QApplication::activeWindow(); -} - -QString FormModule::showMessageBox(const QString& dialogtype, const QString& caption, const QString& message, const QString& details) -{ - KMessageBox::DialogType type; - if(dialogtype == "Error") { - if( ! details.isNull() ) { - KMessageBox::detailedError(0, message, details, caption); - return QString(); - } - type = KMessageBox::Error; - } - else if(dialogtype == "Sorry") { - if( ! details.isNull() ) { - KMessageBox::detailedSorry(0, message, details, caption); - return QString(); - } - type = KMessageBox::Sorry; - } - else if(dialogtype == "QuestionYesNo") type = KMessageBox::QuestionYesNo; - else if(dialogtype == "WarningYesNo") type = KMessageBox::WarningYesNo; - else if(dialogtype == "WarningContinueCancel") type = KMessageBox::WarningContinueCancel; - else if(dialogtype == "WarningYesNoCancel") type = KMessageBox::WarningYesNoCancel; - else if(dialogtype == "QuestionYesNoCancel") type = KMessageBox::QuestionYesNoCancel; - else /*if(dialogtype == "Information")*/ type = KMessageBox::Information; - switch( KMessageBox::messageBox(0, type, message, caption) ) { - case KMessageBox::Ok: return "Ok"; - case KMessageBox::Cancel: return "Cancel"; - case KMessageBox::Yes: return "Yes"; - case KMessageBox::No: return "No"; - case KMessageBox::Continue: return "Continue"; - default: break; - } - return QString(); -} - -QWidget* FormModule::showProgressDialog(const QString& caption, const QString& labelText) -{ - return new FormProgressDialog(caption, labelText); -} - -QWidget* FormModule::createDialog(const QString& caption) -{ - return new FormDialog(caption); -} - -QWidget* FormModule::createAssistant(const QString& caption) -{ - return new FormAssistant(caption); -} - -QObject* FormModule::createLayout(QWidget* parent, const QString& layout) -{ - QLayout* l = 0; - if( layout == "QVBoxLayout" ) - l = new QVBoxLayout(); - else if( layout == "QHBoxLayout" ) - l = new QHBoxLayout(); - else if( layout == "QStackedLayout" ) - l = new QStackedLayout(); - if( parent && l ) - parent->setLayout(l); - return l; -} - -QWidget* FormModule::createWidget(const QString& className) -{ - UiLoader loader; - QWidget* widget = loader.createWidget(className); - return widget; -} - -QWidget* FormModule::createWidget(QWidget* parent, const QString& className, const QString& name) -{ - UiLoader loader; - QWidget* widget = loader.createWidget(className, parent, name); - if( parent && parent->layout() ) - parent->layout()->addWidget(widget); - return widget; -} - - -QString FormModule::tr(const QString& str) -{ - return QObject::tr(str.toUtf8()); -} - -QWidget* FormModule::createWidgetFromUI(QWidget* parent, const QString& xml) -{ - QUiLoader loader; - - QDomDocument doc("mydocument"); - doc.setContent(xml.toUtf8()); - - QDomNodeList strings=doc.elementsByTagName("string"); - int i=strings.size(); - while(--i>=0) - { - QDomElement e=strings.at(i).toElement(); - QString i18nd=QObject::tr(e.text().toUtf8()); - if (i18nd==e.text()) - continue; - QDomNode n = e.firstChild(); - while (!n.isNull()) - { - QDomNode nn=n.nextSibling(); - if (n.isCharacterData()) - e.removeChild(n); - n = nn; - } - e.appendChild(e.ownerDocument().createTextNode(i18nd)); - } - - QByteArray ba = doc.toByteArray(); - QBuffer buffer(&ba); - buffer.open(QIODevice::ReadOnly); - - QWidget* widget = loader.load(&buffer, parent); - if( widget && parent && parent->layout() ) - parent->layout()->addWidget(widget); - return widget; -} - -QWidget* FormModule::createWidgetFromUIFile(QWidget* parent, const QString& filename) -{ - QFile file(filename); - if( ! file.exists() ) { - kDebug() << QString("Kross::FormModule::createWidgetFromUIFile: There exists no such file \"%1\"").arg(filename); - return 0; - } - if( ! file.open(QFile::ReadOnly) ) { - kDebug() << QString("Kross::FormModule::createWidgetFromUIFile: Failed to open the file \"%1\"").arg(filename); - return 0; - } - const QString xml = file.readAll(); - file.close(); - return createWidgetFromUI(parent, xml); -} - -QWidget* FormModule::createFileWidget(QWidget* parent, const QString& startDirOrVariable) -{ - FormFileWidget* widget = new FormFileWidget(parent, startDirOrVariable); - if( parent && parent->layout() ) - parent->layout()->addWidget(widget); - return widget; -} - -QWidget* FormModule::createListView(QWidget* parent) -{ - FormListView* widget = new FormListView(parent); - if( parent && parent->layout() ) - parent->layout()->addWidget(widget); - return widget; -} - -QAction* FormModule::createAction(QObject* parent) -{ - return new QAction(parent); -} - -QObject* FormModule::loadPart(QWidget* parent, const QString& name, const QUrl& url) -{ - //name e.g. "libkghostview" - KPluginFactory* factory = KPluginLoader( name.toLatin1() ).factory(); - if( ! factory ) { - kWarning() << QString("Kross::FormModule::loadPart: No such library \"%1\"").arg(name); - return 0; - } - KParts::ReadOnlyPart* part = factory->create< KParts::ReadOnlyPart >( parent ); - if( ! part ) { - kWarning() << QString("Kross::FormModule::loadPart: Library \"%1\" is not a KPart").arg(name); - return 0; - } - if( url.isValid() ) - part->openUrl(url); - if( parent && parent->layout() && part->widget() ) - parent->layout()->addWidget( part->widget() ); - return part; -} - -#include "moc_form.cpp" diff --git a/kross/modules/form.h b/kross/modules/form.h deleted file mode 100644 index 1768e93a..00000000 --- a/kross/modules/form.h +++ /dev/null @@ -1,699 +0,0 @@ -/*************************************************************************** - * form.h - * This file is part of the KDE project - * copyright (C)2006-2007 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_FORM_H -#define KROSS_FORM_H - -#include -#include -#include - -#include -#include - -namespace Kross { - - /** - * The FormListView class provides access to a ListView. - */ - class FormListView : public QListWidget - { - Q_OBJECT - public: - explicit FormListView(QWidget* parent); - virtual ~FormListView(); - public Q_SLOTS: - void clear(); - void remove(int index); - void addItem(const QString& text); - int count(); - int current(); - void setCurrent(int row); - QString text(int row); - }; - - /** - * The FormFileWidget class provides access to a KFileWidget. - */ - class FormFileWidget : public QWidget - { - Q_OBJECT - Q_ENUMS(Mode) - - public: - FormFileWidget(QWidget* parent, const QString& startDirOrVariable); - virtual ~FormFileWidget(); - - /** - * The Mode the FormFileWidget could have. - */ - enum Mode { Other = 0, Opening, Saving }; - - public Q_SLOTS: - - /** - * Set the \a Mode the FormFileWidget should have to \p mode . - * Valid modes are "Other", "Opening" or "Saving". - */ - void setMode(const QString& mode); - - /** - * \return the current filter. - */ - QString currentFilter() const; - - /** - * Set the filter to \p filter . - */ - void setFilter(const QString &filter); - - /** - * \return the current mimetype filter. - */ - QString currentMimeFilter() const; - - /** - * Set the mimetype filter to \p filter . - */ - void setMimeFilter(const QStringList& filter); - - /** - * \return the currently selected file. - */ - QString selectedFile() const; - - //QStringList selectedFiles() const { return KFileDialog::selectedFiles(); } - //QString selectedUrl() const { return KFileDialog::selectedUrl().toLocalFile(); } - - Q_SIGNALS: - - /** - * Emitted when the user selects a file. It is only emitted in single- - * selection mode. - */ - void fileSelected(const QString& file); - - /** - * Emitted when the user highlights a file. - */ - void fileHighlighted(const QString&); - - /** - * Emitted when the user hilights one or more files in multiselection mode. - */ - void selectionChanged(); - - /** - * Emitted when the filter changed, i.e. the user entered an own filter - * or chose one of the predefined set via setFilter(). - */ - void filterChanged(const QString& filter); - - private Q_SLOTS: - void slotFileSelected(const QString&); - - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; - - /** - * The FormProgressDialog class provides access to progressbar. - * - * Example (in Python) : - * \code - * import time, Kross - * forms = Kross.module("forms") - * progress = forms.showProgressDialog("My Title") - * progress.setText("Some detailed text.") - * for i in range(0,101): - * progress.setValue(i) - * progress.addText("%s" % i) - * time.sleep(1) - * progress.reset() - * \endcode - */ - class FormProgressDialog : public KPageDialog - { - Q_OBJECT - public: - FormProgressDialog(const QString& caption, const QString& labelText); - virtual ~FormProgressDialog(); - virtual void done(int r); - public Q_SLOTS: - /** - * Set the value of the progressbar. If -1 the progressbar will be hidden. - */ - void setValue(int progress); - /** - * Set the minimum and maximum range of the progressbar. - */ - void setRange(int minimum, int maximum); - /** - * Set the HTML-text that is displayed as information to the text \p text . - */ - void setText(const QString& text); - /** - * Add to the HTML-text that is displayed as information the text \p text . - */ - void addText(const QString& text); - /** - * Shows the dialog as a modal dialog, blocking until the user - * closes it and returns the execution result. - * - * \return >=1 if the dialog was accepted (e.g. "Ok" pressed) else - * the user rejected the dialog (e.g. by pressing "Cancel" or just - * closing the dialog by pressing the escape-key). - */ - int exec(); - /** - * Same as the \a exec() method above provided for Python-lovers (python - * does not like functions named "exec" and PyQt named it "exec_loop", so - * just let's do the same). - */ - int exec_loop() { return exec(); } - /** - * Returns true if the user requested to cancel the operation. - */ - bool isCanceled(); - Q_SIGNALS: - /** - * This signal got emitted if the user requests to cancel the operation. - */ - void canceled(); - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; - - /** - * The FormDialog class provides access to KDialog objects as - * top-level containers. - * - * Example (in Python) : - * \code - * import Kross - * import sys,os - * ourPath=(filter(lambda p: os.path.exists(p+'/mywidget.ui'),sys.path)+[''])[0] - * forms = Kross.module("forms") - * mydialog = forms.createDialog("MyDialog") - * mydialog.setButtons("Ok|Cancel") - * mydialog.setFaceType("Plain") #Auto Plain List Tree Tabbed - * mypage = mydialog.addPage("name","header") - * mywidget = forms.createWidgetFromUIFile(mypage, ourPath+'/mywidget.ui') - * mywidget["lineEdit"].setText("some string") - * if mydialog.exec_loop(): - * if mydialog.result() == "Ok": - * print mywidget["lineEdit"].text - * mydialog.deleteLater() - * \endcode - */ - class FormDialog: public KPageDialog - { - Q_OBJECT - - public: - FormDialog(const QString& caption); - virtual ~FormDialog(); - - public Q_SLOTS: - - /** - * Set the buttons. - * - * \param buttons string that defines the displayed buttons. For example the - * string may look like "Ok" or "Ok|Cancel" or "Yes|No|Cancel". - * \return true if the passed \p buttons string was valid and setting the - * buttons was successfully else false is returned. - */ - bool setButtons(const QString& buttons); - - /** - * Set the text of a button. - * - * Sample how to change the buttons of a dialog; - * \code - * dialog.setButtons("Yes|No|Cancel") - * dialog.setButtonText("Yes","Overwrite") - * dialog.setButtonText("No","Skip") - * dialog.setButtonText("Cancel","Abort") - * \endcode - * - * \param button string that defines the button that should be changed. - * \param text string that should be used as button text. - * \return true if the passed \p buttons string was valid and setting the - * button text was successfully else false is returned. - */ - bool setButtonText(const QString& button, const QString& text); - - /** - * Set the face type of the dialog. - * - * \param facetype the face type which could be "Auto", "Plain", "List", - * "Tree" or "Tabbed" as defined in \a KPageView::FaceType . - */ - bool setFaceType(const QString& facetype); - - /** - * \return the name of the currently selected page. Use the \a page() - * method to get the matching page QWidget instance. - */ - QString currentPage() const; - - /** - * Set the current page to \p name . If there exists no page with - * such a pagename the method returns false else (if the page was - * successfully set) true is returned. - */ - bool setCurrentPage(const QString& name); - - /** - * \return the QWidget page instance which has the pagename \p name - * or NULL if there exists no such page. - */ - QWidget* page(const QString& name) const; - - /** - * Add and return a new page. - * - * \param name The name the page has. This name is for example returned - * at the \a currentPage() method and should be unique. The name is also - * used to display a short title for the page. - * \param header The longer header title text used for display purposes. - * \param iconname The name of the icon which the page have. This could - * be for example "about_kde", "document-open", "configure" or any other - * iconname known by KDE. - * \return the new QWidget page instance. - */ - QWidget* addPage(const QString& name, const QString& header = QString(), const QString& iconname = QString()); - - /** - * Set the \p newMainWidget QWidget as main widget. This is only needed if - * you like to replace the KPageDialog page-widget with your own widget. - */ - void setMainWidget(QWidget *newMainWidget); - - /** - * Shows the dialog as a modal dialog, blocking until the user - * closes it and returns the execution result. - * - * \return >=1 if the dialog was accepted (e.g. "Ok" pressed) else - * the user rejected the dialog (e.g. by pressing "Cancel" or just - * closing the dialog by pressing the escape-key). - */ - int exec() { return KDialog::exec(); } - - /** - * Same as the \a exec() method above provided for Python-lovers (python - * does not like functions named "exec" and PyQt named it "exec_loop", so - * just let's do the same). - */ - int exec_loop() { return exec(); } - - /** - * \return the result. The result may for example "Ok", "Cancel", "Yes" or "No". - */ - QString result(); - - private Q_SLOTS: - virtual void slotButtonClicked(int button); - void slotCurrentPageChanged(KPageWidgetItem* current); - - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; - - - /** - * The FormAssistant class provides access to KAssistantDialog objects as - * top-level containers. - * - * Example (in Python) : - * \code - * import Kross - * import sys,os - * ourPath=(filter(lambda p: os.path.exists(p+'/mywidget.ui'),sys.path)+[''])[0] - * forms = Kross.module("forms") - * myassistant = forms.createAssistant("MyAssistant") - * myassistant.showHelpButton(0) - * mypage = myassistant.addPage("name","header") - * mywidget = forms.createWidgetFromUIFile(mypage, ourPath+'/mywidget.ui') - * mypage2 = myassistant.addPage("name2","header2") - * mywidget2 = forms.createWidgetFromUIFile(mypage2, ourPath+'/mywidget.ui') - * mypage3 = myassistant.addPage("name3","header3") - * mywidget3 = forms.createWidgetFromUIFile(mypage3, ourPath+'/mywidget.ui') - * mywidget["lineEdit"].setText("some string") - * - * def nextClicked(): - * myassistant.setAppropriate("name2",0) - * def finished(): - * ... - * myassistant.deleteLater() #remember to cleanup - * - * myassistant.connect("nextClicked()",nextClicked) - * myassistant.connect("finished()",finished) - * myassistant.show() - * - * \endcode - */ - class FormAssistant: public KAssistantDialog - { - Q_OBJECT - Q_ENUMS(AssistantButtonCode) - public: - enum AssistantButtonCode - { - None = 0x00000000, - Help = 0x00000001, - Default = 0x00000002, - Cancel = 0x00000020, - Finish = 0x00001000, - Next = 0x00002000, - Back = 0x00004000, - NoDefault = 0x00008000 - }; - Q_DECLARE_FLAGS(AssistantButtonCodes, AssistantButtonCode) - - public: - FormAssistant(const QString& caption); - virtual ~FormAssistant(); - - public Q_SLOTS: - - void showHelpButton(bool); - - /** - * \return the name of the currently selected page. Use the \a page() - * method to get the matching page QWidget instance. - */ - QString currentPage() const; - - /** - * Set the current page to \p name . If there exists no page with - * such a pagename the method returns false else (if the page was - * successfully set) true is returned. - */ - bool setCurrentPage(const QString& name); - - /** - * \return the QWidget page instance which has the pagename \p name - * or NULL if there exists no such page. - */ - QWidget* page(const QString& name) const; - - /** - * Add and return a new page. - * - * \param name The name the page has. This name is for example returned - * at the \a currentPage() method and should be unique. The name is also - * used to display a short title for the page. - * \param header The longer header title text used for display purposes. - * \param iconname The name of the icon which the page have. This could - * be for example "about_kde", "document-open", "configure" or any other - * iconname known by KDE. - * \return the new QWidget page instance. - */ - QWidget* addPage(const QString& name, const QString& header = QString(), const QString& iconname = QString()); - - /** - * @see KAssistantDialog::isAppropriate() - */ - bool isAppropriate (const QString& name) const; - /** - * @see KAssistantDialog::setAppropriate() - */ - void setAppropriate (const QString& name, bool appropriate); - /** - * @see KAssistantDialog::isValid() - */ - bool isValid (const QString& name) const; - /** - * @see KAssistantDialog::setValid() - */ - void setValid (const QString& name, bool enable); - - /** - * Shows the dialog as a modal dialog, blocking until the user - * closes it and returns the execution result. - * - * \return >=1 if the dialog was accepted (e.g. "Finished" pressed) else - * the user rejected the dialog (e.g. by pressing "Cancel" or just - * closing the dialog by pressing the escape-key). - */ - int exec() { return KDialog::exec(); } - - /** - * Same as the \a exec() method above provided for Python-lovers (python - * does not like functions named "exec" and PyQt named it "exec_loop", so - * just let's do the same). - */ - int exec_loop() { return exec(); } - - /** - * \return the result. The result may for example "Finish" or "Cancel". - */ - QString result(); - - /** - * Force page switching. This will also emit backClicked() - */ - void back(); - /** - * Force page switching. This will also emit nextClicked() - */ - void next(); - - private Q_SLOTS: - virtual void slotButtonClicked(int button); - void slotCurrentPageChanged(KPageWidgetItem* current); - - signals: - /** - * use it to setAppropriate() - */ - void nextClicked(); - void backClicked(); - - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; - - - /** - * The FormModule provides access to UI functionality like dialogs or widgets. - * - * Example (in Python) : - * \code - * import Kross - * forms = Kross.module("forms") - * dialog = forms.createDialog("My Dialog") - * dialog.setButtons("Ok|Cancel") - * page = dialog.addPage("Welcome","Welcome Page","document-open") - * label = forms.createWidget(page,"QLabel") - * label.text = "Hello World Label" - * if dialog.exec_loop(): - * forms.showMessageBox("Information", "Okay...", "The Ok-button was pressed") - * \endcode - */ - class FormModule: public QObject - { - Q_OBJECT - - public: - explicit FormModule(); - virtual ~FormModule(); - - public Q_SLOTS: - - /** - * \return the active modal widget. Modal widgets are special top-level - * widgets which are subclasses of QDialog and are modal. - */ - QWidget* activeModalWidget(); - - /** - * \return the application top-level window that has the keyboard input - * focus, or NULL if no application window has the focus. - */ - QWidget* activeWindow(); - - - /** - * \return i18n'ed version of the string - */ - QString tr(const QString& str); - - /** - * Show a messagebox. - * - * \param dialogtype The type of the dialog which could be one - * of the following; - * \li Sorry - * \li Error - * \li Information - * \li QuestionYesNo - * \li WarningYesNo - * \li WarningContinueCancel - * \li WarningYesNoCancel - * \li QuestionYesNoCancel - * \param caption The caption the messagedialog displays. - * \param message The message that is displayed in the messagedialog. - * \param details The optional details - * \return The buttoncode which chould be one of the following; - * \li Ok - * \li Cancel - * \li Yes - * \li No - * \li Continue - */ - QString showMessageBox(const QString& dialogtype, const QString& caption, const QString& message, const QString& details = QString()); - - /** - * Show a progressdialog to provide visible feedback on the progress - * of a slow operation. - * - * \param caption The caption the progressdialog displays. - * \param labelText The displayed label. - * \return The QProgressDialog widget instance. - */ - QWidget* showProgressDialog(const QString& caption, const QString& labelText); - - /** - * Create and return a new \a FormDialog instance. - * - * \param caption The displayed caption of the dialog. - */ - QWidget* createDialog(const QString& caption); - - /** - * Create and return a new \a FormAssistant instance. - * - * \param caption The displayed caption of the dialog. - */ - QWidget* createAssistant(const QString& caption); - - /** - * Create and return a new QWidget instance. - * - * \param parent the parent QWidget the new QWidget is a child of. - * \param layout the layout style the widget has. This could be one - * of the following strings; - * \li QVBoxLayout - * \li QHBoxLayout - * \li QStackedLayout - * \return the new QLayout instance or NULL. - */ - QObject* createLayout(QWidget* parent, const QString& layout); - - /** - * Create and return a new QWidget instance. - * - * \param parent the parent QWidget the new QWidget is a child of. - * \param className the name of the class that should be created - * and returned. For example "QLabel" or "QForm". - * \param name the objectName the new widget has. - * \return the new QWidget instance or NULL. - */ - QWidget* createWidget(const QString& className); - - /** - * Create and return a new QWidget instance. - * - * \param parent the parent QWidget the new QWidget is a child of. - * \param className the name of the class that should be created - * and returned. For example "QLabel" or "QForm". - * \param name the objectName the new widget has. - * \return the new QWidget instance or NULL. - */ - QWidget* createWidget(QWidget* parent, const QString& className, const QString& name = QString()); - - /** - * Create and return a new QWidget instance. - * - * \param parent the new QWidget is a child of parent. - * \param xml the UI XML string used to construct the new widget. - * \return the new QWidget instance or NULL. - */ - QWidget* createWidgetFromUI(QWidget* parent, const QString& xml); - - /** - * Create and return a new QWidget instance. - * - * \param parent the parent QWidget the new QWidget is a child of. - * \param filename the full filename of the UI file which is readed - * and its UI XML content is used to construct the new widget. - */ - QWidget* createWidgetFromUIFile(QWidget* parent, const QString& filename); - - /** - * Create and return a new \a FormFileWidget instance. - * - * \param parent the parent QWidget the new \a FormFileWidget instance - * is a child of. - * \param startDirOrVariable the start-directory or -variable. - * \return the new \a FormFileWidget instance or NULL. - */ - QWidget* createFileWidget(QWidget* parent, const QString& startDirOrVariable = QString()); - - /** - * Create and return a new \a FormListView instance. - * - * \param parent the parent QWidget the new \a FormListView instance - * is a child of. - * \return the new \a FormFileWidget instance or NULL. - */ - QWidget* createListView(QWidget* parent); - - /** - * Load and return a KPart component. - * \param parent The parent QWidget the KPart's widget will be child of. - * \param name The name of the KPart library like e.g. "libkhtmlpart". - * \param url Optional Url that should be opened on load. - */ - QObject* loadPart(QWidget* parent, const QString& name, const QUrl& url = QUrl()); - - /** - * Create and return a new \a QAction instance. - * - * \param parent the parent QObject the new \a QAction instance - * is a child of. - * \return the new \a QAction instance or NULL. - */ - QAction* createAction(QObject* parent); - - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; -} - -#endif - diff --git a/kross/modules/translation.cpp b/kross/modules/translation.cpp deleted file mode 100644 index 006d7358..00000000 --- a/kross/modules/translation.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/*************************************************************************** - * translation.cpp - * This file is part of the KDE project - * copyright (C)2008 by Dag Andersen - * - * 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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "core/kross_export.h" -#include "translation.h" - -#include -#include - -#include -#include -#include -#include -#include - -extern "C" -{ - KROSS_EXPORT QObject* krossmodule() - { - return new Kross::TranslationModule(); - } -} - -using namespace Kross; - - -namespace Kross { - - /// \internal d-pointer class. - class TranslationModule::Private - { - }; -} - -TranslationModule::TranslationModule() - : QObject() - , d( new Private() ) -{ -} - -TranslationModule::~TranslationModule() -{ - delete d; -} - -KLocalizedString TranslationModule::substituteArguments( const KLocalizedString &kls, const QVariantList &arguments, int max ) const -{ - KLocalizedString ls = kls; - int cnt = qMin( arguments.count(), max ); // QString supports max 99 - for ( int i = 0; i < cnt; ++i ) { - QVariant arg = arguments[i]; - switch ( arg.type() ) { - case QVariant::Int: ls = ls.subs(arg.toInt()); break; - case QVariant::UInt: ls = ls.subs(arg.toUInt()); break; - case QVariant::LongLong: ls = ls.subs(arg.toLongLong()); break; - case QVariant::ULongLong: ls = ls.subs(arg.toULongLong()); break; - case QVariant::Double: ls = ls.subs(arg.toDouble()); break; - default: ls = ls.subs(arg.toString()); break; - } - } - return ls; -} - -QString TranslationModule::i18n( const QString &text, const QVariantList &arguments ) const -{ - KLocalizedString ls = ki18n(text.toUtf8()); - return substituteArguments( ls, arguments ).toString(); -} - -QString TranslationModule::i18nc( const QString &context, const QString &text, const QVariantList &arguments ) const -{ - KLocalizedString ls = ki18nc(context.toUtf8(), text.toUtf8()); - return substituteArguments( ls, arguments ).toString(); -} - -QString TranslationModule::i18np( const QString &singular, const QString &plural, int number, const QVariantList &arguments ) const -{ - KLocalizedString ls = ki18np(singular.toUtf8(), plural.toUtf8()).subs(number); - return substituteArguments( ls, arguments, 98 ).toString(); -} - -QString TranslationModule::i18ncp( const QString &context, const QString &singular, const QString &plural, int number, const QVariantList &arguments ) const -{ - KLocalizedString ls = ki18ncp(context.toUtf8(), singular.toUtf8(), plural.toUtf8()).subs( number ); - return substituteArguments( ls, arguments, 98 ).toString(); -} - -#include "moc_translation.cpp" diff --git a/kross/modules/translation.h b/kross/modules/translation.h deleted file mode 100644 index 18dc79b8..00000000 --- a/kross/modules/translation.h +++ /dev/null @@ -1,72 +0,0 @@ -/*************************************************************************** - * translation.h - * This file is part of the KDE project - * copyright (C)2008 by Dag Andersen - * - * 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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_TRANSLATION_H -#define KROSS_TRANSLATION_H - -#include -#include -#include - -class KLocalizedString; - -namespace Kross { - - /** - * The TranslationModule provides access to KDE translation and internationalization facilities. - * - * Example (in Python) : - * \code - * import Kross - * t = Kross.module("kdetranslation") - * print t.i18n("This string can be translated") - * print t.i18ncp("Plural example", "%1 file not deleted %2", "%1 files not deleted %2", 3, [t.i18n("yesterday")]) - * \endcode - */ - class TranslationModule: public QObject - { - Q_OBJECT - - public: - explicit TranslationModule(); - virtual ~TranslationModule(); - - public Q_SLOTS: - /// Creates localized string from a given @p text. Substitute @p arguments (may be empty) - QString i18n( const QString &text, const QVariantList &arguments = QVariantList() ) const; - /// Creates localized string from a given @p text, with added context. Substitute @p arguments (may be empty) - QString i18nc( const QString &context, const QString &text, const QVariantList &arguments = QVariantList() ) const; - /// Creates localized string from a given @p plural and @p singular form dependent on @p number. Substitute @p arguments (may be empty) - QString i18np( const QString &singular, const QString &plural, int number, const QVariantList &arguments = QVariantList() ) const; - /// Creates localized string from a given @p plural and @p singular form dependent on @p number, with added context. Substitute @p arguments (may be empty) - QString i18ncp( const QString &context, const QString &singular, const QString &plural, int number, const QVariantList &arguments = QVariantList() ) const; - - protected: - KLocalizedString substituteArguments( const KLocalizedString &kls, const QVariantList &arguments, int max = 99 ) const; - - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; -} - -#endif - diff --git a/kross/qts/CMakeLists.txt b/kross/qts/CMakeLists.txt deleted file mode 100644 index 8d7ea4f6..00000000 --- a/kross/qts/CMakeLists.txt +++ /dev/null @@ -1,51 +0,0 @@ -include_directories( - ${CMAKE_SOURCE_DIR} - ${KDE4_KDECORE_INCLUDES} - ${KDE4_KDEUI_INCLUDES} - ${KDE4_KIO_INCLUDES} - ${CMAKE_SOURCE_DIR}/kross - ${CMAKE_BINARY_DIR}/kross -) - -########### next target ############### - -add_library(krossqtsplugin ${LIBRARY_TYPE} plugin.cpp) - -target_link_libraries(krossqtsplugin - ${KDE4_KDECORE_LIBS} - ${KDE4_KDEUI_LIBS} - ${QT_QTSCRIPT_LIBRARY} - ${QT_QTUITOOLS_LIBRARY} - krosscore -) - -set_target_properties(krossqtsplugin PROPERTIES - VERSION ${GENERIC_LIB_VERSION} - SOVERSION ${GENERIC_LIB_SOVERSION} -) - -install(TARGETS krossqtsplugin DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}/kde4/plugins/script) - -########### next target ############### - -# add_executable(krossqtstest main.cpp) -# target_link_libraries(krossqtstest ${KDE4_KDEUI_LIBS} krossqtsplugin ${QT_QTSCRIPT_LIBRARY}) -# set(krossqtsplugintest_SRCS main.cpp) -# target_link_libraries(krossqtsplugintest ${KDE4_KDECORE_LIBS}) -# add_executable(krossqtsplugintest ${krossqtsplugintest_SRCS}) -# #install(TARGETS krossqtsplugintest DESTINATION ${KDE4_BIN_INSTALL_DIR}) - -########### next target ############### - -set(krossqts_PART_SRCS interpreter.cpp script.cpp) - -kde4_add_plugin(krossqts ${krossqts_PART_SRCS}) - -target_link_libraries(krossqts - ${KDE4_KDEUI_LIBS} - ${KDE4_KDECORE_LIBS} - krosscore - ${QT_QTSCRIPT_LIBRARY} -) - -install(TARGETS krossqts DESTINATION ${KDE4_PLUGIN_INSTALL_DIR}) diff --git a/kross/qts/interpreter.cpp b/kross/qts/interpreter.cpp deleted file mode 100644 index baee6f80..00000000 --- a/kross/qts/interpreter.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/*************************************************************************** - * interpreter.cpp - * This file is part of the KDE project - * copyright (C)2007-2008 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "interpreter.h" -#include "script.h" - -// The in krossconfig.h defined KROSS_EXPORT_INTERPRETER macro defines an -// exported C function used as factory for Kross::EcmaInterpreter instances. -KROSS_EXPORT_INTERPRETER( Kross::EcmaInterpreter ) - -using namespace Kross; - -namespace Kross { - - /// \internal private d-pointer class. - class EcmaInterpreter::Private - { - public: - }; - -} - -EcmaInterpreter::EcmaInterpreter(Kross::InterpreterInfo* info) - : Kross::Interpreter(info) - , d(new Private()) -{ - //krossdebug( QString("EcmaInterpreter::EcmaInterpreter") ); -} - -EcmaInterpreter::~EcmaInterpreter() -{ - //krossdebug( QString("EcmaInterpreter::~EcmaInterpreter") ); - delete d; -} - -Kross::Script* EcmaInterpreter::createScript(Kross::Action* action) -{ - return new EcmaScript(this, action); -} - diff --git a/kross/qts/interpreter.h b/kross/qts/interpreter.h deleted file mode 100644 index 961c4d3f..00000000 --- a/kross/qts/interpreter.h +++ /dev/null @@ -1,71 +0,0 @@ -/*************************************************************************** - * interpreter.h - * This file is part of the KDE project - * copyright (C)2007-2008 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_QTS_INTERPRETER_H -#define KROSS_QTS_INTERPRETER_H - -#include -#include -#include -#include - -namespace Kross { - - class EcmaScript; - - /** - * The EcmaInterpreter class implements a \a Kross::Interpreter to provide - * a factory for \a EcmaScript instances. The interpreter is a singleton - * managed by Kross to share information between different script instances. - */ - class EcmaInterpreter : public Kross::Interpreter - { - friend class EcmaScript; - public: - - /** - * Constructor. - * - * \param info The \a Kross::InterpreterInfo instance that - * describes this interpreter. - */ - explicit EcmaInterpreter(Kross::InterpreterInfo* info); - - /** - * Destructor. - */ - virtual ~EcmaInterpreter(); - - /** - * Factory method to create a new \a EcmaScript instance. - * - * \param action The \a Kross::Action instance that decorates - * the script and contains details like the scripting code. - * \return a new \a EcmaScript instance. - */ - virtual Kross::Script* createScript(Kross::Action* action); - - private: - class Private; - Private* const d; - }; - -} - -#endif diff --git a/kross/qts/main.cpp b/kross/qts/main.cpp deleted file mode 100644 index f40c0444..00000000 --- a/kross/qts/main.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/*************************************************************************** - * main.cpp - * This file is part of the KDE project - * copyright (C)2006 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include -#include -#include -#include - -#include -#include -#include -// #include - -KApplication* app = 0; - -bool runScriptFile(QScriptEngine* engine, const QString& scriptfile) -{ - // Read the scriptfile - QFile f(scriptfile); - if(! f.exists()) { - qWarning() << "No such scriptfile:" << scriptfile; - return false; - } - if(! f.open(QIODevice::ReadOnly)) { - qWarning() << "Failed to open scriptfile:" << scriptfile; - return false; - } - QByteArray scriptcode = f.readAll(); - f.close(); - - // Execute the javascript code. - qDebug() << "Execute scriptfile:" << scriptfile; - QScriptValue v = engine->evaluate(scriptcode); - qDebug() << "Execute done. Result:" << v.toString(); - - return true; -} - -int main(int argc, char **argv) -{ - KAboutData about("kross",0,ki18n("Kross"),"0.1", - ki18n("KDE application to run Kross scripts."), - KAboutData::License_LGPL, - ki18n("(C) 2006 Sebastian Sauer"), - ki18n("Run Kross scripts."), - "http://kross.dipe.org","kross@dipe.org"); - about.addAuthor(ki18n("Sebastian Sauer"), ki18n("Author"), "mail@dipe.org"); - - // Initialize command line args - KCmdLineArgs::init(argc, argv, &about); - // Tell which options are supported and parse them. - KCmdLineOptions options; - options.add("+file", ki18n("Scriptfile")); - KCmdLineArgs::addCmdLineOptions(options); - KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); - - QStringList files; - for(int i = 0; i < args->count(); ++i) - files << args->arg(i); - - // If no options are defined. - if(files.count() < 1) { - qWarning() << "Syntax:" << KCmdLineArgs::appName() << "scriptfile1 [scriptfile2] [scriptfile3] ..."; - return -1; - } - - - app = new KApplication( /* GUIenabled */ true ); - QScriptEngine* engine = new QScriptEngine(); - engine->installTranslatorFunctions(); - QScriptValue global = engine->globalObject(); - - //qDebug()<<"QLibraryInfo::PluginsPath="<addLibraryPath("/home/kde4/kde4/lib/kde4/"); - - engine->importExtension("kross").toString(); - - foreach(const QString &file, files) - runScriptFile(engine, file); - - delete engine; - delete app; - return 0; -} diff --git a/kross/qts/plugin.cpp b/kross/qts/plugin.cpp deleted file mode 100644 index 4592c3ce..00000000 --- a/kross/qts/plugin.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/*************************************************************************** - * plugin.cpp - * This file is part of the KDE project - * copyright (C)2007 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "plugin.h" -#include "values_p.h" - -#include "../core/manager.h" - -#include - -using namespace Kross; - -Q_EXPORT_PLUGIN2(krossqtsplugin, Kross::EcmaPlugin) - -namespace Kross { - - /// \internal d-pointer class. - class EcmaPlugin::Private - { - public: - QScriptValue manager; - }; - -} - -EcmaPlugin::EcmaPlugin(QObject* parent) - : QScriptExtensionPlugin(parent) - , d(new Private) -{ - //qDebug()<globalObject(); - - //QScriptContext *context = engine->currentContext(); - d->manager = engine->newQObject( &Kross::Manager::self() ); - global.setProperty("Kross", d->manager); - - initializeCore(engine); - initializeGui(engine); - } - else - qDebug()< Plugin::keys"; - return QStringList() << "kross"; -} - diff --git a/kross/qts/plugin.h b/kross/qts/plugin.h deleted file mode 100644 index 65d16689..00000000 --- a/kross/qts/plugin.h +++ /dev/null @@ -1,89 +0,0 @@ -/*************************************************************************** - * plugin.h - * This file is part of the KDE project - * copyright (C)2007 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_ECMAPLUGIN_H -#define KROSS_ECMAPLUGIN_H - -#include -#include -//#include -//#include -//#include -//#include -//#include -//#include - -//#include "errorinterface.h" -//#include "childreninterface.h" - -#include - -#define KROSSQTSPLUGIN_EXPORT KROSS_EXPORT - -namespace Kross { - - /** - * Kross QtScript Extension that provides access to the Kross Scripting Framework - * within the QtScript scripting language. This EcmaPlugin does implement the - * extension named "kross". - */ - class KROSSQTSPLUGIN_EXPORT EcmaPlugin : public QScriptExtensionPlugin - { - public: - - /** - * Constructor. - * - * \param parent Optional QObject parent of this QObject. - */ - EcmaPlugin(QObject* parent = 0); - - /** - * Destructor. - */ - virtual ~EcmaPlugin(); - - /** - * Initializes this extension. - * - * \param key The key to differ between etensions. We provide - * the extension which key is "kross". - * \param engine The QScriptEngine instance. - */ - virtual void initialize(const QString& key, QScriptEngine* engine); - - /** - * Returns the list of keys this plugin supports. - * - * \return a QStringList with the single item "kross" to let - * QtScript know, that we provide an extension with that key. - */ - virtual QStringList keys() const; - - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; - -} - -#endif - diff --git a/kross/qts/script.cpp b/kross/qts/script.cpp deleted file mode 100644 index f7ae0616..00000000 --- a/kross/qts/script.cpp +++ /dev/null @@ -1,274 +0,0 @@ -/*************************************************************************** - * script.cpp - * This file is part of the KDE project - * copyright (C)2007-2008 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "script.h" - -#include -#include -#include -#include - -#include - -using namespace Kross; - -namespace Kross { - - /// \internal private d-pointer class. - class EcmaScript::Private - { - public: - EcmaScript* m_script; - QScriptEngine* m_engine; - QScriptValue m_kross; - QScriptValue m_self; - - explicit Private(EcmaScript* script) : m_script(script), m_engine(0) {} - ~Private() { delete m_engine; } - - bool init() { - if( m_script->action()->hadError() ) - m_script->action()->clearError(); - - delete m_engine; - m_engine = new QScriptEngine(); - m_engine->installTranslatorFunctions(); - - // load the Kross QScriptExtensionPlugin plugin that provides - // us a bridge between Kross and QtScript. See here plugin.h - m_engine->importExtension("kross"); - if( m_engine->hasUncaughtException() ) { - handleException(); - delete m_engine; - m_engine = 0; - return false; - } - - // the Kross QScriptExtensionPlugin exports the "Kross" property. - QScriptValue global = m_engine->globalObject(); - m_kross = global.property("Kross"); - Q_ASSERT( m_kross.isQObject() ); - Q_ASSERT( ! m_engine->hasUncaughtException() ); - - // Attach our Kross::Action instance to be able to access it in - // scripts. Just like at the Kjs-backend we publish our own - // action as "self". - m_self = m_engine->newQObject( m_script->action() ); - global.setProperty("self", m_self, QScriptValue::ReadOnly|QScriptValue::Undeletable); - - { // publish the global objects. - QHash< QString, QObject* > objects = Manager::self().objects(); - QHash< QString, QObject* >::Iterator it(objects.begin()), end(objects.end()); - for(; it != end; ++it) - global.setProperty(it.key(), m_engine->newQObject( it.value() ) ); - } - - { // publish the local objects. - QHash< QString, QObject* > objects = m_script->action()->objects(); - QHash< QString, QObject* >::Iterator it(objects.begin()), end(objects.end()); - for(; it != end; ++it) { - copyEnumsToProperties( it.value() ); - global.setProperty(it.key(), m_engine->newQObject( it.value() ) ); - } - } - - return ! m_engine->hasUncaughtException(); - } - - void copyEnumsToProperties(QObject* object) { - const QMetaObject* meta = object->metaObject(); - for (int i = 0; i < meta->enumeratorCount(); ++i) { - QMetaEnum metaenum = meta->enumerator(i); - for (int j = 0; j < metaenum.keyCount(); ++j) { - object->setProperty(metaenum.key(j), metaenum.value(j)); - } - } - } - - void handleException() { - Q_ASSERT( m_engine ); - Q_ASSERT( m_engine->hasUncaughtException() ); - const QString err = m_engine->uncaughtException().toString(); - const int linenr = m_engine->uncaughtExceptionLineNumber(); - const QString trace = m_engine->uncaughtExceptionBacktrace().join("\n"); - krossdebug( QString("%1, line:%2, backtrace:\n%3").arg(err).arg(linenr).arg(trace) ); - m_script->action()->setError(err, trace, linenr); - m_engine->clearExceptions(); - } - - void addObject(QObject* object, const QString& name = QString()) { - Q_ASSERT( m_engine ); - Q_ASSERT( ! m_engine->hasUncaughtException() ); - QScriptValue global = m_engine->globalObject(); - QScriptValue value = m_engine->newQObject(object); - global.setProperty(name.isEmpty() ? object->objectName() : name, value); - } - - void connectFunctions(ChildrenInterface* children) { - Q_ASSERT( m_engine ); - Q_ASSERT( ! m_engine->hasUncaughtException() ); - QString eval; - QScriptValue global = m_engine->globalObject(); - QHashIterator< QString, ChildrenInterface::Options > it( children->objectOptions() ); - while(it.hasNext()) { - it.next(); - if( it.value() & ChildrenInterface::AutoConnectSignals ) { - QObject* sender = children->object(it.key()); - if( ! sender ) - continue; - QScriptValue obj = m_engine->globalObject().property(it.key()); - if( ! obj.isQObject() ) - continue; - const QMetaObject* mo = sender->metaObject(); - const int count = mo->methodCount(); - for(int i = 0; i < count; ++i) { - QMetaMethod mm = mo->method(i); - const QString signature = mm.signature(); - const QString name = signature.left(signature.indexOf('(')); - if( mm.methodType() == QMetaMethod::Signal ) { - QScriptValue func = global.property(name); - if( ! func.isFunction() ) { - //krossdebug( QString("EcmaScript::connectFunctions No function to connect with %1.%2").arg(it.key()).arg(name) ); - continue; - } - krossdebug( QString("EcmaScript::connectFunctions Connecting with %1.%2").arg(it.key()).arg(name) ); - eval += QString("try { %1.%2.connect(%3); } catch(e) { print(e); }\n").arg(it.key()).arg(name).arg(name); - } - } - } - } - Q_ASSERT( ! m_engine->hasUncaughtException() ); - if( ! eval.isNull() ) { - m_engine->evaluate(eval); - Q_ASSERT( ! m_engine->hasUncaughtException() ); - } - } - - }; - -} - -EcmaScript::EcmaScript(Interpreter* interpreter, Action* action) : Script(interpreter, action), d(new Private(this)) -{ - //krossdebug( QString("EcmaScript::EcmaScript") ); -} - -EcmaScript::~EcmaScript() -{ - //krossdebug( QString("EcmaScript::~EcmaScript") ); - delete d; -} - -void EcmaScript::execute() -{ - if( ! d->init() ) { - d->handleException(); - return; - } - - QString scriptCode = action()->code(); - if( scriptCode.startsWith(QLatin1String("#!")) ) // remove optional shebang-line - scriptCode.remove(0, scriptCode.indexOf('\n')); - - const QString fileName = action()->file().isEmpty() ? action()->name() : action()->file(); - - //krossdebug( QString("EcmaScript::execute fileName=%1 scriptCode=\n%2").arg(fileName).arg(scriptCode) ); - - Q_ASSERT( d->m_engine ); - - if( d->m_engine->hasUncaughtException() ) { - d->m_engine->clearExceptions(); - } - - d->m_engine->evaluate( scriptCode, fileName ); - - if( d->m_engine->hasUncaughtException() ) { - d->handleException(); - return; - } - - //d->connectFunctions( &Manager::self() ); - d->connectFunctions( action() ); -} - -QStringList EcmaScript::functionNames() -{ - if( ! d->m_engine && ! d->init() ) { - d->handleException(); - return QStringList(); - } - QStringList names; - QScriptValueIterator it( d->m_engine->globalObject() ); - while( it.hasNext() ) { - it.next(); - if( it.value().isFunction() ) { - names << it.name(); - } - } - return names; -} - -QVariant EcmaScript::callFunction(const QString& name, const QVariantList& args) -{ - if( ! d->m_engine && ! d->init() ) { - d->handleException(); - return QVariant(); - } - - QScriptValue obj = d->m_engine->globalObject(); - QScriptValue function = obj.property(name); - if( ! function.isFunction() ) { - QString err = QString("No such function '%1'").arg(name); - krosswarning( QString("EcmaScript::callFunction %1").arg(err) ); - setError(err); - return QVariant(); - } - - QScriptValueList arguments; - foreach(const QVariant &v, args) - arguments << d->m_engine->toScriptValue(v); - QScriptValue result = function.call(obj, arguments); - if( d->m_engine->hasUncaughtException() ) { - d->handleException(); - return QVariant(); - } - return result.toVariant(); -} - -QVariant EcmaScript::evaluate(const QByteArray& code) -{ - if( ! d->m_engine && ! d->init() ) { - d->handleException(); - return QVariant(); - } - - QScriptValue result = d->m_engine->evaluate(code); - if( d->m_engine->hasUncaughtException() ) { - d->handleException(); - return QVariant(); - } - return result.toVariant(); -} - -QObject* EcmaScript::engine() const -{ - return d->m_engine; -} - -#include "moc_script.cpp" diff --git a/kross/qts/script.h b/kross/qts/script.h deleted file mode 100644 index d8085871..00000000 --- a/kross/qts/script.h +++ /dev/null @@ -1,99 +0,0 @@ -/*************************************************************************** - * script.h - * This file is part of the KDE project - * copyright (C)2007-2008 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_QTS_SCRIPT_H -#define KROSS_QTS_SCRIPT_H - -#include -#include -#include -#include -#include -#include - -namespace Kross { - - /** - * The EcmaScript class implements a \a Kross::Script to handle - * a single script. Each script and script file will have its - * own \a EcmaScript instance as container for a Ecma QtScript - * that is managed by the \a Kross::Action class. - */ - class EcmaScript : public Kross::Script - { - Q_OBJECT - public: - - /** - * Constructor. - * - * \param interpreter The \a EcmaInterpreter instance this - * script belongs to. - * \param action The \a Kross::Action instance that contains - * details about the script and that decorates this script. - */ - EcmaScript(Kross::Interpreter* interpreter, Kross::Action* action); - - /** - * Destructor. - */ - virtual ~EcmaScript(); - - public Q_SLOTS: - - /** - * Executes the script. - */ - virtual void execute(); - - /** - * \return a list of function-names. - */ - virtual QStringList functionNames(); - - /** - * Execute a function. - * - * \param name The name of the function that should be called. - * \param args The optional arguments for the function. - * \return The return value of the function. - */ - virtual QVariant callFunction(const QString& name, const QVariantList& args = QVariantList()); - - /** - * Evaluate some scripting code. - * - * \param code The scripting code to evaluate. - * \return The return value of the evaluation. - */ - virtual QVariant evaluate(const QByteArray& code); - - /** - * \return the internal used QScriptEngine instance. - */ - QObject* engine() const; - - private: - class Private; - Private* const d; - }; - -} - -#endif diff --git a/kross/qts/test.es b/kross/qts/test.es deleted file mode 100644 index 102f4fd3..00000000 --- a/kross/qts/test.es +++ /dev/null @@ -1,122 +0,0 @@ -// #!/usr/bin/env kross - -/* - This function does print some general information about - Kross to stdout. -*/ -function printInfos() -{ - function inspect(v) { - var items = new Array(); - for(i in v) - items.push(i); - return items; - } - - // print the items the Kross object provides - print(Kross + " [" + inspect(Kross) + "]\n"); - - // print the items the Kross.self object provides - //print(Kross.self + " [" + inspect(Kross.self) + "]\n"); - - // print the list of supported interpreters - print("interpreters=" + Kross.interpreters() + "\n"); -} - -/* - This function does execute Python scripting code using - the Kross Scripting Framework. -*/ -function executePythonCode(PythonScriptCode) -{ - // create an action-instance which is our script - var action = Kross.action("MyPythonScript"); - // publish our action instance as "MyAction" - action.addQObject(action, "MyAction"); - // set the name of the used interpreter. - action.setInterpreter("python"); - - // set the python scripting code we like to execute. - //action.setCode( Kross.QByteArray(PythonScriptCode) ); - action.setCode( PythonScriptCode ); - - // finally execute the script - action.trigger(); -} - -/* - This function does execute a Python scripting file using - the Kross Scripting Framework. -*/ -function executePythonFile(PythonFileName) -{ - // create an action-instance which is our script - var action = Kross.action(PythonFileName); - // publish our action instance as "MyAction" - action.addQObject(action, "MyAction"); - // set the scripting file that should be executed - action.setFile(PythonFileName); - // finally execute the script - action.trigger(); -} - -/* - This function does show a dialog using the Kross forms-module - shipped together with kross in kdelibs. The forms module does - provide us some high-level functionality like KPageDialog, - KFileWidget and the UI-loader. All the functionality provided - within that module is accessible from within all supported - scripting languages. -*/ -function showKrossForms() -{ - var krossforms = Kross.module("forms"); - var dialog = krossforms.createDialog("My Dialog"); - dialog.setButtons("Ok|Cancel"); - dialog.setFaceType("List"); //Auto Plain List Tree Tabbed - var mypage = dialog.addPage("My Page","This is my page","document-save"); - var lst = new QListWidget(mypage); - var btn = new QPushButton(mypage); - dialog.exec_loop(); -} - -/* - This function does show a dialog using the QtScript - functionality. -*/ -function showDialog() -{ - var dialog = new QDialog(); - layout = new QVBoxLayout(dialog); - - var otherlayout = new QHBoxLayout(); - var brw = new QTextBrowser(dialog); - brw.html = "Some HTML text"; - otherlayout.addWidget(brw); - var lst = new QListWidget(dialog); - otherlayout.addWidget(lst); - layout.addLayout(otherlayout); - - var gridlayout = new QGridLayout(); - var lbl = new QLabel(dialog); - lbl.text = "First Label"; - gridlayout.addWidget(lbl, 0, 0); - var btn = new QPushButton(dialog); - btn.text = "First Button"; - gridlayout.addWidget(btn, 0, 1); - var lbl = new QLabel(dialog); - lbl.text = "Second Label"; - gridlayout.addWidget(lbl, 1, 0); - var btn = new QPushButton(dialog); - btn.text = "Second Button"; - gridlayout.addWidget(btn, 1, 1); - layout.addLayout(gridlayout); - - dialog.exec(); -} - -printInfos(); -executePythonCode("import MyAction ; print 'This is Python. name=>',MyAction.name()"); -//executePythonFile("/home/kde4/svn/_src/kdelibs/kross/ext/test.py"); -showKrossForms(); -//showDialog(); diff --git a/kross/qts/values_p.h b/kross/qts/values_p.h deleted file mode 100644 index 6d9699b3..00000000 --- a/kross/qts/values_p.h +++ /dev/null @@ -1,304 +0,0 @@ -/*************************************************************************** - * plugin.cpp - * This file is part of the KDE project - * copyright (C)2007 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "plugin.h" - -#include "../core/manager.h" -#include "../core/object.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -using namespace Kross; - -namespace Kross { - - /** - * The EcmaObject implements QScriptClass and Kross::Object to provide - * custom behavior to QtScript objects. - */ - class EcmaObject : public QScriptClass, public Kross::Object - { - public: - explicit EcmaObject(QScriptEngine* engine, const QScriptValue& object = QScriptValue()) - : QScriptClass(engine), Kross::Object(), m_object(object) {} - virtual ~EcmaObject() {} - virtual QString name() const { return "KrossObject"; } - virtual QScriptValue prototype() const { return m_object; } - - virtual QVariant callMethod(const QString& name, const QVariantList& args = QVariantList()) - { - QScriptValue function = m_object.property(name); - if( ! function.isFunction() ) { - krosswarning( QString("EcmaScript::callFunction No such function \"%1\"").arg(name) ); - if( QScriptContext* context = engine()->currentContext() ) - context->throwError(QScriptContext::ReferenceError, i18n("No such function \"%1\"", name)); - return QVariant(); - } - QScriptValueList arguments; - foreach(const QVariant &v, args) - arguments << engine()->toScriptValue(v); - QScriptValue result = function.call(m_object, arguments); - return result.toVariant(); - } - - virtual QStringList methodNames() - { - QStringList methods; - QScriptValueIterator it( m_object ); - while( it.hasNext() ) { - it.next(); - if( it.value().isFunction() ) - methods << it.name(); - } - return methods; - } - - private: - QScriptValue m_object; - }; - - QScriptValue toByteArray(QScriptEngine *e, const QByteArray &ba) { - return ba.isNull() ? e->nullValue() : e->newVariant(ba); - } - void fromByteArray(const QScriptValue &v, QByteArray &ba) { - ba = v.isNull() ? QByteArray() : v.toString().toUtf8(); - } - - QScriptValue toUrl(QScriptEngine *e, const QUrl &url) { - return e->newVariant( url.toString() ); - } - void fromUrl(const QScriptValue &v, QUrl &url) { - url.setUrl( v.toString() ); - } - - QScriptValue toKUrl(QScriptEngine *e, const KUrl &url) { - return e->newVariant( url.url() ); - } - void fromKUrl(const QScriptValue &v, KUrl &url) { - url.setUrl( v.toString() ); - } - - QScriptValue toColor(QScriptEngine *e, const QColor &c) { - return c.isValid() ? e->newVariant(c.name()) : e->nullValue(); - } - void fromColor(const QScriptValue &v, QColor &c) { - c.setNamedColor( v.isNull() ? QString() : v.toString() ); - } - - QScriptValue toRect(QScriptEngine *e, const QRect &r) { - return e->toScriptValue( QVariantList() << r.x() << r.y() << r.width() << r.height() ); - } - void fromRect(const QScriptValue &v, QRect &r) { - r = v.isArray() ? QRect(v.property(0).toInt32(),v.property(1).toInt32(),v.property(2).toInt32(),v.property(3).toInt32()) : QRect(); - } - QScriptValue toRectF(QScriptEngine *e, const QRectF &r) { - return e->toScriptValue( QVariantList() << r.x() << r.y() << r.width() << r.height() ); - } - void fromRectF(const QScriptValue &v, QRectF &r) { - r = v.isArray() ? QRectF(v.property(0).toNumber(),v.property(1).toNumber(),v.property(2).toNumber(),v.property(3).toNumber()) : QRectF(); - } - - QScriptValue toPoint(QScriptEngine *e, const QPoint &p) { - return e->toScriptValue( QVariantList() << p.x() << p.y() ); - } - void fromPoint(const QScriptValue &v, QPoint &p) { - p = v.isArray() ? QPoint(v.property(0).toInt32(),v.property(1).toInt32()) : QPoint(); - } - QScriptValue toPointF(QScriptEngine *e, const QPointF &p) { - return e->toScriptValue( QVariantList() << p.x() << p.y() ); - } - void fromPointF(const QScriptValue &v, QPointF &p) { - p = v.isArray() ? QPointF(v.property(0).toNumber(),v.property(1).toNumber()) : QPointF(); - } - - QScriptValue toSize(QScriptEngine *e, const QSize &s) { - return e->toScriptValue( QVariantList() << s.width() << s.height() ); - } - void fromSize(const QScriptValue &v, QSize &s) { - s = v.isArray() ? QSize(v.property(0).toInt32(),v.property(1).toInt32()) : QSize(); - } - QScriptValue toSizeF(QScriptEngine *e, const QSizeF &s) { - return e->toScriptValue( QVariantList() << s.width() << s.height() ); - } - void fromSizeF(const QScriptValue &v, QSizeF &s) { - s = v.isArray() ? QSizeF(v.property(0).toNumber(),v.property(1).toNumber()) : QSizeF(); - } - - /* - QScriptValue toVariantList(QScriptEngine *e, const QVariantList &l) { - const int len = l.size(); - QScriptValue a = e->newArray(len); - for(int i = 0; i < len; ++i) - a.setProperty(i, e->toScriptValue(l[i])); - return a; - } - void fromVariantList(const QScriptValue &v, QVariantList &l) { - l.clear(); - const int len = v.isArray() ? v.property("length").toInt32() : 0; - for(int i = 0; i < len; ++i) - l << v.property(i).toVariant(); - } - */ - - QScriptValue toObjPtr(QScriptEngine *e, const Kross::Object::Ptr &ptr) { - const EcmaObject* obj = dynamic_cast( ptr.data() ); - return obj ? obj->prototype() : e->nullValue(); - } - void fromObjPtr(const QScriptValue &v, Kross::Object::Ptr &ptr) { - ptr = new EcmaObject(v.engine(), v); - } - - QScriptValue createWidget(QScriptContext *context, QScriptEngine *engine) { - const QString widgetname = context->callee().prototype().property("className").toString(); - Q_ASSERT( ! widgetname.isEmpty() ); - QWidget *parent = qscriptvalue_cast(context->argument(0)); - QUiLoader loader; - QWidget *widget = loader.createWidget(widgetname, parent); - if( ! widget ) - return context->throwError(QScriptContext::TypeError, QString("No such QWidget \"%1\"").arg(widgetname)); - if( parent && parent->layout() ) - parent->layout()->addWidget(widget); - QScriptEngine::ValueOwnership owner = parent ? QScriptEngine::QtOwnership : QScriptEngine::ScriptOwnership; - QScriptValue result = engine->newQObject(widget, owner); - //result.setPrototype(context->callee().prototype()); - return result; - } - - QScriptValue addWidgetLayout(QScriptContext *c, QScriptEngine *engine) { - if( QLayout *layout = dynamic_cast( qscriptvalue_cast(c->thisObject()) ) ) { - QGridLayout *gridLayout = dynamic_cast(layout); - QObject *obj = qscriptvalue_cast( c->argument(0) ); - if( QWidget *w = dynamic_cast(obj) ) { - if( gridLayout ) - gridLayout->addWidget(w, c->argument(1).toInt32(), c->argument(2).toInt32(), (Qt::Alignment)c->argument(3).toInt32()); - else - layout->addWidget(w); - } - else if( QLayout *l = dynamic_cast( qscriptvalue_cast(c->argument(0)) ) ) { - if( gridLayout ) - gridLayout->addLayout(l, c->argument(1).toInt32(), c->argument(2).toInt32(), (Qt::Alignment)c->argument(3).toInt32()); - else if( QBoxLayout *bl = dynamic_cast(layout) ) - bl->addLayout(l); - } - } - return engine->nullValue(); - } - QScriptValue createLayout(QScriptContext *context, QScriptEngine *engine, QLayout *layout) { - QObject *parent = qscriptvalue_cast(context->argument(0)); - if( QWidget *parentWidget = dynamic_cast(parent) ) - parentWidget->setLayout(layout); - else if( QBoxLayout *parentLayout = dynamic_cast(parent) ) - parentLayout->addLayout(layout); - QScriptValue obj = engine->newQObject(layout); - obj.setProperty("addWidget", engine->newFunction(addWidgetLayout)); - obj.setProperty("addLayout", engine->newFunction(addWidgetLayout)); - return obj; - } - QScriptValue createVBoxLayout(QScriptContext *context, QScriptEngine *engine) { - return createLayout(context, engine, new QVBoxLayout()); - } - QScriptValue createHBoxLayout(QScriptContext *context, QScriptEngine *engine) { - return createLayout(context, engine, new QHBoxLayout()); - } - QScriptValue createGridLayout(QScriptContext *context, QScriptEngine *engine) { - return createLayout(context, engine, new QGridLayout()); - } - QScriptValue includeFunction(QScriptContext *context, QScriptEngine *engine) { - if (context->argumentCount() < 1) - return engine->nullValue(); - return engine->importExtension(context->argument(0).toString()); - } - - /** - * Initialize some core functionality like common used types we like - * to use within scripts. - */ - void initializeCore(QScriptEngine *engine) { - QScriptValue global = engine->globalObject(); - - // compatibility to kjs/kjsembed - if( ! global.property("println").isValid() ) - global.setProperty("println", global.property("print")); - - // register common used types - qScriptRegisterMetaType< QByteArray >(engine, toByteArray, fromByteArray); - qScriptRegisterMetaType< QUrl >(engine, toUrl, fromUrl); - qScriptRegisterMetaType< KUrl >(engine, toKUrl, fromKUrl); - qScriptRegisterMetaType< QColor >(engine, toColor, fromColor); - qScriptRegisterMetaType< QRect >(engine, toRect, fromRect); - qScriptRegisterMetaType< QRectF >(engine, toRectF, fromRectF); - qScriptRegisterMetaType< QPoint >(engine, toPoint, fromPoint); - qScriptRegisterMetaType< QPointF >(engine, toPointF, fromPointF); - qScriptRegisterMetaType< QSize >(engine, toSize, fromSize); - qScriptRegisterMetaType< QSizeF >(engine, toSizeF, fromSizeF); - - // we should probably go with an own wrapper for QVariant/QObject... - //qScriptRegisterMetaType< QVariant >(engine, toVariant, fromVariant); - //qScriptRegisterMetaType< QVariantList >(engine, toVariantList, fromVariantList); - - // register the Kross::Object::Ptr wrapper - qScriptRegisterMetaType< Kross::Object::Ptr >(engine, toObjPtr, fromObjPtr); - - // register the include function that allows to importExtension - global.setProperty("include", engine->newFunction(includeFunction)); - } - - /** - * Initialize GUI functionality like widgets the QUiLoader provides - * and some layout-managers. - */ - void initializeGui(QScriptEngine *engine) { - QScriptValue global = engine->globalObject(); - - // register UI widgets - QUiLoader loader; - foreach(const QString &widgetname, loader.availableWidgets()) { - QScriptValue proto = engine->newObject(); - proto.setProperty("className", QScriptValue(engine, widgetname)); - QScriptValue func = engine->newFunction(createWidget); - func.setPrototype(proto); - global.setProperty(widgetname, func); - } - - // register layouts - global.setProperty("QVBoxLayout", engine->newFunction(createVBoxLayout)); - global.setProperty("QHBoxLayout", engine->newFunction(createHBoxLayout)); - global.setProperty("QGridLayout", engine->newFunction(createGridLayout)); - } - -} diff --git a/kross/test/CMakeLists.txt b/kross/test/CMakeLists.txt deleted file mode 100644 index 9a8973a2..00000000 --- a/kross/test/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -include_directories(${KDE4_KIO_INCLUDES}) - -set(krosstest_SRCS - testobject.cpp - main.cpp -) - -kde4_add_manual_test(krosstest ${krosstest_SRCS}) - -target_link_libraries(krosstest ${KDE4_KDEUI_LIBS} krosscore) diff --git a/kross/test/main.cpp b/kross/test/main.cpp deleted file mode 100644 index c864ac54..00000000 --- a/kross/test/main.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/*************************************************************************** - * main.cpp - * This file is part of the KDE project - * copyright (C)2004-2007 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "testobject.h" - -// Kross -#include "../core/action.h" -#include "../core/interpreter.h" -#include "../core/manager.h" -#include "../core/wrapperinterface.h" - -// Qt - -#include -#include -#include - -// KDE -#include -#include -#include -#include -#include -#include - -// for std namespace -#include -#include - -#define ERROR_OK 0 -#define ERROR_HELP -1 -#define ERROR_NOSUCHFILE -2 -#define ERROR_OPENFAILED -3 -#define ERROR_NOINTERPRETER -4 -#define ERROR_EXCEPTION -6 - -KApplication *app = 0; - -QString getInterpreterName(const QString& scriptfile) -{ - Kross::InterpreterInfo* interpreterinfo = Kross::Manager::self().interpreterInfo( Kross::Manager::self().interpreternameForFile(scriptfile) ); - return interpreterinfo ? interpreterinfo->interpreterName() : QString(); -} - -int readFile(const QString& scriptfile, QByteArray& content) -{ - QFile f(scriptfile); - if(! f.exists()) { - std::cerr << "No such scriptfile: " << scriptfile.toLatin1().data() << std::endl; - return ERROR_NOSUCHFILE; - } - if(! f.open(QIODevice::ReadOnly)) { - std::cerr << "Failed to open scriptfile: " << scriptfile.toLatin1().data() << std::endl; - return ERROR_OPENFAILED; - } - content = f.readAll(); - f.close(); - return ERROR_OK; -} - -int runScriptFile(const QString& scriptfile) -{ - // Read the scriptfile - QByteArray scriptcode; - int result = readFile(scriptfile, scriptcode); - if(result != ERROR_OK) - return result; - - // Determinate the matching interpreter - QString interpretername = getInterpreterName(scriptfile); - if( interpretername.isNull() ) { - std::cerr << "No interpreter for scriptfile: " << scriptfile.toLatin1().data() << std::endl; - return ERROR_NOINTERPRETER; - } - - // First we need a Action and fill it. - Kross::Action* action = new Kross::Action(0 /*no parent*/, KUrl(scriptfile)); - action->setObjectName("MyAction"); - action->setInterpreter( interpretername ); - action->setCode( scriptcode ); - - // Create the testobject instances. - TestObject* testobj3 = new TestObject(action, "TestObject3"); - TestObject* testobj4 = new TestObject(action, "TestObject4"); - - // Publish other both testobject instance to the script. - action->addObject( testobj3, "TestObject3", Kross::ChildrenInterface::AutoConnectSignals ); - action->addObject( testobj4, "TestObject4" ); - - // Now execute the Action. - std::cout << "Execute scriptfile " << scriptfile.toLatin1().data() << " now" << std::endl; - action->trigger(); - std::cout << "Execution of scriptfile " << scriptfile.toLatin1().data() << " done" << std::endl; - - /* - if(action->hadException()) { - // We had an exception. - QString errormessage = action->getException()->getError(); - QString tracedetails = action->getException()->getTrace(); - std::cerr << QString("%2\n%1").arg(tracedetails).arg(errormessage).toLatin1().data() << std::endl; - return ERROR_EXCEPTION; - } - */ - - delete action; - return ERROR_OK; -} - -QVariant OtherObjectHandler(void* ptr) -{ - OtherObject* obj = static_cast(ptr); - kDebug()<<"OtherObjectHandler objectName="<<(obj ? obj->objectName() : "NULL"); - OtherObjectWrapper* wrapper = new OtherObjectWrapper(obj); - QVariant r; - r.setValue( (QObject*) wrapper ); - return r; -} - -int main(int argc, char **argv) -{ - int result = 0; - - KAboutData about("krosstest", - 0, - ki18n("KrossTest"), - "0.1", - ki18n("KDE application to test the Kross framework."), - KAboutData::License_LGPL, - ki18n("(C) 2005-2007 Sebastian Sauer"), - ki18n("Test the Kross framework!"), - "http://kross.dipe.org", - "kross@dipe.org"); - about.addAuthor(ki18n("Sebastian Sauer"), ki18n("Author"), "mail@dipe.org"); - - KCmdLineOptions options; - options.add("+file", ki18n("Scriptfile")); - //options.add("functionname ", ki18n("Execute the function in the defined script file.")); - //options.add("functionargs ", ki18n("List of arguments to pass to the function on execution.")); - - KCmdLineArgs::init(argc, argv, &about); - KCmdLineArgs::addCmdLineOptions(options); - - KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); - - QStringList scriptfiles; - for(int i = 0; i < args->count(); i++) - scriptfiles.append( args->arg(i) ); - - if(scriptfiles.count() < 1) { - std::cerr << "No scriptfile to execute defined. See --help" << std::endl; - return ERROR_NOSUCHFILE; - } - - // init - app = new KApplication(); - TestObject* testobj1 = new TestObject(0, "TestObject1"); - TestObject* testobj2 = new TestObject(0, "TestObject2"); - Kross::Manager::self().addObject( testobj1 ); - Kross::Manager::self().addObject( testobj2 ); - - Kross::Manager::self().registerMetaTypeHandler("OtherObject*", OtherObjectHandler); - - foreach(const QString &file, scriptfiles) { - result = runScriptFile(file); - if(result != ERROR_OK) - break; - } - - // finish - delete testobj1; - delete testobj2; - delete app; - - kDebug() << "DONE!!!"; - return result; -} diff --git a/kross/test/profile.py b/kross/test/profile.py deleted file mode 100755 index a56ec941..00000000 --- a/kross/test/profile.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env kross - -""" - This Python script is used as performance-tester and profiler - for the Kross scripting framework. -""" - -def runner(): - import MyTestObject1 - testobject1 = MyTestObject1 - - def test1(): - """ Ok. It's a stupid test. But well... :) """ - print "test1" - for i in range(300000): - testobject1.func_uint_uint(233) - testobject1.func_qstring_qstring("Some string") - - test1() - -import profile -__main__.runner=runner -profile.run("runner()") diff --git a/kross/test/testguiform.py b/kross/test/testguiform.py deleted file mode 100644 index ee0b694b..00000000 --- a/kross/test/testguiform.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env kross - -import Kross, os - -#window = Kross.activeWindow() -#if window == None: -# print "Creating new dialog" -# window = Kross.createDialog("TestGuiFormDialog") -#else: -# print "Using active window" - -print "1................" -forms = Kross.module("forms") -print "2................" -print "===================================> %s" % forms -print dir(forms) - -dialog = forms.createDialog("TestGuiFormDialog") -dialog.setButtons("Ok|Cancel") -dialog.setFaceType("List") #Auto Plain List Tree Tabbed - -#print "===> dialog %s %s" % (dialog,dir(dialog)) - -#page0 = dialog.addPage("Welcome","Welcome","about_kde") -##widget0 = Kross.forms().createWidget(page0, 'QWidget', 'MyForm1', {}) -##widget0label = Kross.forms().createWidget(page0, 'QLabel', 'label', {'text':'Testlabel'}) -#widget0 = Kross.forms().createWidgetFromUI(page0, - #'' - #' Form' - #' ' - #' ' - #' ' - #' 9' - #' ' - #' ' - #' 6' - #' ' - #' ' - #' ' - #' ' - #' Testlabel' - #' ' - #' ' - #' Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop' - #' ' - #' ' - #' ' - #' ' - #' ' - #'') - -page3 = dialog.addPage("Options","Options","configure") -uifile = os.path.join( self.currentPath(), "testguiform.ui" ) -widget3 = forms.createWidgetFromUIFile(page3, uifile) - -page1 = dialog.addPage("File","Import From Image File","fileopen") -widget1 = forms.createFileWidget(page1, "kfiledialog:///mytestthingy1") -#widget1.setMode("Saving") -widget1.setMode("Opening") -widget1.setFilter("*.cpp|C++ Source Files\n*.h|Header files") - -#optionspage = dialog.addPage("Options","Import Options","configure") -#optionswidget = Kross.forms().createWidgetFromUIFile(optionspage, "/home/kde4/koffice/krita/plugins/viewplugins/scripting/scripts/pilimport.ui") - -#w = widget #widget["KFileDialog::mainWidget"] -#print dir(w) -#for idx in range( len(w) ): -# obj = w[ idx:idx ][0] -# print "...... idx=%s obj=%s name=%s class=%s" % ( idx , obj , obj.__name__ , obj.__class__ ) - -##combo = dialog["QWidget"]["QWidget"]["QGroupBox"]["QComboBox"] -#combo = widget["QGroupBox"]["QComboBox"] -#combo.setEditText("Hello World") - -print "######################################## self.currentPath=\"%s\"" % self.currentPath() - -result = dialog.exec_loop() -if result: - print "===> result=%s" % dialog.result() - - def getOption(widget, optionname, optionlist): - try: - childwidget = widget[ optionname ] - for option in optionlist: - radiobutton = childwidget[ option ] - if radiobutton.checked: - return option - except: - import sys, traceback - raise "\n".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ) - raise "No such option \"%s\"" % optionname - - colorspace = getOption(optionswidget, "Colorspace", ["RGB","CMYK"]) - destination = getOption(optionswidget, "Destination", ["NewLayer","ActiveLayer"]) - size = getOption(optionswidget, "Size", ["Resize","Scale","Ignore"]) - - print "===> colorspace=%s destination=%s size=%s" % (colorspace,destination,size) - - #destinationwidget = optionswidget["Destination"] - #if destinationwidget["NewLayer"].checked: - #elif destinationwidget["ActiveLayer"].checked: - #else: - - #sizebox = optionswidget["Size"] - #if sizebox["Resize"].checked: - #elif sizebox["Scale"].checked: - #elif sizebox["Ignore"].checked: - #else: - - #w = csbox - #for idx in range( len(w) ): - # obj = w[ idx:idx ][0] - # print "...... idx=%s obj=%s name=%s class=%s" % ( idx , obj , obj.__name__ , obj.__class__ ) - -print dir(dialog) -dialog.delayedDestruct(); diff --git a/kross/test/testguiform.rb b/kross/test/testguiform.rb deleted file mode 100644 index e3a6e159..00000000 --- a/kross/test/testguiform.rb +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env kross - -require 'Kross' - -dialog = Kross.createDialog("TestGuiFormDialog") -form = dialog -print "form %s %s" % (form,dir(form)) -form.loadUiFile("/home/kde4/koffice/libs/kross/test/testguiform.ui") -form.exec_loop() diff --git a/kross/test/testguiform.ui b/kross/test/testguiform.ui deleted file mode 100644 index b36ea162..00000000 --- a/kross/test/testguiform.ui +++ /dev/null @@ -1,255 +0,0 @@ - - Form - - - - 0 - 0 - 442 - 334 - - - - - 400 - 0 - - - - - 9 - - - 6 - - - - - 0 - - - 6 - - - - - - 7 - 5 - 1 - 0 - - - - File: - - - - 9 - - - 6 - - - - - 0 - - - 6 - - - - - - 5 - 0 - 1 - 0 - - - - true - - - - - - - ... - - - - - - - - - - - - - 5 - 5 - 1 - 0 - - - - GroupBox 1 - - - - 9 - - - 6 - - - - - 0 - - - 6 - - - - - - 1 - 0 - 1 - 0 - - - - CheckBox - - - - - - - - 1 - 0 - 1 - 0 - - - - CheckBox - - - - - - - - - - - - - 5 - 5 - 1 - 0 - - - - Other GroupBox - - - - 9 - - - 6 - - - - - 0 - - - 6 - - - - - - 1 - 0 - 1 - 0 - - - - RadioButton - - - - - - - - 1 - 0 - 1 - 0 - - - - RadioButton - - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - action1 - - - - - - - pushButton - clicked() - actionAction1 - trigger() - - - 338 - 55 - - - -1 - -1 - - - - - diff --git a/kross/test/testguiqt.py b/kross/test/testguiqt.py deleted file mode 100644 index ad651102..00000000 --- a/kross/test/testguiqt.py +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env krosstest - -#import qt -#class Button(qt.QPushButton): - #def __init__(self, *args): - #apply(qt.QPushButton.__init__, (self,) + args) -#class ComboBox(qt.QHBox): - #def __init__(self, parent, caption, items = []): - #qt.QHBox.__init__(self, parent) - #self.setSpacing(6) - #label = qt.QLabel(str(caption), self) - #self.combobox = qt.QComboBox(self) - #self.setStretchFactor(self.combobox, 1) - #label.setBuddy(self.combobox) - #for item in items: - #self.combobox.insertItem( str(item) ) -#class FileChooser(qt.QHBox): - #def __init__(self, *args): - #apply(qt.QHBox.__init__, (self,) + args) - #self.defaultfilename = "~/output.html" - #self.setSpacing(6) - #label = qt.QLabel("File:", self) - #self.edit = qt.QLineEdit(self) - #self.edit.setText(self.defaultfilename) - #self.setStretchFactor(self.edit, 1) - #label.setBuddy(self.edit) - #browsebutton = Button("...", self) - #qt.QObject.connect(browsebutton, qt.SIGNAL("clicked()"), self.browseButtonClicked) - #def file(self): - #return self.edit.text() - #def browseButtonClicked(self): - #filename = None - #try: - ## try to use the kfile module included in pykde - #import kfile - #filename = kfile.KFileDialog.getOpenFileName(self.defaultfilename, "*.html", self, "Save to file") - #except: - ## fallback to Qt filedialog - #filename = qt.QFileDialog.getOpenFileName(self.defaultfilename, "*.html", self, "Save to file") - #if filename != None and filename != "": - #self.edit.setText(filename) -#class Dialog(qt.QDialog): - #def __init__(self, parent = None, name = None, modal = 0, fl = 0): - #qt.QDialog.__init__(self, parent, name, modal, fl) - #qt.QDialog.accept = self.accept - #self.setCaption("Export to HTML") - ##self.layout() - #self.layout = qt.QVBoxLayout(self) - #self.layout.setSpacing(6) - #self.layout.setMargin(11) - #infolabel = qt.QLabel("Export the data of a table or a query to a HTML-file.", self) - #self.layout.addWidget(infolabel) - #source = ComboBox(self, "Datasource:") - #self.layout.addWidget(source) - #self.exporttype = ComboBox(self, "Style:", ["Plain","Paper","Desert","Blues"]) - #self.layout.addWidget(self.exporttype) - #self.filechooser = FileChooser(self) - #self.layout.addWidget(self.filechooser) - #buttonbox = qt.QHBox(self) - #buttonbox.setSpacing(6) - #self.layout.addWidget(buttonbox) - #savebutton = Button("Save", buttonbox) - #qt.QObject.connect(savebutton, qt.SIGNAL("clicked()"), self, qt.SLOT("accept()")) - ##qt.QObject.connect(savebutton, qt.SIGNAL("clicked()"), self.exportButtonClicked) - #cancelbutton = Button("Cancel", buttonbox) - #qt.QObject.connect(cancelbutton, qt.SIGNAL("clicked()"), self, qt.SLOT("close()")) - #def accept(self): - #print "ACCEPT" - #file = qt.QFile( self.filechooser.file() ) - ##if not file.exists(): - ## print "File '%s' does not exist." % self.filechooser.file() - ##else: - ## print "File '%s' does exist." % self.filechooser.file() - #def exportButtonClicked(self): - #print "Export to HTML" - #def __getattr__(self, attr): - #print "=> Dialog.__getattr__(self,attr)" - ##def closeEvent(self, ev): pass - #def event(self, e): - #print "=> Dialog.event %s" % e - ##self.deleteLater() - ##support.swapThreadState() # calls appropriate c-function - #return qt.QDialog.event(self, e) -#app = qt.qApp -#dialog = Dialog(app.mainWidget(), "Dialog", 1) -#dialog.show() - -#from PyQt4 import QtCore -from PyQt4 import QtGui -import TestObject1, TestObject2 - -class OwnWidget(QtGui.QLabel): - def __init__(self): - QtGui.QLabel.__init__(self) - self.setObjectName("MyLabelObjectName") - -def test(): - #label = QtGui.QLabel() - #label.setObjectName("MyQtLabelObjectName") - #obj = TestObject1.func_qwidget_qwidget(label) - #print "test() ===========> label=%s object=%s" % (label,obj) - label = OwnWidget() - obj = TestObject1.func_qwidget_qwidget(label) - print "test() ===========> label=%s object=%s" % (label,obj) - -test() diff --git a/kross/test/testguiqt.rb b/kross/test/testguiqt.rb deleted file mode 100644 index f87e54cc..00000000 --- a/kross/test/testguiqt.rb +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env krosstest - -#require 'Qt' -require 'korundum4' -require 'TestObject1' - -def test() - label = KDE::SqueezedTextLabel.new() - #label = Qt::Label.new() - - label.setObjectName("MyQtLabelObjectName") - obj = TestObject1.func_qwidget_qwidget(label) - puts "####### testguiqt.rb test() label=" + label.to_s + " object=" + obj.to_s -end - -test() diff --git a/kross/test/testguitk.py b/kross/test/testguitk.py deleted file mode 100644 index 2adc2c91..00000000 --- a/kross/test/testguitk.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env kross - -class TkTest: - def __init__(self): - import Tkinter - self.root = Tkinter.Tk() - self.root.title("TkTest") - self.root.deiconify() - - self.mainframe = Tkinter.Frame(self.root) - self.mainframe.pack() - - self.button1 = Tkinter.Button(self.mainframe, text="Button1", command=self.callback1) - self.button1.pack(side=Tkinter.LEFT) - - self.button2 = Tkinter.Button(self.mainframe, text="Button2", command=self.callback2) - self.button2.pack(side=Tkinter.LEFT) - - self.exitbutton = Tkinter.Button(self.mainframe, text="Exit", command=self.root.destroy) - self.exitbutton.pack(side=Tkinter.LEFT) - - self.root.mainloop() - - def callback1(self): - import tkMessageBox - tkMessageBox.showinfo("Callback1", "Callback1 called.") - - def callback2(self): - import tkMessageBox - tkMessageBox.showinfo("Callback2", "Callback2 called.") - -TkTest() diff --git a/kross/test/testkross.js b/kross/test/testkross.js deleted file mode 100644 index e8e77292..00000000 --- a/kross/test/testkross.js +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env kross - -var kross = Kross -var kjsaction = kross.action("MyKjsScript") - -kjsaction.setInterpreter("python") -kjsaction.setCode("print \"Hello world from Python\"") - -println("-----------------------> trigger"); -kjsaction.trigger() diff --git a/kross/test/testkross.py b/kross/test/testkross.py deleted file mode 100644 index ce5b064a..00000000 --- a/kross/test/testkross.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env kross - -""" - This Python script demonstrates how Kross could be used from - within python scripts. -""" - -print "__name__ = %s" % __name__ -#print "__main__ = %s %s" % (__main__,dir(__main__)) - -#import TestObject1, TestObject2 -#self.object1 = TestObject1 -#self.object2 = TestObject2 - -import Kross -#print dir(Kross) -kjsaction = Kross.action("MyKjsScript") -#print dir(kjsaction) -kjsaction.setInterpreter("javascript") -kjsaction.setCode( "println(\"Hello world from Kjs\");" ) -print "-----------------------> trigger" -kjsaction.trigger() diff --git a/kross/test/testobject.cpp b/kross/test/testobject.cpp deleted file mode 100644 index 4eb63d09..00000000 --- a/kross/test/testobject.cpp +++ /dev/null @@ -1,373 +0,0 @@ -/*************************************************************************** - * testobject.cpp - * This file is part of the KDE project - * copyright (C)2004-2005 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "testobject.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -TestObject::TestObject(QObject* parent, const QString& name) - : QObject(parent) -{ - setObjectName(name); - - qRegisterMetaType("TestObject"); - //qRegisterMetaType< QList >("QList"); - - QTimer* timer = new QTimer(this); - timer->setObjectName("TestTimer"); - - setProperty("dynamicProperty",QVariantList() << "Some String" << 99); -} - -TestObject::~TestObject() -{ -} - -QObject* TestObject::createThread(int steps, int msecs, bool start) -{ - TestThread* t = new TestThread(this, steps, msecs); - if( start ) - t->run(); - return t; -} - -QString TestObject::name() -{ - return objectName(); -} - -void TestObject::func_void() -{ - //kDebug() << "TestObject::func_void"; -} - -void TestObject::func_void_int(int) -{ - //kDebug() << "TestObject::func_void_int i=" << i; -} - -int TestObject::func_int_int(int i) -{ - //kDebug() << "TestObject::func_int_int i=" << i; - return i; -} - -bool TestObject::func_bool_bool(bool b) -{ - //kDebug() << "TestObject::func_bool_bool b=" << b; - return b; -} - -uint TestObject::func_uint_uint(uint i) -{ - //kDebug() << "TestObject::func_uint_uint i=" << i; - return i; -} - -double TestObject::func_double_double(double d) -{ - //kDebug() << "TestObject::func_double_double d=" << d; - return d; -} - -qlonglong TestObject::func_qlonglong_qlonglong(qlonglong l) -{ - //kDebug() << "TestObject::func_qlonglong_qlonglong l=" << l; - return l; -} - -qulonglong TestObject::func_qulonglong_qulonglong(qulonglong l) -{ - //kDebug() << "TestObject::func_qulonglong_qulonglong l=" << l; - return l; -} - -void TestObject::func_void_qstring_int(QString, int) -{ - //kDebug() << "TestObject::func_void_qstring_int s=" << s << " i=" << i; -} - -void TestObject::func_void_qstringlist(QStringList) -{ - //kDebug() << "TestObject::func_void_qstringlist sl=" << sl.join(","); -} - -QString TestObject::func_qstring_qstring_int(QString s, int i) -{ - QString r = QString("%1,%2").arg(s).arg(i); - //kDebug() << "TestObject::func_void_qstring_int s=" << s << " i=" << i << " returnvalue=" << r; - return r; -} - -QByteArray TestObject::func_qbytearray_qbytearray(QByteArray ba) -{ - //kDebug() << "TestObject::func_qbytearray_qbytearray ba=" << ba; - return ba; -} - -QString TestObject::func_qstring_qstring(const QString& s) -{ - //kDebug() << "TestObject::func_qstring_qstring s=" << s; - return s; -} - -QStringList TestObject::func_qstringlist_qstringlist(QStringList sl) -{ - //kDebug() << "TestObject::func_qstringlist_qstringlist sl=" << sl.join(","); - return sl; -} - -QVariantList TestObject::func_qvariantlist_qvariantlist(QVariantList vl) -{ - //kDebug() << "TestObject::func_qvariantlist_qvariantlist vl.count=" << vl.count(); - return vl; -} - -QVariantMap TestObject::func_qvariantmap_qvariantmap(QVariantMap vm) -{ - //kDebug() << "TestObject::func_qvariantmap_qvariantmap vm.count=" << vm.count(); - return vm; -} - -QVariantList TestObject::func_qobject2qvariantlist(QObject* obj) -{ - //kDebug()<<"TestObject::func_qobject2qvariantlist obj="<<(obj ? obj->objectName() : "NULL"); - QVariant v; - v.setValue(obj); - return QVariantList() << v; -} - -QObject* TestObject::func_qvariantlist2qobject(QVariantList list) -{ - return list.count() > 0 ? list[0].value() : 0; -} - -QSize TestObject::func_qsize_qsize(const QSize& s) { return s; } -QSizeF TestObject::func_qsizef_qsizef(const QSizeF& s) { return s; } -QPoint TestObject::func_qpoint_qpoint(const QPoint& p) { return p; } -QPointF TestObject::func_qpointf_qpointf(const QPointF& p) { return p; } -QRect TestObject::func_qrect_qrect(const QRect& r) { return r; } -QRectF TestObject::func_qrectf_qrectf(const QRectF& r) { return r; } -QUrl TestObject::func_qurl_qurl(const QUrl& u) { return u; } -QUrl TestObject::func_qurl_kurl(const KUrl& u) { return u; } -KUrl TestObject::func_kurl_kurl(const KUrl& u) { return u; } -const KUrl& TestObject::func_kurl_qstring(const QString& u) { return KUrl(u); } - -QColor TestObject::func_qcolor_qcolor(const QColor& c) { return c; } -QFont TestObject::func_qfont_qfont(const QFont& f) { return f; } -QBrush TestObject::func_qbrush_qbrush(const QBrush& b) { return b; } -QTime TestObject::func_qtime_qtime(const QTime& t) { return t; } -QDate TestObject::func_qdate_qdate(const QDate& d) { return d; } -QDateTime TestObject::func_qdatetime_qdatetime(const QDateTime& dt) { return dt; } - -void TestObject::func_void_qvariant(const QVariant& v) -{ - kDebug() << "TestObject::func_void_qvariant variant.toString=" << v.toString() << " variant.type=" << v.typeName(); -} - -QVariant TestObject::func_qvariant_qvariant(const QVariant& v) -{ - //kDebug() << "TestObject::func_qvariant_qvariant value=" << v.toString() << " type=" << v.typeName(); - return v; -} - -Kross::Object::Ptr TestObject::func_krossobject_krossobject(Kross::Object::Ptr object) -{ - //kDebug() << "TestObject::func_krossobject_krossobject"; - return object; -} - -QStringList TestObject::get_krossobject_methods(Kross::Object::Ptr object) -{ - //kDebug() << "TestObject::get_krossobject_methods"; - return object->methodNames(); -} - -QVariant TestObject::call_krossobject_method(Kross::Object::Ptr object, const QString& methodname, const QVariantList& args) -{ - //kDebug() << "TestObject::call_krossobject_method"; - return object->callMethod(methodname, args); -} - -QObject* TestObject::func_createChildTestObject(const QString& objectname) -{ - return new TestObject(this, objectname); -} - -void TestObject::func_void_qobject(QObject*) -{ - //kDebug() << "TestObject::func_void_qobject " << (obj ? QString("objectName=%1 className=%2").arg(obj->objectName()).arg(obj->metaObject()->className()) : "NULL"); -} - -QObject* TestObject::func_qobject_qobject(QObject* obj) -{ - //kDebug() << "TestObject::func_qobject_qobject " << (obj ? QString("objectName=%1 className=%2").arg(obj->objectName()).arg(obj->metaObject()->className()) : "NULL"); - return obj; -} - -QWidget* TestObject::func_qwidget_qwidget(QWidget* widget) -{ - kDebug() << "TestObject::func_qwidget_qwidget " << (widget ? QString("objectName=%1 className=%2").arg(widget->objectName()).arg(widget->metaObject()->className()) : "NULL"); - return widget; -} - -void TestObject::func_void_testobject(TestObject* obj) -{ - kDebug() << "TestObject::func_void_testobject " << (obj ? QString("objectName=%1 className=%2").arg(obj->objectName()).arg(obj->metaObject()->className()) : "NULL"); -} - -TestObject* TestObject::func_testobject_testobject(TestObject* obj) -{ - kDebug() << "TestObject::func_testobject_testobject " << (obj ? QString("objectName=%1 className=%2").arg(obj->objectName()).arg(obj->metaObject()->className()) : "NULL"); - return obj; -} - -TestObject* TestObject::func_testobject_qobject(QObject* obj) -{ - TestObject* tobj = dynamic_cast(obj); - return tobj; -} - -void TestObject::func_void_testobjectlist(QList l) -{ - kDebug() << "TestObject::func_void_testobjectlist " << l.count(); - foreach(TestObject* obj, l) - kDebug() << " " << (obj ? obj->objectName() : "NULL"); -} - -QList TestObject::func_testobjectlist_testobjectlist(QList l) -{ - kDebug() << "TestObject::func_testobjectlist_testobjectlist " << l.count(); - return l; -} - -void TestObject::connectCallTestFunction(Kross::Action* krossAction, QObject* sender, const QString& signal) -{ - m_krossAction = krossAction; - - QString signalName = signal; - if (!signalName.startsWith('2')) { - signalName = QString("2%1").arg(signal); - } - - connect(sender, signalName.toLatin1(), this, SLOT(callTestFunction())); -} - -void TestObject::callTestFunction() -{ - QVariantList arguments; - arguments << 42; - m_testFunctionReturnedValue = m_krossAction->callFunction("testFunction", arguments); -} - -void TestObject::connectCallTestFunctionException(Kross::Action* krossAction, QObject* sender, const QString& signal) -{ - m_krossAction = krossAction; - - QString signalName = signal; - if (!signalName.startsWith('2')) { - signalName = QString("2%1").arg(signal); - } - - connect(sender, signalName.toLatin1(), this, SLOT(callTestFunctionException())); -} - -void TestObject::callTestFunctionException() -{ - QVariantList arguments; - arguments << 42; - m_testFunctionReturnedValue = m_krossAction->callFunction("testFunctionException", arguments); -} - -QVariant TestObject::testFunctionReturnedValue() -{ - return m_testFunctionReturnedValue; -} - -/***************************************************************************************** - * OtherObject - */ - -OtherObject* TestObject::func_otherobject(const QByteArray& name) -{ - if( OtherObject* obj = findChild(name) ) - return obj; - return new OtherObject(this, name); -} - -OtherObject* TestObject::func_otherobject_otherobject(OtherObject* obj) -{ - return obj; -} - -QList TestObject::func_otherobjectlist_otherobjectlist(QList l) -{ - return l; -} - -/***************************************************************************************** - * TestThread - */ - -TestThread::TestThread(TestObject* parent, int steps, int msecs) - : QThread(parent) - , m_testobject(parent) - , m_steps(steps) - , m_msecs(msecs) -{ - //kDebug() << "TestThread::TestThread()"; -} - -TestThread::~TestThread() -{ - //kDebug() << "TestThread::~TestThread()"; -} - -void TestThread::emitStepDone(int step) -{ - //kDebug() << "TestThread::emitStepDone() step=" << step; - emit stepDone(step); -} - -QVariant TestThread::callFunction(QObject* action, const QString& functionname, QVariantList arguments) -{ - Kross::Action* a = dynamic_cast(action); - Q_ASSERT(a); - return a->callFunction(functionname, arguments); -} - -void TestThread::run() -{ - //kDebug() << "TestThread::run()"; - for(int i = 0; i < m_steps; ++i) { - kDebug() << "TestThread::run() 1 step=" << i << "m_steps=" << m_steps << "m_msecs=" << m_msecs; - emit stepDone(i); - //m_testobject->emitSignalVoid(); - msleep(m_msecs); - } -} - -#include "moc_testobject.cpp" diff --git a/kross/test/testobject.h b/kross/test/testobject.h deleted file mode 100644 index 9d8cb449..00000000 --- a/kross/test/testobject.h +++ /dev/null @@ -1,310 +0,0 @@ -/*************************************************************************** - * testobject.h - * This file is part of the KDE project - * copyright (C)2004-2005 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_TEST_TESTOBJECT_H -#define KROSS_TEST_TESTOBJECT_H - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "../core/action.h" -#include "../core/object.h" -#include "../core/wrapperinterface.h" - -class OtherObject; - -/// \internal class to test functionality within krosstest -class TestObject : public QObject -{ - Q_OBJECT - - Q_PROPERTY(bool boolProperty READ boolProperty WRITE setBoolProperty) - Q_PROPERTY(int intProperty READ intProperty WRITE setIntProperty) - Q_PROPERTY(double doubleProperty READ doubleProperty WRITE setDoubleProperty) - Q_PROPERTY(QString stringProperty READ stringProperty WRITE setStringProperty) - Q_PROPERTY(QStringList stringListProperty READ stringListProperty WRITE setStringListProperty) - Q_PROPERTY(QVariantList listProperty READ listProperty WRITE setListProperty) - - Q_ENUMS(TestEnum) - - public: - explicit TestObject(QObject* parent = 0, const QString& name = QString()); - //TestObject(const TestObject&) {} - virtual ~TestObject(); - - enum TestEnum { TESTENUM1 = 1, TESTENUM2 = 2, TESTENUM3 = 4, TESTENUM4 = 8 }; - - private: - - bool m_boolproperty; - bool boolProperty() const { return m_boolproperty; } - void setBoolProperty(bool prop) { m_boolproperty = prop; } - - int m_intproperty; - int intProperty() const { return m_intproperty; } - void setIntProperty(int prop) { m_intproperty = prop; } - - double m_doubleproperty; - double doubleProperty() const { return m_doubleproperty; } - void setDoubleProperty(double prop) { m_doubleproperty = prop; } - - QString m_stringproperty; - QString stringProperty() const { return m_stringproperty; } - void setStringProperty(QString prop) { m_stringproperty = prop; } - - QStringList m_stringlistproperty; - QStringList stringListProperty() const { return m_stringlistproperty; } - void setStringListProperty(QStringList prop) { m_stringlistproperty = prop; } - - QVariantList m_listproperty; - QVariantList listProperty() const { return m_listproperty; } - void setListProperty(QVariantList prop) { m_listproperty = prop; } - - Kross::Action* m_krossAction; - QVariant m_testFunctionReturnedValue; - - Q_SIGNALS: - void signalVoid(); - void signalBool(bool); - void signalInt(int); - void signalString(const QString&); - void signalObject(QObject* obj); - - public Q_SLOTS: - - QObject* myself() { return this; } - TestObject* myself2() { return this; } - QList myself3() { return QList() << this; } - - // return a TestThread instance. - QObject* createThread(int steps, int msecs, bool start = false); - - // emit some signals - void emitSignalVoid() { emit signalVoid(); } - void emitSignalBool(bool b) { emit signalBool(b); } - void emitSignalInt(int i) { emit signalInt(i); } - void emitSignalString(const QString& s) { emit signalString(s); } - void emitSignalObject(QObject* obj) { emit signalObject(obj); } - - // return the objectname - QString name(); - - // test the enumerator - //TestEnum testEnum(TestEnum e) const { return e; } - - // to test basic datatypes - int func_int_int(int); - bool func_bool_bool(bool); - uint func_uint_uint(uint); - double func_double_double(double); - qlonglong func_qlonglong_qlonglong(qlonglong); - qulonglong func_qulonglong_qulonglong(qulonglong); - QByteArray func_qbytearray_qbytearray(QByteArray); - QString func_qstring_qstring(const QString&); - QStringList func_qstringlist_qstringlist(QStringList); - QVariantList func_qvariantlist_qvariantlist(QVariantList); - QVariantMap func_qvariantmap_qvariantmap(QVariantMap); - - QVariantList func_qobject2qvariantlist(QObject* obj); - QObject* func_qvariantlist2qobject(QVariantList list); - - QSize func_qsize_qsize(const QSize&); - QSizeF func_qsizef_qsizef(const QSizeF&); - QPoint func_qpoint_qpoint(const QPoint&); - QPointF func_qpointf_qpointf(const QPointF&); - QRect func_qrect_qrect(const QRect&); - QRectF func_qrectf_qrectf(const QRectF&); - QUrl func_qurl_qurl(const QUrl&); - QUrl func_qurl_kurl(const KUrl&); - KUrl func_kurl_kurl(const KUrl&); - - // following is returned by reference which is a big nono - // cause it may lead to crashes. So, the backends should - // set such things to None/nil/NULL/etc. - const KUrl& func_kurl_qstring(const QString&); - - QColor func_qcolor_qcolor(const QColor&); - QFont func_qfont_qfont(const QFont&); - QBrush func_qbrush_qbrush(const QBrush&); - QTime func_qtime_qtime(const QTime&); - QDate func_qdate_qdate(const QDate&); - QDateTime func_qdatetime_qdatetime(const QDateTime&); - void func_void_qvariant(const QVariant&); - QVariant func_qvariant_qvariant(const QVariant&); - - // for misc tests - void func_void(); - void func_void_int(int); - void func_void_qstring_int(QString,int); - void func_void_qstringlist(QStringList); - QString func_qstring_qstring_int(QString,int); - - // Kross::Object - Kross::Object::Ptr func_krossobject_krossobject(Kross::Object::Ptr object); - QStringList get_krossobject_methods(Kross::Object::Ptr object); - QVariant call_krossobject_method(Kross::Object::Ptr object, const QString& methodname, const QVariantList& args = QVariantList()); - - // QObject - QObject* func_createChildTestObject(const QString& objectname); - void func_void_qobject(QObject*); - QObject* func_qobject_qobject(QObject*); - - // QWidget - QWidget* func_qwidget_qwidget(QWidget*); - - // TestObject - void func_void_testobject(TestObject*); - TestObject* func_testobject_testobject(TestObject*); - TestObject* func_testobject_qobject(QObject*); - void func_void_testobjectlist(QList); - QList func_testobjectlist_testobjectlist(QList); - - // OtherObject - OtherObject* func_otherobject(const QByteArray& name); - OtherObject* func_otherobject_otherobject(OtherObject*); - QList func_otherobjectlist_otherobjectlist(QList); - - // for PyQt signal test - void connectCallTestFunction(Kross::Action* krossAction, QObject* sender, const QString& signal); - void callTestFunction(); - void connectCallTestFunctionException(Kross::Action* krossAction, QObject* sender, const QString& signal); - void callTestFunctionException(); - QVariant testFunctionReturnedValue(); -}; - -/// \internal class used in TestObject to test functionality within krosstest -class OtherObject : public QObject -{ - Q_OBJECT - public: - explicit OtherObject(TestObject* testobj, const QByteArray& name) : QObject(testobj) { setObjectName(name); } - public Q_SLOTS: - QObject* testObject() const { return parent(); } -}; - -/// \internal class used in a handler within krosstest to provide a OtherObject wrapper on demand -class OtherObjectWrapper : public QObject, public Kross::WrapperInterface -{ - Q_OBJECT - public: - OtherObjectWrapper(QObject* obj) : QObject(obj) { - Q_ASSERT(obj); - setObjectName(QString("%1_wrapper").arg(obj->objectName()).toLatin1()); - } - void* wrappedObject() const { return parent(); } - public Q_SLOTS: - QObject* parentObject() const { return parent(); } -}; - -/** -* \internal class to test threading functionality within krosstest. -* -* Following python code does provide a sample how this class -* may used to test the threading functionality. -* \code -* import time, TestObject1 -* # this function will be called by our thread -* def myFunction(step): -* print "myFunction step=%i" % step -* # create a thread that iterates 15 times and waits 200 -* # milliseconds on each iteration, 20*200=2 seconds -* mythread = TestObject1.createThread(15,200) -* # connect the stepDone signal our thread provides to -* # our own python function above -* mythread.connect("stepDone(int)",myFunction) -* # start the thread -* mythread.start() -* # let this python thread sleep for a second -* time.sleep(1) -* # ask our action to call our myFunction function -* self.callFunction("myFunction", [123]) -* # ask our thread to emit the stepDone signal which in -* # turn should call our myFunction function. -* mythread.emitStepDone(456) -* # same as above but we emit the signal by our own -* # rather than going through a helper-function. -* mythread.stepDone(789) -* # now let's ask our thread to ask our action to execute -* # our function to have one complete roundtrip :) -* mythread.callFunction(self, "myFunction", [987]) -* # sleep again one second -* time.sleep(1) -* \endcode -* -* Following sample code does the same as the code above but -* uses the Ruby scripting language. -* \code -* require 'TestObject1' -* def myFunction(step) -* puts "myFunction step=" + step.to_s -* end -* mythread = TestObject1.createThread(10,200) -* mythread.connect("stepDone(int)", method("myFunction")) -* mythread.start() -* sleep(1) -* self.action().callFunction("myFunction", [123]) -* mythread.emitStepDone(456) -* mythread.stepDone(789) -* mythread.callFunction(self.action(), "myFunction", [987]) -* sleep(1) -* \endcode -*/ -class TestThread : public QThread -{ - Q_OBJECT - public: - explicit TestThread(TestObject* parent, int steps, int msecs); - virtual ~TestThread(); - virtual void run(); - public Q_SLOTS: - void emitStepDone(int step); - QVariant callFunction(QObject* action, const QString& functionname, QVariantList arguments); - Q_SIGNALS: - void stepDone(int step); - private: - TestObject* m_testobject; - int m_steps, m_msecs; -}; - -//Q_DECLARE_METATYPE( TestObject* ) -//Q_DECLARE_METATYPE( TestObject ) - -#endif diff --git a/kross/test/unittest.es b/kross/test/unittest.es deleted file mode 100644 index 499374dc..00000000 --- a/kross/test/unittest.es +++ /dev/null @@ -1,237 +0,0 @@ -#!/usr/bin/env kross - -// Print something on the console. -println("Let's start the Unittest :-)"); - -function UnitTest() -{ - var numpassed = 0; - var numfailed = 0; - - this.passed = function() { - numpassed = numpassed + 1; - } - - this.failed = function(actual, expected) { - print("FAILED actual=" + actual + " expected=" + expected); - numfailed = numfailed + 1; - } - - this.missingException = function(message) { - print("MISSING EXCEPTION: " + message); - numfailed = numfailed + 1; - } - - this.unexpectedException = function(message, exception) { - print("UNEXPECTED EXCEPTION: " + message + "\n" + exception); - numfailed = numfailed + 1; - } - - this.assert = function(actual, expected) { - if(actual == expected) - this.passed(); - else - this.failed(actual, expected); - } - - this.assertArray = function(actual, expected) { - if(actual.length != expected.length) { - this.failed(actual, expected); - print("Array-Length does not match: actual=" + actual.length + " expected=" + expected.length); - } - else { - var failed = false; - for(i=0;i>>>>>>>>>>>>>>>>>> %s" % qo - - def testPyQtSignal(self): - try: - from PyQt4 import QtCore, Qt - import string - version = string.split(QtCore.PYQT_VERSION_STR, ".") - if map(int, version) < [4, 5]: - print "PyQt4 version (", QtCore.PYQT_VERSION_STR, ") is lower than 4.5, skipping test" - return - except: - print "PyQt4 wasn't found, skipping test" - return - - class PyQtObject(Qt.QObject): - customSignal = QtCore.pyqtSignal() - - pyQtObject = PyQtObject() - self.object1.connectCallTestFunction(KrossAction, pyQtObject, "customSignal()") - pyQtObject.customSignal.emit() - - self.assert_( self.object1.testFunctionReturnedValue() == [42] ) - - def testPyQtSignalException(self): - try: - from PyQt4 import QtCore, Qt - import string - version = string.split(QtCore.PYQT_VERSION_STR, ".") - if map(int, version) < [4, 5]: - print "PyQt4 version (", QtCore.PYQT_VERSION_STR, ") is lower than 4.5, skipping test" - return - except: - print "PyQt4 wasn't found, skipping test" - return - - class PyQtObject(Qt.QObject): - customSignal = QtCore.pyqtSignal() - - pyQtObject = PyQtObject() - self.object1.connectCallTestFunctionException(KrossAction, pyQtObject, "customSignal()") - pyQtObject.customSignal.emit() - - self.assert_( self.object1.testFunctionReturnedValue() == None ) - - def testClass(self): - class MyClass: - def __init__(self, result): - self.result = result - def myMethod(self): - return self.result - s = "my string" - myclass = MyClass(s) - self.assert_( self.object1.call_krossobject_method(myclass, "myMethod") == s ) - - def testOtherObject(self): - otherobj1 = self.object1.func_otherobject("OtherObject1") - otherobj2 = self.object1.func_otherobject("OtherObject2") - #print "otherobj1=%s otherobj1.objectName=%s dir(otherobj1)=%s" % (otherobj1, otherobj1.objectName, dir(otherobj1)) - - self.assert_( otherobj1.objectName == "OtherObject1_wrapper" ) - self.assert_( otherobj2.parentObject().objectName == "OtherObject2" ) - self.assert_( self.object1.func_otherobject_otherobject(otherobj1).objectName == otherobj1.objectName ) - - l = self.object1.func_otherobjectlist_otherobjectlist( [otherobj1,otherobj2] ) - self.assert_( len(l) == 2 ) - self.assert_( l[0].objectName == "OtherObject1_wrapper" ) - self.assert_( l[1].parentObject().objectName == "OtherObject2" ) - - def testEvaluation(self): - self.assert_( KrossAction.evaluate("1+2") == 3 ) - self.assert_( KrossAction.evaluate("testFunction(None,99)") == [None,99] ) - -print "__name__ = %s" % __name__ -#print "__main__ = %s %s" % (__main__,dir(__main__)) -#print "TestObject3.name = %s" % TestObject3.name() - -suite = unittest.makeSuite(TestKross) -unittest.TextTestRunner(verbosity=2).run(suite) - -#import Kross, TestObject1 -#print "===========> %s" % TestObject1.func_qsize_qsize( [12,-94] ) -#print "===========> %s" % TestObject1.func_qsizef_qsizef( [12.2,-94.2] ) diff --git a/kross/test/unittest.rb b/kross/test/unittest.rb deleted file mode 100644 index 70766fc0..00000000 --- a/kross/test/unittest.rb +++ /dev/null @@ -1,448 +0,0 @@ -#!/usr/bin/env krosstest - -require 'test/unit' - -require "TestObject1" -require "TestObject2" - -KrossAction = self.action() - -class MyClass - def initialize(result) - @result = result - end - def myMethod - return @result - end -end - -def testFunction1(arg1) - return arg1 -end - -def testFunction2(arg1,arg2) - return [arg1,arg2] -end - -class TestKross < Test::Unit::TestCase - - def setup - end - - def testBool - assert_raises(TypeError) { TestObject1.func_bool_bool(17) } - assert_raises(TypeError) { TestObject1.func_bool_bool("string") } - assert_raises(TypeError) { TestObject1.func_bool_bool([]) } - - assert( TestObject1.func_bool_bool(nil) == false ) - assert( TestObject1.func_bool_bool(true) == true ) - assert( TestObject1.func_bool_bool(false) == false ) - end - - def testInt - assert_raises(TypeError) { TestObject1.func_int_int(false) } - assert_raises(TypeError) { TestObject1.func_int_int("string") } - assert_raises(TypeError) { TestObject1.func_bool_bool([]) } - - assert( TestObject1.func_int_int(nil) == 0 ) - assert( TestObject1.func_int_int(0) == 0 ) - assert( TestObject1.func_int_int(177321) == 177321 ) - assert( TestObject1.func_int_int(-98765) == -98765 ) - assert( TestObject1.func_int_int(17.111) == 17 ) - assert( TestObject1.func_int_int(42.999) == 42 ) - end - - def testUInt - assert_raises(TypeError) { TestObject1.func_uint_uint(true) } - assert_raises(TypeError) { TestObject1.func_uint_uint("string") } - assert_raises(TypeError) { TestObject1.func_uint_uint([]) } - - assert( TestObject1.func_uint_uint(nil) == 0 ) - assert( TestObject1.func_uint_uint(0) == 0 ) - assert( TestObject1.func_uint_uint(177321) == 177321 ) - assert( TestObject1.func_uint_uint(17.111) == 17 ) - assert( TestObject1.func_uint_uint(42.999) == 42 ) - end - - def testDouble - assert_raises(TypeError) { TestObject1.func_double_double(true) } - assert_raises(TypeError) { TestObject1.func_double_double("string") } - assert_raises(TypeError) { TestObject1.func_double_double([]) } - #assert_raises(TypeError) { TestObject1.func_double_double(83) } - - assert( TestObject1.func_double_double(nil) == 0.0 ) - assert( TestObject1.func_double_double(0.0) == 0.0 ) - assert( TestObject1.func_double_double(1773.2177) == 1773.2177 ) - assert( TestObject1.func_double_double(-548993.271993) == -548993.271993 ) - assert( TestObject1.func_double_double(123) == 123.0 ) - assert( TestObject1.func_double_double(-456) == -456.0 ) - end - - def testLongLong - assert_raises(TypeError) { TestObject1.func_qlonglong_qlonglong(true) } - assert_raises(TypeError) { TestObject1.func_qlonglong_qlonglong("string") } - assert_raises(TypeError) { TestObject1.func_qlonglong_qlonglong([]) } - - assert( TestObject1.func_qlonglong_qlonglong(nil) == 0 ) - assert( TestObject1.func_qlonglong_qlonglong(0) == 0 ) - assert( TestObject1.func_qlonglong_qlonglong(7379) == 7379 ) - assert( TestObject1.func_qlonglong_qlonglong(-6384673) == -6384673 ) - #assert( TestObject1.func_qlonglong_qlonglong(678324787843223472165) == 678324787843223472165 ) - end - - def testULongLong - assert_raises(TypeError) { TestObject1.func_qulonglong_qulonglong(true) } - assert_raises(TypeError) { TestObject1.func_qulonglong_qulonglong("string") } - assert_raises(TypeError) { TestObject1.func_qulonglong_qulonglong([]) } - - assert( TestObject1.func_qulonglong_qulonglong(nil) == 0 ) - assert( TestObject1.func_qulonglong_qulonglong(0) == 0 ) - assert( TestObject1.func_qulonglong_qulonglong(378972) == 378972 ) - #assert( TestObject1.func_qulonglong_qulonglong(-8540276823902375665225676321823) == -8540276823902375665225676321823 ) - end - - def testByteArray - assert_raises(TypeError) { TestObject1.func_qbytearray_qbytearray(false) } - assert_raises(TypeError) { TestObject1.func_qbytearray_qbytearray(true) } - assert_raises(TypeError) { TestObject1.func_qbytearray_qbytearray(532) } - assert_raises(TypeError) { TestObject1.func_qbytearray_qbytearray(-2) } - assert_raises(TypeError) { TestObject1.func_qbytearray_qbytearray(8572.45) } - assert_raises(TypeError) { TestObject1.func_qbytearray_qbytearray([]) } - - #assert( TestObject1.func_qbytearray_qbytearray(nil) == "" ) - assert( TestObject1.func_qbytearray_qbytearray("") == "" ) - assert( TestObject1.func_qbytearray_qbytearray(" Some String as ByteArray ") == " Some String as ByteArray " ) - assert( TestObject1.func_qbytearray_qbytearray(" \0\n\r\t\s\0 test ") == " \0\n\r\t\s\0 test " ) - end - - def testString - assert_raises(TypeError) { TestObject1.func_qstring_qstring(false) } - assert_raises(TypeError) { TestObject1.func_qstring_qstring(true) } - assert_raises(TypeError) { TestObject1.func_qstring_qstring(927) } - assert_raises(TypeError) { TestObject1.func_qstring_qstring(19.32) } - assert_raises(TypeError) { TestObject1.func_qstring_qstring([]) } - - #assert( TestObject1.func_qstring_qstring(nil) == "" ) - assert( TestObject1.func_qstring_qstring("") == "" ) - assert( TestObject1.func_qstring_qstring(" ") == " " ) - assert( TestObject1.func_qstring_qstring(" Another \n\r Test! $%&\" ") == " Another \n\r Test! $%&\" " ) - end - - def testSize - assert_raises(TypeError) { TestObject1.func_qsize_qsize("") } - assert_raises(TypeError) { TestObject1.func_qsize_qsize(123) } - assert_raises(TypeError) { TestObject1.func_qsize_qsize(456.789) } - assert_raises(TypeError) { TestObject1.func_qsize_qsize([]) } - - #assert( TestObject1.func_qsize_qsize( nil ) == [0,0] ) - #assert( TestObject1.func_qsize_qsize( [0,0] ) == [0,0] ) - assert( TestObject1.func_qsize_qsize( [12,-94] ) == [12,-94] ) - assert( TestObject1.func_qsize_qsize( [-7264,6224] ) == [-7264,6224] ) - end - - def testSizeF - assert_raises(TypeError) { TestObject1.func_qsizef_qsizef("") } - assert_raises(TypeError) { TestObject1.func_qsizef_qsizef(123) } - assert_raises(TypeError) { TestObject1.func_qsizef_qsizef(456.789) } - assert_raises(TypeError) { TestObject1.func_qsizef_qsizef([]) } - - #assert_raises(TypeError) { TestObject1.func_qsizef_qsizef(nil) } - #assert_raises(TypeError) { TestObject1.func_qsizef_qsizef([0.0]) } - #assert_raises(TypeError) { TestObject1.func_qsizef_qsizef([0.0,0.0,0.0]) } - #assert( TestObject1.func_qsizef_qsizef( [0.0,0.0] ) == [0.0,0.0] ) - assert( TestObject1.func_qsizef_qsizef( [-956.0,75.0] ) == [-956.0,75.0] ) - assert( TestObject1.func_qsizef_qsizef( [-14.21,-535.0] ) == [-14.21,-535.0] ) - assert( TestObject1.func_qsizef_qsizef( [26,-525] ) == [26,-525] ) - assert( TestObject1.func_qsizef_qsizef( [-956.0,75.21] ) == [-956.0,75.21] ) - end - - def testPoint - assert_raises(TypeError) { TestObject1.func_qpoint_qpoint("") } - assert_raises(TypeError) { TestObject1.func_qpoint_qpoint(123) } - assert_raises(TypeError) { TestObject1.func_qpoint_qpoint(456.789) } - assert_raises(TypeError) { TestObject1.func_qpoint_qpoint([]) } - - #assert_raises(TypeError) { TestObject1.func_qpoint_qpoint(nil) } - #assert_raises(TypeError) { TestObject1.func_qpoint_qpoint([0]) } - #assert_raises(TypeError) { TestObject1.func_qpoint_qpoint([0,0,0]) } - #assert( TestObject1.func_qpoint_qpoint( [0,0] ) == [0,0] ) - assert( TestObject1.func_qpoint_qpoint( [12,-94] ) == [12,-94] ) - assert( TestObject1.func_qpoint_qpoint( [-7264,6224] ) == [-7264,6224] ) - end - - def testPointF - assert_raises(TypeError) { TestObject1.func_qpointf_qpointf("") } - assert_raises(TypeError) { TestObject1.func_qpointf_qpointf(123) } - assert_raises(TypeError) { TestObject1.func_qpointf_qpointf(456.789) } - assert_raises(TypeError) { TestObject1.func_qpointf_qpointf([]) } - - #assert_raises(TypeError) { TestObject1.func_qpointf_qpointf(nil) } - #assert_raises(TypeError) { TestObject1.func_qpointf_qpointf([0.0]) } - #assert_raises(TypeError) { TestObject1.func_qpointf_qpointf([0.0,0.0,0.0]) } - #assert( TestObject1.func_qpointf_qpointf( [0.0,0.0] ) == [0.0,0.0] ) - assert( TestObject1.func_qpointf_qpointf( [-956.0,751.0] ) == [-956.0,751.0] ) - assert( TestObject1.func_qpointf_qpointf( [-82.3172,17.0] ) == [-82.3172,17.0] ) - assert( TestObject1.func_qpointf_qpointf( [1.2,2.3] ) == [1.2,2.3] ) - assert( TestObject1.func_qpointf_qpointf( [-956.03,751.4165] ) == [-956.03,751.4165] ) - end - - def testRect - assert_raises(TypeError) { TestObject1.func_qrect_qrect("") } - assert_raises(TypeError) { TestObject1.func_qrect_qrect(123) } - assert_raises(TypeError) { TestObject1.func_qrect_qrect(456.789) } - assert_raises(TypeError) { TestObject1.func_qrect_qrect([]) } - - #assert_raises(TypeError) { TestObject1.func_qrect_qrect(nil) } - #assert_raises(TypeError) { TestObject1.func_qrect_qrect([0,0,0]) } - #assert_raises(TypeError) { TestObject1.func_qrect_qrect([0,0,0,0,0]) } - #assert( TestObject1.func_qrect_qrect( [0,0,0,0] ) == [0,0,0,0] ) - assert( TestObject1.func_qrect_qrect( [-1,-2,3,4] ) == [-1,-2,3,4] ) - assert( TestObject1.func_qrect_qrect( [1,2,-3,-4] ) == [1,2,-3,-4] ) - assert( TestObject1.func_qrect_qrect( [-10,-20,30,40] ) == [-10,-20,30,40] ) - assert( TestObject1.func_qrect_qrect( [10,20,30,40] ) == [10,20,30,40] ) - assert( TestObject1.func_qrect_qrect( [10,20,-30,-40] ) == [10,20,-30,-40] ) - end - - def testRectF - assert_raises(TypeError) { TestObject1.func_qrectf_qrectf("") } - assert_raises(TypeError) { TestObject1.func_qrectf_qrectf(123) } - assert_raises(TypeError) { TestObject1.func_qrectf_qrectf(456.789) } - assert_raises(TypeError) { TestObject1.func_qrectf_qrectf([]) } - - #assert_raises(TypeError) { TestObject1.func_qrectf_qrectf(nil) } - #assert_raises(TypeError) { TestObject1.func_qrectf_qrectf([0.0,0.0,0.0]) } - #assert_raises(TypeError) { TestObject1.func_qrectf_qrectf([0.0,0.0,0.0,0.0,0.0]) } - #assert( TestObject1.func_qrectf_qrectf( [0.0,0.0,0.0,0.0] ) == [0.0,0.0,0.0,0.0] ) - assert( TestObject1.func_qrectf_qrectf( [-1.0,-2.0,3.0,4.0] ) == [-1.0,-2.0,3.0,4.0] ) - assert( TestObject1.func_qrectf_qrectf( [-1.1,-2.2,3.3,4.4] ) == [-1.1,-2.2,3.3,4.4] ) - end - - def testColor - assert( TestObject1.func_qcolor_qcolor(nil) == nil ) - assert( TestObject1.func_qcolor_qcolor("") == nil ) - assert( TestObject1.func_qcolor_qcolor("#0066ff") == "#0066ff" ) - end - - def testUrl - #assert( TestObject1.func_qurl_qurl(nil) == nil ) - assert( TestObject1.func_qurl_qurl("") == "" ) - assert( TestObject1.func_qurl_qurl("/home/myuser") == "/home/myuser" ) - assert( TestObject1.func_qurl_qurl("file:///home/myuser/myfile.txt") == "file:///home/myuser/myfile.txt" ) - assert( TestObject1.func_qurl_qurl("http://myname:mypass@kross.dipe.org?404.cgi?test=123&test2=456") == "http://myname:mypass@kross.dipe.org?404.cgi?test=123&test2=456" ) - assert( TestObject1.func_kurl_kurl("http://www.kde.org/whatiskde/") == "http://www.kde.org/whatiskde/" ) - assert( ! TestObject1.func_kurl_qstring("http://www.kde.org/whatiskde/") ) - end - - def testStringList - assert_raises(TypeError) { TestObject1.func_qstringlist_qstringlist("") } - assert_raises(TypeError) { TestObject1.func_qstringlist_qstringlist(0) } - assert_raises(TypeError) { TestObject1.func_qstringlist_qstringlist(true) } - assert_raises(TypeError) { TestObject1.func_qstringlist_qstringlist(false) } - assert_raises(TypeError) { TestObject1.func_qstringlist_qstringlist(-32.85) } - - assert( TestObject1.func_qstringlist_qstringlist( nil ) == [] ) - assert( TestObject1.func_qstringlist_qstringlist( [] ) == [] ) - assert( TestObject1.func_qstringlist_qstringlist( ["string1"] ) == ["string1"] ) - assert( TestObject1.func_qstringlist_qstringlist( [" string1","string2 "] ) == [" string1","string2 "] ) - end - - def testVariantList - assert_raises(TypeError) { TestObject1.func_qvariantlist_qvariantlist("") } - assert_raises(TypeError) { TestObject1.func_qvariantlist_qvariantlist(0) } - assert_raises(TypeError) { TestObject1.func_qvariantlist_qvariantlist(true) } - assert_raises(TypeError) { TestObject1.func_qvariantlist_qvariantlist(false) } - assert_raises(TypeError) { TestObject1.func_qvariantlist_qvariantlist(-32.85) } - - #assert_raises(TypeError) { TestObject1.func_qvariantlist_qvariantlist(nil) } - assert( TestObject1.func_qvariantlist_qvariantlist( [] ) == [] ) - assert( TestObject1.func_qvariantlist_qvariantlist( [[[[]],[]]] ) == [[[[]],[]]] ) - assert( TestObject1.func_qvariantlist_qvariantlist( ["A string",[17539,-8591],[5.32,-842.775]] ) == ["A string",[17539,-8591],[5.32,-842.775]] ) - - l = TestObject1.func_qobject2qvariantlist(TestObject2) - assert( l[0].objectName == TestObject2.objectName ) - assert( TestObject1.func_qvariantlist2qobject(l).objectName == TestObject2.objectName ) - end - - def testVariantMap - #assert_raises(TypeError) { TestObject1.func_qvariantmap_qvariantmap(nil) } - #assert( {} ) - #assert( {"1":73682,"2":285} ) - #assert( {"a":-6892.957,"b":692.66} ) - #assert( {"key1":True,"key2":False} ) - #assert( {"key 1":" Some String ","key 2":"oThEr StRiNg"} ) - #assert( {" key1 ":[12.5,True]," key2 ":[83.002,"test"]} ) - end - - def testVariant - assert( TestObject1.func_qvariant_qvariant(0.0) == 0.0 ) - assert( TestObject1.func_qvariant_qvariant(true) == true ) - assert( TestObject1.func_qvariant_qvariant(false) == false ) - assert( TestObject1.func_qvariant_qvariant(187937) == 187937 ) - assert( TestObject1.func_qvariant_qvariant(-69825) == -69825 ) - assert( TestObject1.func_qvariant_qvariant(8632.274) == 8632.274 ) - assert( TestObject1.func_qvariant_qvariant(-8632.351) == -8632.351 ) - assert( TestObject1.func_qvariant_qvariant(" Test \n\r This String $%&\"") == " Test \n\r This String $%&\"") - end - - def testFunctions - assert( KrossAction.functionNames().include?("testFunction1") ) - assert( KrossAction.callFunction("testFunction1",[true]) == true ) - assert( KrossAction.callFunction("testFunction1",[false]) == false ) - assert( KrossAction.callFunction("testFunction1",[524]) == 524 ) - assert( KrossAction.callFunction("testFunction1",[-958]) == -958 ) - assert( KrossAction.callFunction("testFunction1",[524.98]) == 524.98 ) - assert( KrossAction.callFunction("testFunction1",[-958.1257]) == -958.1257 ) - assert( KrossAction.callFunction("testFunction1",[""]) == "" ) - assert( KrossAction.callFunction("testFunction1",[" Some\nString "]) == " Some\nString " ) - assert( KrossAction.callFunction("testFunction1",[[]]) == [] ) - assert( KrossAction.callFunction("testFunction1",[["one",23,"two",nil,false]]) == ["one",23,"two",nil,false] ) - assert( KrossAction.functionNames().include?("testFunction2") ) - assert( KrossAction.callFunction("testFunction2",[[],[]]) == [[],[]] ) - assert( KrossAction.callFunction("testFunction2",[[1,"test"],nil]) == [[1,"test"],nil] ) - - #TODO this results in a crach in Ruby 1.8.6 in the callcache code. Probably related to the issue Cyrille jumped at? - #puts KrossAction.callFunction("testFunction1",[KrossAction]) - - end - - def testObject - assert( KrossAction.name() == "MyAction" ) - assert( KrossAction.interpreter() == "ruby" ) - - assert( TestObject1.name() == "TestObject1" ) - assert( TestObject2.name() == "TestObject2" ) - - assert( TestObject1.func_qobject_qobject(true) == nil ) - assert( TestObject1.func_qobject_qobject("String") == nil ) - assert( TestObject1.func_qobject_qobject(nil) == nil ) - - assert( TestObject1.func_bool_bool(true) == TestObject2.func_bool_bool(true) ) - assert( TestObject2.func_bool_bool(false) == TestObject2.func_bool_bool(false) ) - assert( TestObject1.func_int_int(82396) == TestObject2.func_int_int(82396) ) - assert( TestObject1.func_int_int(-672) == TestObject2.func_int_int(-672) ) - assert( TestObject1.func_qstringlist_qstringlist( ["s1","s2"] ) == TestObject2.func_qstringlist_qstringlist( ["s1","s2"] ) ) - - assert_raises(NameError) { TestObject1.ThisDoesNotExist } - assert_raises(TypeError) { TestObject1.findChild() } - assert_raises(TypeError) { TestObject1.findChild(123) } - assert_raises(TypeError) { TestObject1.findChild(nil,nil) } - - assert( TestObject1.TestTimer.objectName() == "TestTimer" ) - assert( TestObject1.findChild("TestTimer").objectName() == "TestTimer" ) - assert( TestObject1.findChild(nil,"TestTimer").objectName() == "TestTimer" ) - end - - def testProperties - TestObject1.boolProperty = true - assert( TestObject1.boolProperty == true ) - TestObject1.boolProperty = false - assert( TestObject1.boolProperty == false ) - - TestObject1.intProperty = 20 - assert( TestObject1.intProperty == 20 ) - - TestObject1.doubleProperty = 7436.671 - assert( TestObject1.doubleProperty == 7436.671 ) - - TestObject1.stringProperty = " SoMe StRiNg " - assert( TestObject1.stringProperty == " SoMe StRiNg " ) - - TestObject1.stringListProperty = [ "TestString", " Other String " ] - assert( TestObject1.stringListProperty == [ "TestString", " Other String " ] ) - - TestObject1.listProperty = [ true, [2464, -8295], -572.07516, "test", [] ] - assert( TestObject1.listProperty == [ true, [2464, -8295], -572.07516, "test", [] ] ) - end - - def testPropertyMethods - TestObject1.setProperty("boolProperty", false) - assert( TestObject1.boolProperty == false ) - TestObject1.setProperty("boolProperty", true) - assert( TestObject1.property("boolProperty") == true ) - TestObject1.setProperty("intProperty", -75825) - assert( TestObject1.property("intProperty") == -75825 ) - TestObject1.setProperty("doubleProperty", -9373.8721) - assert( TestObject1.property("doubleProperty") == -9373.8721 ) - TestObject1.setProperty("stringProperty", " AnOtHeR sTrInG ") - assert( TestObject1.property("stringProperty") == " AnOtHeR sTrInG " ) - TestObject1.setProperty("stringListProperty", ["s1","s2",""]) - assert( TestObject1.property("stringListProperty") == ["s1","s2",""] ) - TestObject1.setProperty("listProperty", [[true,false],"abc",[846,-573.02],[]]) - assert( TestObject1.property("listProperty") == [[true,false],"abc",[846,-573.02],[]] ) - end - - def testEnumerations - assert( TestObject1.TESTENUM1 == 1 ) - assert( TestObject1.TESTENUM2 == 2 ) - assert( TestObject1.TESTENUM3 == 4 ) - assert( TestObject1.TESTENUM4 == 8 ) - #self.assert_( self.object1.testEnum( self.object1.TESTENUM3 ) == 4 ) - end - - def testSignalString - @mySignalString = "" - def callbackSignalString(s) - @mySignalString = s - end - TestObject1.connect("signalString(const QString&)", method("callbackSignalString")) - TestObject1.signalString("Some string") - assert( @mySignalString == "Some string" ) - end - - def testSignalBool - @mySignalBool = nil - def callbackSignalBool(b) - @mySignalBool = b - end - TestObject1.connect("signalBool(bool)", method("callbackSignalBool")) - TestObject1.signalBool(true) - assert( @mySignalBool == true ) - TestObject1.signalBool(false) - assert( @mySignalBool == false ) - end - - #def testSignalObject - # @myTestObject = nil - # def callbackSignalObject(obj) - # @myTestObject = obj - # end - # TestObject1.connect("signalObject(QObject*)", method("callbackSignalObject")) - # TestObject1.signalObject(TestObject2) - # assert( @myTestObject == TestObject2 ) - #end - - def testClass - s = "my string" - myclass = MyClass.new(s) - assert(TestObject1.call_krossobject_method(myclass, "myMethod") == s) - end - - def testOtherObject - otherobj1 = TestObject1.func_otherobject("OtherObject1") - otherobj2 = TestObject1.func_otherobject("OtherObject2") - - assert(otherobj1.objectName == "OtherObject1_wrapper") - assert(otherobj2.parentObject().objectName == "OtherObject2") - assert(TestObject1.func_otherobject_otherobject(otherobj1).objectName == otherobj1.objectName) - - l = TestObject1.func_otherobjectlist_otherobjectlist( [otherobj1,otherobj2] ) - assert( l.size == 2 ) - assert( l[0].objectName == "OtherObject1_wrapper" ) - assert( l[1].parentObject().objectName == "OtherObject2" ) - end - - def testEvaluation - assert(KrossAction.evaluate("1+2") == 3) - assert(KrossAction.evaluate("testFunction1(nil)") == nil) - assert(KrossAction.evaluate("testFunction1(99)") == 99) - end - -end - -require 'test/unit/ui/console/testrunner' -Test::Unit::UI::Console::TestRunner.run(TestKross) - -#require "TestObject1" -#puts "=======> " + TestObject1.func_bool_bool(false).to_s() -#puts "=======> " + TestObject1.func_bool_bool(true).to_s() -#puts "=======> " + TestObject1.func_qpoint_qpoint( [0,0] ).inspect() diff --git a/kross/ui/CMakeLists.txt b/kross/ui/CMakeLists.txt deleted file mode 100644 index 1bfd630b..00000000 --- a/kross/ui/CMakeLists.txt +++ /dev/null @@ -1,43 +0,0 @@ -include_directories( - ${CMAKE_SOURCE_DIR} - ${KDE4_KDECORE_INCLUDES} - ${KDE4_KDEUI_INCLUDES} - ${KDE4_KIO_INCLUDES} -) - -set(krossui_LIB_SRCS - model.cpp - view.cpp - plugin.cpp - # guiclient.cpp -) - -add_library(krossui ${LIBRARY_TYPE} ${krossui_LIB_SRCS}) -target_link_libraries(krossui PUBLIC - ${KDE4_KDEUI_LIBS} - ${KDE4_KPARTS_LIBS} - ${KDE4_KIO_LIBS} - krosscore -) -set_target_properties(krossui PROPERTIES - VERSION ${GENERIC_LIB_VERSION} - SOVERSION ${GENERIC_LIB_SOVERSION} -) - -########### install files ############### - -install( - TARGETS krossui - EXPORT kdelibsLibraryTargets - ${INSTALL_TARGETS_DEFAULT_ARGS} -) - -install( - FILES - # guiclient.h - model.h - view.h - plugin.h - DESTINATION ${KDE4_INCLUDE_INSTALL_DIR}/kross/ui - COMPONENT Devel -) diff --git a/kross/ui/model.cpp b/kross/ui/model.cpp deleted file mode 100644 index 68cef769..00000000 --- a/kross/ui/model.cpp +++ /dev/null @@ -1,541 +0,0 @@ -/*************************************************************************** - * model.cpp - * This file is part of the KDE project - * copyright (C) 2006-2007 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#include "model.h" - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include - -using namespace Kross; - -/****************************************************************************** - * ActionCollectionModel - */ - -namespace Kross { - - /// \internal d-pointer class. - class ActionCollectionModel::Private - { - public: - QPointer collection; - Mode mode; - }; - -} - -ActionCollectionModel::ActionCollectionModel(QObject* parent, ActionCollection* collection, Mode mode) - : QAbstractItemModel(parent) - , d( new Private() ) -{ - //krossdebug( QString( "ActionCollectionModel::ActionCollectionModel:") ); - d->collection = collection ? collection : Kross::Manager::self().actionCollection(); - d->mode = mode; - //setSupportedDragActions(Qt::MoveAction); - - //ActionCollection propagates signals to parent - QObject::connect( d->collection, SIGNAL(dataChanged(Action*)), this, SLOT(slotDataChanged(Action*)) ); - QObject::connect( d->collection, SIGNAL(dataChanged(ActionCollection*)), this, SLOT(slotDataChanged(ActionCollection*)) ); - - QObject::connect( d->collection, SIGNAL(collectionToBeInserted(ActionCollection*,ActionCollection*)), this, SLOT(slotCollectionToBeInserted(ActionCollection*,ActionCollection*)) ); - QObject::connect( d->collection, SIGNAL(collectionInserted(ActionCollection*,ActionCollection*)), this, SLOT(slotCollectionInserted(ActionCollection*,ActionCollection*)) ); - QObject::connect( d->collection, SIGNAL(collectionToBeRemoved(ActionCollection*,ActionCollection*)), this, SLOT(slotCollectionToBeRemoved(ActionCollection*,ActionCollection*)) ); - QObject::connect( d->collection, SIGNAL(collectionRemoved(ActionCollection*,ActionCollection*)), this, SLOT(slotCollectionRemoved(ActionCollection*,ActionCollection*)) ); - - QObject::connect( d->collection, SIGNAL(actionToBeInserted(Action*,ActionCollection*)), this, SLOT(slotActionToBeInserted(Action*,ActionCollection*)) ); - QObject::connect( d->collection, SIGNAL(actionInserted(Action*,ActionCollection*)), this, SLOT(slotActionInserted(Action*,ActionCollection*)) ); - QObject::connect( d->collection, SIGNAL(actionToBeRemoved(Action*,ActionCollection*)), this, SLOT(slotActionToBeRemoved(Action*,ActionCollection*)) ); - QObject::connect( d->collection, SIGNAL(actionRemoved(Action*,ActionCollection*)), this, SLOT(slotActionRemoved(Action*,ActionCollection*)) ); -} - -ActionCollectionModel::~ActionCollectionModel() -{ - delete d; -} - -ActionCollection *ActionCollectionModel::rootCollection() const -{ - return d->collection; -} - -int ActionCollectionModel::rowNumber( ActionCollection *collection ) const -{ - Q_ASSERT( collection != 0 ); - ActionCollection *par = collection->parentCollection(); - Q_ASSERT( par != 0 ); - int row = par->collections().indexOf( collection->objectName() ) + par->actions().count(); - return row; -} - -QModelIndex ActionCollectionModel::indexForCollection( ActionCollection *collection ) const -{ - if ( collection == d->collection ) { - return QModelIndex(); - } - return createIndex( rowNumber( collection ), 0, collection->parentCollection() ); -} - -QModelIndex ActionCollectionModel::indexForAction( Action *act ) const -{ - ActionCollection *coll = static_cast( act->parent() ); - return createIndex( coll->actions().indexOf( act ), 0, coll ); -} - -void ActionCollectionModel::slotCollectionToBeInserted( ActionCollection* child, ActionCollection* parent ) -{ - //krossdebug( QString( "ActionCollectionModel::slotCollectionToBeInserted: %1 %2" ).arg( child->name() ).arg( parent->name( ) ) ); - Q_ASSERT( parent ); - Q_UNUSED( child ) - int row = parent->actions().count() + parent->collections().count(); // we assume child is appended!! - QModelIndex parIdx = indexForCollection( parent ); - beginInsertRows( parIdx, row, row ); -} - -void ActionCollectionModel::slotCollectionInserted( ActionCollection*, ActionCollection* ) -{ - //krossdebug( QString( "ActionCollectionModel::slotCollectionInserted: %1 %2" ).arg( child->name( ) ).arg( parent->name( ) ) ); - endInsertRows(); -} - -void ActionCollectionModel::slotCollectionToBeRemoved( ActionCollection* child, ActionCollection* parent ) -{ - //krossdebug( QString( "ActionCollectionModel::slotCollectionToBeRemoved: %1 %2" ).arg( child->name() ).arg( parent->name() ) ); - int row = rowNumber( child ); - QModelIndex parIdx = indexForCollection( parent ); - beginRemoveRows( parIdx, row, row ); -} - -void ActionCollectionModel::slotCollectionRemoved( ActionCollection*, ActionCollection* ) -{ - //krossdebug( QString( "ActionCollectionModel::slotCollectionRemoved: %1 %2" ).arg( child->name() ).arg( parent->name() ) ); - endRemoveRows(); -} - -void ActionCollectionModel::slotActionToBeInserted( Action* child, ActionCollection* parent ) -{ - //krossdebug( QString( "ActionCollectionModel::slotActionInserted: %1 %2" ).arg( child->name() ).arg( parent->name() ) ); - Q_ASSERT( parent ); - Q_UNUSED( child ) - int row = parent->actions().count(); // assume child is appended to actions!! - QModelIndex parIdx = indexForCollection( parent ); - beginInsertRows( parIdx, row, row ); -} - -void ActionCollectionModel::slotActionInserted( Action*, ActionCollection* ) -{ - //krossdebug( QString( "ActionCollectionModel::slotActionInserted: %1 %2" ).arg( child->name() ).arg( parent->name() ) ); - endInsertRows(); -} - -void ActionCollectionModel::slotActionToBeRemoved( Action* child, ActionCollection* parent ) -{ - //krossdebug( QString( "ActionCollectionModel::slotActionToBeRemoved: %1 %2" ).arg( child->name() ).arg( parent->name() ) ); - Q_ASSERT( parent ); - int row = parent->actions().indexOf( child ); - QModelIndex parIdx = indexForCollection( parent ); - beginRemoveRows( parIdx, row, row ); -} - -void ActionCollectionModel::slotActionRemoved( Action*, ActionCollection* ) -{ - //krossdebug( QString( "ActionCollectionModel::slotActionRemoved: %1 %2" ).arg( child->name() ).arg( parent->name() ) ); - endRemoveRows(); -} - -//NOTE: not used anymore, remove? -void ActionCollectionModel::slotUpdated() -{ - //emit layoutAboutToBeChanged(); - //emit layoutChanged(); -} - -void ActionCollectionModel::slotDataChanged( ActionCollection* coll ) -{ - //krossdebug( QString( "ActionCollectionModel::slotDataChanged: %1" ).arg( coll->name() ) ); - QModelIndex idx = indexForCollection( coll ); - emit dataChanged( idx, idx ); // NOTE: change if more than one column -} - -void ActionCollectionModel::slotDataChanged( Action* act ) -{ - //krossdebug( QString( "ActionCollectionModel::slotDataChanged: %1" ).arg( act->name() ) ); - QModelIndex idx = indexForAction( act ); - emit dataChanged( idx, idx ); // NOTE: change if more than one column -} - -Action* ActionCollectionModel::action(const QModelIndex& index) -{ - ActionCollection *par = static_cast( index.internalPointer() ); - if ( par == 0 || index.row() >= par->actions().count() ) { - return 0; - } - return par->actions().value( index.row() ); -} - -ActionCollection* ActionCollectionModel::collection(const QModelIndex& index) -{ - ActionCollection *par = static_cast( index.internalPointer() ); - if ( par == 0 ) { - return 0; - } - int row = index.row() - par->actions().count(); - if ( row < 0 ) { - return 0; // this is probably an action - } - return par->collection( par->collections().value( row) ); -} - -int ActionCollectionModel::columnCount(const QModelIndex&) const -{ - return 1; -} - -int ActionCollectionModel::rowCount(const QModelIndex& index) const -{ - if ( action( index) ) { - return 0; - } - ActionCollection* par = index.isValid() ? collection( index ) : d->collection.data(); - Q_ASSERT_X( par, "ActionCollectionModel::rowCount", "index is not an action nor a collection" ); - if (!par) { - kWarning()<<"index is not an action nor a collection"<actions().count() + par->collections().count(); - return rows; -} - -QModelIndex ActionCollectionModel::index(int row, int column, const QModelIndex& parent) const -{ - if ( ! hasIndex( row, column, parent ) ) { - return QModelIndex(); - } - ActionCollection* par = parent.isValid() ? collection( parent ) : d->collection.data(); - if ( par == 0 ) { - // safety: may happen if parent index is an action (ModelTest tests this) - return QModelIndex(); - } - return createIndex( row, column, par ); -} - -QModelIndex ActionCollectionModel::parent(const QModelIndex& index) const -{ - if( ! index.isValid() ) { - return QModelIndex(); - } - ActionCollection *par = static_cast( index.internalPointer() ); - Q_ASSERT( par != 0 ); - if ( par == d->collection ) { - return QModelIndex(); - } - return createIndex( rowNumber( par ), 0, par->parentCollection() ); -} - -Qt::ItemFlags ActionCollectionModel::flags(const QModelIndex &index) const -{ - Qt::ItemFlags flags = QAbstractItemModel::flags(index); - if( ! index.isValid() ) - return Qt::ItemIsDropEnabled | flags; - - flags |= Qt::ItemIsSelectable; - //flags |= Qt::ItemIsEditable; - flags |= Qt::ItemIsDragEnabled; - flags |= Qt::ItemIsDropEnabled; - - if( (index.column() == 0) && (d->mode & UserCheckable) ) - flags |= Qt::ItemIsUserCheckable; - return flags; -} - -QVariant ActionCollectionModel::data(const QModelIndex& index, int role) const -{ - if( index.isValid() ) { - Action *act = action( index ); - if ( act ) { - switch( role ) { - case Qt::DecorationRole: { - if( d->mode & Icons ) - if( ! act->iconName().isEmpty() ) - return act->icon(); - } break; - case Qt::DisplayRole: - return KGlobal::locale()->removeAcceleratorMarker( act->text() ); - case Qt::ToolTipRole: // fall through - case Qt::WhatsThisRole: { - if( d->mode & ToolTips ) { - const QString file = QFileInfo( act->file() ).fileName(); - return QString( "%1
%2
" ) - .arg( file.isEmpty() ? act->name() : file ) - .arg( act->description() ); - } - } break; - case Qt::CheckStateRole: { - if( d->mode & UserCheckable ) - return act->isEnabled() ? Qt::Checked : Qt::Unchecked; - } break; - default: break; - } - return QVariant(); - } - ActionCollection *coll = collection( index ); - if ( coll ) { - switch( role ) { - case Qt::DecorationRole: { - if( d->mode & Icons ) - if( ! coll->iconName().isEmpty() ) - return coll->icon(); - } break; - case Qt::DisplayRole: - return coll->text(); - case Qt::ToolTipRole: // fall through - case Qt::WhatsThisRole: { - if( d->mode & ToolTips ) - return QString( "%1
%2
" ).arg( coll->text() ).arg( coll->description() ); - } break; - case Qt::CheckStateRole: { - if( d->mode & UserCheckable ) - return coll->isEnabled() ? Qt::Checked : Qt::Unchecked; - } break; - default: break; - } - return QVariant(); - } - } - return QVariant(); -} - -bool ActionCollectionModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ - Q_UNUSED(value); - if( ! index.isValid() /*|| ! (d->mode & UserCheckable)*/ ) - return false; - - Action *act = action( index ); - if ( act ) { - switch( role ) { - //case Qt::EditRole: act->setText( value.toString() ); break; - case Qt::CheckStateRole: act->setEnabled( ! act->isEnabled() ); break; - default: return false; - } - return false; - } - ActionCollection *coll = collection( index ); - if ( coll ) { - switch( role ) { - //case Qt::EditRole: item->coll->setText( value.toString() ); break; - case Qt::CheckStateRole: coll->setEnabled( ! coll->isEnabled() ); break; - default: return false; - } - return false; - } - //emit dataChanged(index, index); - return true; -} - -bool ActionCollectionModel::insertRows(int row, int count, const QModelIndex& parent) -{ - krossdebug( QString("ActionCollectionModel::insertRows: row=%1 count=%2").arg(row).arg(count) ); - if( ! parent.isValid() ) - return false; - - ActionCollection* coll = collection( parent ); - if ( coll ) { - krossdebug( QString( "ActionCollectionModel::insertRows: parentindex is ActionCollection with name=%1" ).arg( coll->name() ) ); - } else { - Action *act = action( parent ); - if ( act ) { - krossdebug( QString( "ActionCollectionModel::insertRows: parentindex is Action with name=%1" ).arg( act->name() ) ); - } - } - return QAbstractItemModel::insertRows(row, count, parent); -} - -bool ActionCollectionModel::removeRows(int row, int count, const QModelIndex& parent) -{ - krossdebug( QString("ActionCollectionModel::removeRows: row=%1 count=%2").arg(row).arg(count) ); - return QAbstractItemModel::removeRows(row, count, parent); -} - -bool ActionCollectionModel::insertColumns(int column, int count, const QModelIndex& parent) -{ - krossdebug( QString("ActionCollectionModel::insertColumns: column=%1 count=%2").arg(column).arg(count) ); - return QAbstractItemModel::insertColumns(column, count, parent); -} - -bool ActionCollectionModel::removeColumns(int column, int count, const QModelIndex& parent) -{ - krossdebug( QString("ActionCollectionModel::removeColumns: column=%1 count=%2").arg(column).arg(count) ); - return QAbstractItemModel::removeColumns(column, count, parent); -} - -QStringList ActionCollectionModel::mimeTypes() const -{ - //krossdebug( QString("ActionCollectionModel::mimeTypes") ); - return QStringList() << "application/vnd.text.list"; -} - -QString fullPath(const QModelIndex& index) -{ - if( ! index.isValid() ) return QString(); - QString n; - Action *a = ActionCollectionModel::action( index ); - if ( a ) { - n = a->name(); - } else { - ActionCollection *c = ActionCollectionModel::collection( index ); - if ( c ) { - n = c->name() + '/'; - if ( ! n.endsWith('/' ) ) - n += '/'; - } - } - ActionCollection* par = static_cast( index.internalPointer() ); - for ( ActionCollection *p = par; p != 0; p = par->parentCollection() ) { - QString s = p->name(); - if ( ! s.endsWith( '/' ) ) { - s += '/'; - } - n = s + n; - } - return n; -} - -QMimeData* ActionCollectionModel::mimeData(const QModelIndexList& indexes) const -{ - //krossdebug( QString("ActionCollectionModel::mimeData") ); - QMimeData* mimeData = new QMimeData(); - QByteArray encodedData; - - QDataStream stream(&encodedData, QIODevice::WriteOnly); - foreach(const QModelIndex &index, indexes) { - //if( ! index.isValid() ) continue; - //QString text = data(index, Qt::DisplayRole).toString(); - QString path = fullPath(index); - if( ! path.isNull() ) - stream << path; - } - - mimeData->setData("application/vnd.text.list", encodedData); - return mimeData; -} - -bool ActionCollectionModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) -{ - krossdebug( QString("ActionCollectionModel::dropMimeData: row=%1 col=%2").arg(row).arg(column) ); - if( action == Qt::IgnoreAction ) return true; - if( ! data->hasFormat("application/vnd.text.list") ) return false; - if( column > 0 ) return false; - - krossdebug( QString("ActionCollectionModel::dropMimeData: ENCODED DATA:") ); - QByteArray encodedData = data->data("application/vnd.text.list"); - QDataStream stream(&encodedData, QIODevice::ReadOnly); - QStringList newItems; - int rows = 0; - while( ! stream.atEnd() ) { - QString text; - stream >> text; - newItems << text; - krossdebug( QString(" %1 \"%2\"").arg(rows).arg(text) ); - ++rows; - } - - //FIXME: return false for now since insertRows/removeRows need to be implemented before! - //return false; - - /* - int beginRow; - if( row != -1 ) - beginRow = row; - else if( parent.isValid() ) - beginRow = parent.row(); - else - beginRow = rowCount( QModelIndex() ); - krossdebug( QString("ActionCollectionModel::dropMimeData: beginRow=%1").arg(beginRow) ); - */ - - QModelIndex targetindex = index( row, column, parent ); - ActionCollection *coll = collection( targetindex ); - if ( coll ) { - krossdebug( QString( "ActionCollectionModel::dropMimeData: parentindex is ActionCollection with name=%1" ).arg( coll->name() ) ); - } else { - Action *act = this->action( targetindex ); - if ( act ) { - krossdebug( QString( "ActionCollectionModel::dropMimeData: parentindex is Action with name=%1" ).arg( act->name() ) ); - } - } - return false; - //return QAbstractItemModel::dropMimeData(data, action, row, column, parent); -} - -Qt::DropActions ActionCollectionModel::supportedDropActions() const -{ - return Qt::CopyAction | Qt::MoveAction; - //return Qt::CopyAction | Qt::MoveAction | Qt::LinkAction; -} - -/****************************************************************************** - * ActionCollectionProxyModel - */ - -ActionCollectionProxyModel::ActionCollectionProxyModel(QObject* parent, ActionCollectionModel* model) - : QSortFilterProxyModel(parent) -{ - setSourceModel( model ? model : new ActionCollectionModel(this) ); - setFilterCaseSensitivity(Qt::CaseInsensitive); - setDynamicSortFilter(true); -} - -ActionCollectionProxyModel::~ActionCollectionProxyModel() -{ -} - -void ActionCollectionProxyModel::setSourceModel(QAbstractItemModel* sourceModel) -{ - Q_ASSERT( dynamic_cast< ActionCollectionModel* >(sourceModel) ); - QSortFilterProxyModel::setSourceModel(sourceModel); -} - -bool ActionCollectionProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const -{ - //krossdebug( QString( "ActionCollectionProxyModel::filterAcceptsRow: row=%1 parentrow=%2" ).arg( source_row ).arg( source_parent.row() ) ); - QModelIndex index = sourceModel()->index(source_row, 0, source_parent); - if( ! index.isValid() ) - return false; - - Action *action = ActionCollectionModel::action( index ); - if ( action ) { - return action->isEnabled() && QSortFilterProxyModel::filterAcceptsRow( source_row, source_parent ); - } - ActionCollection *collection = ActionCollectionModel::collection( index ); - if( collection ) { - return collection->isEnabled(); - } - return true; -} - -#include "moc_model.cpp" diff --git a/kross/ui/model.h b/kross/ui/model.h deleted file mode 100644 index 7263bc5a..00000000 --- a/kross/ui/model.h +++ /dev/null @@ -1,144 +0,0 @@ -/*************************************************************************** - * model.h - * This file is part of the KDE project - * copyright (C) 2006-2007 by Sebastian Sauer (mail@dipe.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 of the License, 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 - * Library General Public License for more details. - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ***************************************************************************/ - -#ifndef KROSS_MODEL_H -#define KROSS_MODEL_H - -#include - -#include -#include - -namespace Kross { - - // Forward declarations. - class Action; - class ActionCollection; - class ActionCollectionModelItem; - - /** - * The ActionCollectionModel class implements a QAbstractItemModel to provide - * a model for views of a \a ActionCollection instance that manages a - * collection of \a Action instances. - * - * Important implementation detatils: - * \li An action can not have children. - * \li A collection can have both collections and actions as children. - * \li This model lists actions before collections. - * \li The internalPointer() of QModelIndex is used to hold a pointer to the parent collection. - */ - class KROSS_EXPORT ActionCollectionModel : public QAbstractItemModel - { - Q_OBJECT - public: - enum Mode { - None = 0, - Icons = 1, - ToolTips = 2, - UserCheckable = 4 - //Editable = 8 - }; - - explicit ActionCollectionModel(QObject* parent, ActionCollection* collection = 0, Mode mode = Mode(Icons|ToolTips)); - virtual ~ActionCollectionModel(); - - virtual int columnCount(const QModelIndex& parent = QModelIndex()) const; - virtual int rowCount(const QModelIndex& parent = QModelIndex()) const; - virtual QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const; - virtual QModelIndex parent(const QModelIndex& index) const; - virtual Qt::ItemFlags flags(const QModelIndex &index) const; - virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); - - virtual bool insertRows(int row, int count, const QModelIndex& parent = QModelIndex()); - virtual bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex()); - virtual bool insertColumns(int column, int count, const QModelIndex& parent = QModelIndex()); - virtual bool removeColumns(int column, int count, const QModelIndex& parent = QModelIndex()); - - //Qt::DropActions supportedDragActions() const; - virtual QStringList mimeTypes() const; - virtual QMimeData* mimeData(const QModelIndexList& indexes) const; - virtual bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent); - - virtual Qt::DropActions supportedDropActions() const; - - QModelIndex indexForCollection( ActionCollection *collection ) const; - QModelIndex indexForAction( Action *action ) const; - /// Return the root collection - ActionCollection *rootCollection() const; - - /** - * \return the \a Action instance the as argument passed QModelIndex - * represents or NULL if the QModelIndex is not a \a Action . - */ - static Action* action(const QModelIndex& index); - - /** - * \return the \a ActionCollection instance the as argument passed QModelIndex - * represents or NULL if the QModelIndex is not a \a ActionCollection . - */ - static ActionCollection* collection(const QModelIndex& index); - - protected: - /// @returns the row number of the @p collection - int rowNumber( ActionCollection *collection ) const; - - private Q_SLOTS: - void slotUpdated(); - - void slotDataChanged( ActionCollection* ); - void slotDataChanged( Action* ); - - void slotCollectionToBeInserted( ActionCollection* child, ActionCollection* parent ); - void slotCollectionInserted( ActionCollection* child, ActionCollection* parent ); - void slotCollectionToBeRemoved( ActionCollection* child, ActionCollection* parent ); - void slotCollectionRemoved( ActionCollection* child, ActionCollection* parent ); - - void slotActionToBeInserted( Action* child, ActionCollection* parent ); - void slotActionInserted( Action* child, ActionCollection* parent ); - void slotActionToBeRemoved( Action* child, ActionCollection* parent ); - void slotActionRemoved( Action* child, ActionCollection* parent ); - private: - /// \internal d-pointer class. - class Private; - /// \internal d-pointer instance. - Private* const d; - }; - - /** - * The ActionCollectionProxyModel class implements a QSortFilterProxyModel - * for a \a ActionCollectionModel instance. - */ - class KROSS_EXPORT ActionCollectionProxyModel : public QSortFilterProxyModel - { - public: - explicit ActionCollectionProxyModel(QObject* parent, ActionCollectionModel* model = 0); - virtual ~ActionCollectionProxyModel(); - - private: - /// Set the \a ActionCollectionModel source model we are proxy for. - virtual void setSourceModel(QAbstractItemModel* sourceModel); - /// Implements a filter for the QModelIndex instances. - virtual bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const; - }; - -} - -#endif - diff --git a/kross/ui/plugin.cpp b/kross/ui/plugin.cpp deleted file mode 100644 index 7e5107f7..00000000 --- a/kross/ui/plugin.cpp +++ /dev/null @@ -1,266 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2008 Paulo Moura Guedes - - 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 "plugin.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace Kross; - -struct Object -{ - QPointer object; - ChildrenInterface::Options options; - Object(QObject* obj, ChildrenInterface::Options opt):object(obj),options(opt){} -}; - - -/// \internal d-pointer class -class ScriptingPlugin::ScriptingPluginPrivate -{ -public: - QString collectionName; - QString userActionsFile; - QString referenceActionsDir; - QHash objects; - - QDomElement menuFromName(QString const& name, const QDomDocument& document) - { - QDomElement menuBar = document.documentElement().firstChildElement("MenuBar"); - QDomElement menu = menuBar.firstChildElement("Menu"); - for(; !menu.isNull(); menu = menu.nextSiblingElement("Menu")) { - if(menu.attribute("name") == name) { - return menu; - } - } - return QDomElement(); - } -}; - -ScriptingPlugin::ScriptingPlugin(QObject* parent) - : KParts::Plugin(parent) - , d(new ScriptingPluginPrivate()) -{ - d->userActionsFile = KGlobal::dirs()->locateLocal("appdata", "scripts/scriptactions.rc"); - d->collectionName="scripting-plugin"; -} - -ScriptingPlugin::ScriptingPlugin(const QString& collectionName, const QString& userActionsFile, const QString& referenceActionsDir, QObject* parent) - : KParts::Plugin(parent) - , d(new ScriptingPluginPrivate()) -{ - d->collectionName=collectionName; - d->userActionsFile = userActionsFile; - d->referenceActionsDir = referenceActionsDir; -} - -ScriptingPlugin::~ScriptingPlugin() -{ - if (QFile::exists(d->userActionsFile)) - save(); - - Kross::ActionCollection* collection=Kross::Manager::self().actionCollection()->collection(d->collectionName); - if (collection) { - collection->setParentCollection(0); - collection->deleteLater(); - } - - delete d; -} - -void ScriptingPlugin::setDOMDocument(const QDomDocument &document, bool merge) -{ - QDomDocument doc = buildDomDocument(document); - KXMLGUIClient::setDOMDocument(doc, merge); -} - -void ScriptingPlugin::addObject(QObject* object, const QString& name) -{ - QString n = name.isNull() ? object->objectName() : name; - d->objects.insert(n, Object(object,ChildrenInterface::NoOption)); -} - -void ScriptingPlugin::addObject(QObject* object, const QString& name, ChildrenInterface::Options options) -{ - QString n = name.isNull() ? object->objectName() : name; - d->objects.insert(n, Object(object,options)); -} - -QDomDocument ScriptingPlugin::buildDomDocument(const QDomDocument& document) -{ - Kross::ActionCollection* collection=Kross::Manager::self().actionCollection()->collection(d->collectionName); - if (!collection) { - collection=new Kross::ActionCollection(d->collectionName, Kross::Manager::self().actionCollection()); - } - - QStringList allActionFiles = KGlobal::dirs()->findAllResources("appdata", "scripts/"+d->referenceActionsDir+"/*.rc"); - //move userActionsFile to the end so that it updates existing actions and adds new ones. - int pos=allActionFiles.indexOf(d->userActionsFile); - if (pos!=-1) - allActionFiles.append(allActionFiles.takeAt(pos)); - else if (QFile::exists(d->userActionsFile)) //in case d->userActionsFile isn't in the standard local dir - allActionFiles.append(d->userActionsFile); - - QStringList searchPath=KGlobal::dirs()->findDirs("appdata", "scripts/"+d->referenceActionsDir); - foreach(const QString &file, allActionFiles) { - QFile f(file); - if (!f.open(QIODevice::ReadOnly)) - continue; - - collection->readXml(&f, searchPath+QStringList(QFileInfo(f).absolutePath())); - f.close(); - - } - - QDomDocument doc(document); - buildDomDocument(doc, collection); - - return doc; -} - -void ScriptingPlugin::buildDomDocument(QDomDocument& document, - Kross::ActionCollection* collection) -{ - QDomElement menuElement = d->menuFromName(collection->name(), document); - - foreach(Kross::Action* action, collection->actions()) { - QHashIterator i(d->objects); - while(i.hasNext()) { - i.next(); - action->addObject(i.value().object, i.key(), i.value().options); - } - - // Create and append new Menu element if doesn't exist - if(menuElement.isNull()) { - menuElement = document.createElement("Menu"); - menuElement.setAttribute("name", collection->name()); - menuElement.setAttribute("noMerge", "0"); - - QDomElement textElement = document.createElement("text"); - textElement.appendChild(document.createTextNode(collection->text())); - menuElement.appendChild(textElement); - - Kross::ActionCollection* parentCollection = collection->parentCollection(); - QDomElement root; - if(parentCollection) { - QDomElement parentMenuElement = d->menuFromName(parentCollection->name(), document); - if(!parentMenuElement.isNull()) - root=parentMenuElement; - } - if (root.isNull()) - root=document.documentElement().firstChildElement("MenuBar"); - root.appendChild(menuElement); - } - - // Create and append new Action element - QDomElement newActionElement = document.createElement("Action"); - newActionElement.setAttribute("name", action->name()); - - menuElement.appendChild(newActionElement); - - - KAction* adaptor=new KAction(action->text(), action); - connect (adaptor,SIGNAL(triggered()),action,SLOT(trigger())); - adaptor->setEnabled(action->isEnabled()); - adaptor->setIcon(action->icon()); - actionCollection()->addAction(action->name(), adaptor); - } - - foreach(const QString &collectionname, collection->collections()) { - Kross::ActionCollection* c = collection->collection(collectionname); - if(c->isEnabled()) { - buildDomDocument(document, c); - } - } -} - -void ScriptingPlugin::save() -{ - QFile f(d->userActionsFile); - if(!f.open(QIODevice::WriteOnly)) - return; - - Kross::ActionCollection* collection=Kross::Manager::self().actionCollection()->collection(d->collectionName); - bool collectionEmpty = !collection||(collection->actions().empty()&&collection->collections().empty()); - - if( !collectionEmpty ) { - QStringList searchPath=KGlobal::dirs()->findDirs("appdata", "scripts/"+d->referenceActionsDir); - searchPath.append(QFileInfo(d->userActionsFile).absolutePath()); - if( collection->writeXml(&f, 2, searchPath) ) { - kDebug() << "Successfully saved file: " << d->userActionsFile; - } - } - else { - QTextStream out(&f); - QString xml= - ""; - - - out << xml; - } - f.close(); -} - -void ScriptingPlugin::slotEditScriptActions() -{ - if(!KIO::NetAccess::exists(KUrl(d->userActionsFile), KIO::NetAccess::SourceSide, 0)) { - KUrl dir = KUrl(d->userActionsFile).directory(); - KIO::NetAccess::mkdir(dir, 0); - - save(); - } - - //TODO very funny! this should use ui/view.h instead --Nick - KRun::runUrl(KUrl(d->userActionsFile), QString("text/plain"), 0, false); -} - -void ScriptingPlugin::slotResetScriptActions() -{ - KIO::NetAccess::del(KUrl(d->userActionsFile), 0); -} - -#include "moc_plugin.cpp" diff --git a/kross/ui/plugin.h b/kross/ui/plugin.h deleted file mode 100644 index b1552581..00000000 --- a/kross/ui/plugin.h +++ /dev/null @@ -1,126 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2008 Paulo Moura Guedes - - 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 KROSS_PLUGIN_H -#define KROSS_PLUGIN_H - -#include - -#include -#include - -namespace Kross { - class ActionCollection; -} - -#include - -namespace Kross -{ - -/** - * The ScriptingPlugin class loads additional actions stored in rc files with the - * KrossScripting format: - * - * \code - * - * - *