diff options
author | No'am Rosenthal <noam.rosenthal@nokia.com> | 2009-11-07 18:25:17 -0800 |
---|---|---|
committer | No'am Rosenthal <noam.rosenthal@nokia.com> | 2009-11-07 18:25:17 -0800 |
commit | c39312db7feaa9c698d48f58510a552209c41163 (patch) | |
tree | 9e5aaa3bc902a758afa76efb2b387809dcad66c3 | |
parent | 971072b2b14c6bcd356f79c43b1fc56974fb7134 (diff) |
statechartz branch: only for webdev
55 files changed, 0 insertions, 6276 deletions
diff --git a/doc/classic.css b/doc/classic.css deleted file mode 100644 index 3704a15..0000000 --- a/doc/classic.css +++ /dev/null @@ -1,199 +0,0 @@ -BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV { - font-family: Geneva, Arial, Helvetica, sans-serif; -} -BODY,TD { - font-size: 90%; -} -H1 { - text-align: center; - font-size: 160%; -} -H2 { - font-size: 120%; -} -H3 { - font-size: 100%; -} - -h3.fn,span.fn -{ - background-color: #d5e1e8; - border-width: 1px; - border-style: solid; - border-color: #84b0c7; - font-weight: bold; - -moz-border-radius: 8px 8px 8px 8px; - padding: 6px 0px 6px 10px; -} - -a:link -{ - color: #004faf; - text-decoration: none -} - -a:visited -{ - color: #672967; - text-decoration: none -} - -a.obsolete -{ - color: #661100; - text-decoration: none -} - -a.compat -{ - color: #661100; - text-decoration: none -} - -a.obsolete:visited -{ - color: #995500; - text-decoration: none -} - -a.compat:visited -{ - color: #995500; - text-decoration: none -} - -td.postheader -{ - font-family: sans-serif -} - -tr.address -{ - font-family: sans-serif -} - -body -{ - background: #ffffff; - color: black -} - -table td.memItemLeft { - width: 200px; - padding: 1px 0px 0px 8px; - margin: 4px; - border-top-width: 1px; - border-right-width: 1px; - border-bottom-width: 1px; - border-left-width: 1px; - border-top-color: #E0E0E0; - border-right-color: #E0E0E0; - border-bottom-color: #E0E0E0; - border-left-color: #E0E0E0; - border-top-style: solid; - border-right-style: none; - border-bottom-style: none; - border-left-style: none; - background-color: #FAFAFA; - font-size: 80%; -} -table td.memItemRight { - padding: 1px 8px 0px 8px; - margin: 4px; - border-top-width: 1px; - border-right-width: 1px; - border-bottom-width: 1px; - border-left-width: 1px; - border-top-color: #E0E0E0; - border-right-color: #E0E0E0; - border-bottom-color: #E0E0E0; - border-left-color: #E0E0E0; - border-top-style: solid; - border-right-style: none; - border-bottom-style: none; - border-left-style: none; - background-color: #FAFAFA; - font-size: 80%; -} - -table tr.odd { - background: #f0f0f0; - color: black; -} - -table tr.even { - background: #e4e4e4; - color: black; -} - -table.annotated th { - padding: 3px; - text-align: left -} - -table.annotated td { - padding: 3px; -} - -table tr pre -{ - padding-top: none; - padding-bottom: none; - padding-left: none; - padding-right: none; - border: none; - background: none -} - -tr.qt-style -{ - background: #96E066; - color: black -} - -body pre -{ - padding: 0.2em; - border: #e7e7e7 1px solid; - background: #f1f1f1; - color: black -} - -table tr.qt-code pre -{ - padding: 0.2em; - border: #e7e7e7 1px solid; - background: #f1f1f1; - color: black -} - -span.preprocessor, span.preprocessor a -{ - color: darkblue; -} - -span.comment -{ - color: darkred; - font-style: italic -} - -span.string,span.char -{ - color: darkgreen; -} - -.title -{ - text-align: center -} - -.subtitle -{ - font-size: 0.8em -} - -.small-subtitle -{ - font-size: 0.65em -} diff --git a/doc/scxml.qdoc b/doc/scxml.qdoc deleted file mode 100644 index d0211ba..0000000 --- a/doc/scxml.qdoc +++ /dev/null @@ -1,208 +0,0 @@ -/*! - \page scxml.html - \title Using SCXML files in Qt - \ingroup sctools - \brief An overview of the sctools module, which allows loading scripted state charts with SCXML - - \tableofcontents - - The sctools module allows loading SCXML files into a QtScriptedStateMachine object. - - The files that the tool can load conform to the \l{State Chart XML: State Machine Notation for Control Abstraction}{State Chart XML (SCXML)} standard. - - \section1 Getting Started with Qt & SCXML - \list - \i First of all, make yourself familiar with the \l{State Chart XML: State Machine Notation for Control Abstraction}{SCXML specification}. - \i Read this document to understand how to enable SCXML files in your project, and how to load SCXML files in runtime/build-time. - \i Go over the blackjack, calc and mediaplayer examples for usage demonstration. - \endlist - - \section1 Enabling the QtScriptedStateMachine class - - The \l QtScriptedStateMachine class is enabled automatically when the script module is enabled. - - \section1 Using the QtScriptedStateMachine class - - QtScriptedStateMachine is a subclass of QtStateMachine. QtStateMachine actually includes most of the - "interesting" API, while QtScriptedStateMachine adds the missing parts to support SCXML. - - Most of the interaction with QtScriptedStateMachine occurs after the state-machine is loaded, - and before it's started. - The interesting functionalities of QtScriptedStateMachine are: - \section2 Working with the script engine - - The main feature of \l QtScriptedStateMachine is that it includes a single \a QScriptEngine object that's - shared between all state actions and transitions. That's what allows the states to rely on a single - data context for evaluating conditions and executing the entry/exit/transition actions. - - A very useful function is \l QtScriptedStateMachine::registerObject(), which allows you to add an object - (and optionally all its descendants) to the scripting context. - \l QtScriptedStateMachine::scriptEngine() allows you to manipulate the scripting context directly. - Use the mediaplayer example as a reference for using the registerObject function. - - - \section2 Connecting the state-machine to signals/slots - - A simpler way to interact with the state machine is through signals and slots. - The slot \l QtScriptedStateMachine::postNamedEvent() and the signal \l QtScriptedStateMachine::eventTriggered() - allow for a simple interaction with the state machine, as you can connect signals to postNamedEvent - and eventTriggered to and signal/slot. - - There are no entered/exited signals from states, as that would make the state-machines less deterministic - and would create results that are difficult to manage and predict (does the signal get emitted before, - after or during the normal execution list?) - - The calc example shows the usage of \l QtScriptedStateMachine::postNamedEvent(). - - \section2 Extending the state-machine with custom invokers - - A custom invoker allows you to write your own \l{http://www.w3.org/TR/scxml/#Invoke}{invoke} tags, and implement specific invoke types, - as described in the SCXML standard. - - To create a custom invoker, you must subclass from \l QtSsmInvoker, and implement at least: - \list - \i A constructor with \l QtScriptedEvent and \l QtStateMachine arguments - \i The \l QtSsmInvoker::activate() function - \i A static bool isTypeSupportedString(QString) function, conforms to the \l {http://www.w3.org/TR/scxml/#Invoke}{invoke} element's type attribute - \i A static void initInvokerFactory(QtScriptedStateMachine*) function, allows some initialization (like adding properties to the script engine) - \endlist - - - When these terms are met, you can create an invoke-factory, and register it to the state machine. - Example: - \code - #include <QtScriptedStateMachine> - - class MyInvoker : public QtSsmInvoker - { - Q_OBJECT - public: - MyInvoker(QtScriptedEvent* ievent, QtScriptedStateMachine* p) : QtSsmInvoker(ievent,p),menu(0) - { - } - static void initInvokerFactory(QtScriptedStateMachine* machine) - { - machine->scriptEngine()->globalObject().setProperty("some-name",someValue); - } - static bool isTypeSupported (const QString & s) { return s== "my-type"; } - public Q_SLOTS: - void activate () - { - doSomeStuff (); - } - }; - ... - static QSsmAutoInvokerFactory<MyInvoker> _s_factory; - myScriptedStateMachine->registerInvoker(&_s_factory); - - \endcode - - The initEvent protected member can be used to access the parameters - given to the invoker by the calling state machine. \l QtSsmInvoker::postParentEvent() - allows sending events back to the calling state machine. - - - - - - \section1 Loading SCXML files at runtime - - To load SCXML files in runtime, the static function \l QtScriptedStateMachine::load() must be used. - Note that this function requires the xmlpatterns and xml modules to be enabled. - \l QtScriptedStateMachine::load() it creates a new \l QtScriptedStateMachine object. - An example code would be: - -\code - #include "qscriptedstatemachine.h" - - // some code - QtScriptedStateMachine* stateMachine = QtScriptedStateMachine::load ("path-to-some-file.scxml"); - // ... register some objects, handle some stuff in the script engine... - stateMachine->start (); -\endcode - - - \section1 Supported SCXML tags and features - -Though most of the SCXML features are supported in this implementation, the support is incomplete, -partially because the spec itself is still evolving. This documentation tries to capture most of the -gaps and differences. - - \section2 Fully supported elements - The tags \l {http://www.w3.org/TR/scxml/#state}{state}, \l {http://www.w3.org/TR/scxml/#parallel}{parallel}, \l {http://www.w3.org/TR/scxml/#final}{final}, \l {http://www.w3.org/TR/scxml/#onentry}{onentry}, \l {http://www.w3.org/TR/scxml/#onexit}{onexit}, \l {http://www.w3.org/TR/scxml/#raise}{raise}, \l {http://www.w3.org/TR/scxml/#if}{if}, \l {http://www.w3.org/TR/scxml/#elseif}{elseif}, \l {http://www.w3.org/TR/scxml/#else}{else}, \l {http://www.w3.org/TR/scxml/#log}{log}, \l {http://www.w3.org/TR/scxml/#cancel}{cancel}, \l {http://www.w3.org/TR/scxml/#datamodel}{datamodel},\l {http://www.w3.org/TR/scxml/#data}{data}, \l {http://www.w3.org/TR/scxml/#assign}{assign}, \l {http://www.w3.org/TR/scxml/#param}{param}, ands \l {http://www.w3.org/TR/scxml/#anchor}{anchor} are fully supported according to the scxml spec. - - \section2 Partially supported elements - \list - \i \l {http://www.w3.org/TR/scxml/#scxml}{scxml}: The attributes version, profile and exmode are ignored. - \i \l {http://www.w3.org/TR/scxml/#initial}{initial}: Treated as a regular state that's marked as initial for the parent state. - \i \l {http://www.w3.org/TR/scxml/#history}{history}: Actions in the history's default transition are ignored. - \i \l {http://www.w3.org/TR/scxml/#content}{content}: Supports only JSON data, not XML. - \i \l {http://www.w3.org/TR/scxml/#send}{send}: only the scxml target type is supported. The id attribute is ignored. - \i \l {http://www.w3.org/TR/scxml/#invoke}{invoke}: the autoforward and id tags are ignored. - \endlist - - \section2 Unsupported elements - The elements \l {http://www.w3.org/TR/scxml/#Donedata}{donedata}, \l {http://www.w3.org/TR/scxml/#Finalize}{finalize} and \l {http://www.w3.org/TR/scxml/#Validate}{validate} are not supported. - Also, the local/global script scoping functionality is not implemented. - - \section2 Extras - \section3 Signal transitions - To declare a signal transition, use a transition tag with a q-signal uri scheme. - Example: - \code - <transition target="someState" event="q-signal:someObject.someSignal()" /> - \endcode - - \section3 Property binding - The q-binding invoker can be used to setup properties on entry, that are restored on exit. - Note that if the properties are changed externally while the state is active, the properties - would still be restored. - - The binding invoke element accepts a content tag with a JSON array, of which each element is a 3-item - array: [object, property-name, property-value]. - - Example: - - \code - <invoke type="q-bindings"><content> - [[myObject,"someProperty",someValue1 + someValue2], - [myObject,"text","hello"]] - </content></invoke> - \endcode - - \section3 Menus - A custom invoker added to the solution is the "q-menu" invoker. This invoker allows you to display a - QMenu and listen to its events. - The q-menu invoker should a content tag, which includes an expression evaluating to an ecmascript - object defining the menu. - Note that support for menus is currently experimental, and the mediaplayer example demonstrates its use. - - \section3 Message Boxes - Similar to q-menus, the "q-messagebox" invoker lets you show a QMessageBox and react to - the user interactions with it. - - The q-messagebox invoker accepts an ecmascript object that contains name/value pairs for the QMessageBox - properties. - - Example: - \code - <invoke type="q-messagebox"> - <content> - { - "parent" : myParentWidget, - "icon" : QMessageBox.Question, - "windowTitle" : "Would you like to exit?", - "text" : "Are you sure?", - "standardButtons" : QMessageBox.Yes|QMessageBox.No - } - </content> - </invoke> - \endcode - - See the blackjack example for reference. - - - - - - */ diff --git a/doc/scxml.qdocconf b/doc/scxml.qdocconf deleted file mode 100644 index 8fcf8fa..0000000 --- a/doc/scxml.qdocconf +++ /dev/null @@ -1,192 +0,0 @@ -# Run qdoc from the directory that contains this file. - -project = qscxml -description = Qt SCXML - -headerdirs = ../src -sourcedirs = ../src -imagedirs = src/images -outputdir = html - -extraimages.HTML = qt-logo - -headers.fileextesnions = "*.h" -sources.fileextensions = "*.cpp *.qdoc" - - -# macros.qdocconf - -macro.aring.HTML = "å" -macro.Auml.HTML = "Ä" -macro.author = "\\bold{Author:}" -macro.br.HTML = "<br />" -macro.BR.HTML = "<br />" -macro.aacute.HTML = "á" -macro.eacute.HTML = "é" -macro.iacute.HTML = "í" -macro.gui = "\\bold" -macro.hr.HTML = "<hr />" -macro.key = "\\bold" -macro.menu = "\\bold" -macro.note = "\\bold{Note:}" -macro.oslash.HTML = "ø" -macro.ouml.HTML = "ö" -macro.QA = "\\e{Qt Assistant}" -macro.QD = "\\e{Qt Designer}" -macro.QL = "\\e{Qt Linguist}" -macro.param = "\\e" -macro.raisedaster.HTML = "<sup>*</sup>" -macro.reg.HTML = "<sup>®</sup>" -macro.return = "Returns" -macro.starslash = "\\c{*/}" -macro.uuml.HTML = "ü" -macro.mdash.HTML = "—" - -# compat.qdocconf - -alias.i = e -alias.include = input - -macro.0 = "\\\\0" -macro.b = "\\\\b" -macro.n = "\\\\n" -macro.r = "\\\\r" -macro.i = "\\o" -macro.i11 = "\\o{1,1}" -macro.i12 = "\\o{1,2}" -macro.i13 = "\\o{1,3}" -macro.i14 = "\\o{1,4}" -macro.i15 = "\\o{1,5}" -macro.i16 = "\\o{1,6}" -macro.i17 = "\\o{1,7}" -macro.i18 = "\\o{1,8}" -macro.i19 = "\\o{1,9}" -macro.i21 = "\\o{2,1}" -macro.i31 = "\\o{3,1}" -macro.i41 = "\\o{4,1}" -macro.i51 = "\\o{5,1}" -macro.i61 = "\\o{6,1}" -macro.i71 = "\\o{7,1}" -macro.i81 = "\\o{8,1}" -macro.i91 = "\\o{9,1}" -macro.img = "\\image" -macro.endquote = "\\endquotation" - -spurious = "Missing comma in .*" \ - "Missing pattern .*" - -# Doxygen compatibility commands - -macro.see = "\\sa" -macro.function = "\\fn" - -# qt-cpp-ignore.qdocconf - -Cpp.ignoretokens = QAXFACTORY_EXPORT \ - QDESIGNER_COMPONENTS_LIBRARY \ - QDESIGNER_EXTENSION_LIBRARY \ - QDESIGNER_SDK_LIBRARY \ - QDESIGNER_SHARED_LIBRARY \ - QDESIGNER_UILIB_LIBRARY \ - QM_EXPORT_CANVAS \ - QM_EXPORT_DNS \ - QM_EXPORT_DOM \ - QM_EXPORT_FTP \ - QM_EXPORT_HTTP \ - QM_EXPORT_ICONVIEW \ - QM_EXPORT_NETWORK \ - QM_EXPORT_OPENGL \ - QM_EXPORT_SQL \ - QM_EXPORT_TABLE \ - QM_EXPORT_WORKSPACE \ - QM_EXPORT_XML \ - QT_ASCII_CAST_WARN \ - QT_ASCII_CAST_WARN_CONSTRUCTOR \ - QT_BEGIN_HEADER \ - QT_DESIGNER_STATIC \ - QT_END_HEADER \ - QT_FASTCALL \ - QT_WIDGET_PLUGIN_EXPORT \ - Q_COMPAT_EXPORT \ - Q_CORE_EXPORT \ - Q_EXPLICIT \ - Q_EXPORT \ - Q_EXPORT_CODECS_CN \ - Q_EXPORT_CODECS_JP \ - Q_EXPORT_CODECS_KR \ - Q_EXPORT_PLUGIN \ - Q_GFX_INLINE \ - Q_GUI_EXPORT \ - Q_GUI_EXPORT_INLINE \ - Q_GUI_EXPORT_STYLE_CDE \ - Q_GUI_EXPORT_STYLE_COMPACT \ - Q_GUI_EXPORT_STYLE_MAC \ - Q_GUI_EXPORT_STYLE_MOTIF \ - Q_GUI_EXPORT_STYLE_MOTIFPLUS \ - Q_GUI_EXPORT_STYLE_PLATINUM \ - Q_GUI_EXPORT_STYLE_POCKETPC \ - Q_GUI_EXPORT_STYLE_SGI \ - Q_GUI_EXPORT_STYLE_WINDOWS \ - Q_GUI_EXPORT_STYLE_WINDOWSXP \ - QHELP_EXPORT \ - Q_INLINE_TEMPLATE \ - Q_INTERNAL_WIN_NO_THROW \ - Q_NETWORK_EXPORT \ - Q_OPENGL_EXPORT \ - Q_OUTOFLINE_TEMPLATE \ - Q_SQL_EXPORT \ - Q_SVG_EXPORT \ - Q_SCRIPT_EXPORT \ - Q_TESTLIB_EXPORT \ - Q_TYPENAME \ - Q_XML_EXPORT \ - Q_XMLSTREAM_EXPORT \ - Q_XMLPATTERNS_EXPORT \ - QDBUS_EXPORT \ - QT_BEGIN_NAMESPACE \ - QT_BEGIN_INCLUDE_NAMESPACE \ - QT_END_NAMESPACE \ - QT_END_INCLUDE_NAMESPACE \ - PHONON_EXPORT \ - EXTENSIONSYSTEM_EXPORT -Cpp.ignoredirectives = Q_DECLARE_HANDLE \ - Q_DECLARE_INTERFACE \ - Q_DECLARE_METATYPE \ - Q_DECLARE_OPERATORS_FOR_FLAGS \ - Q_DECLARE_PRIVATE \ - Q_DECLARE_PUBLIC \ - Q_DECLARE_SHARED \ - Q_DECLARE_TR_FUNCTIONS \ - Q_DECLARE_TYPEINFO \ - Q_DISABLE_COPY \ - QT_FORWARD_DECLARE_CLASS \ - Q_DUMMY_COMPARISON_OPERATOR \ - Q_ENUMS \ - Q_FLAGS \ - Q_INTERFACES \ - __attribute__ \ - K_DECLARE_PRIVATE \ - PHONON_OBJECT \ - PHONON_HEIR - - - -HTML.stylesheets = classic.css -HTML.postheader = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" \ - "<tr>\n" \ - "<td align=\"left\" valign=\"top\" width=\"32\">" \ - "<img src=\"images/qt-logo.png\" align=\"left\" width=\"32\" height=\"32\" border=\"0\" />" \ - "</td>\n" \ - "<td width=\"1\"> </td>" \ - "<td class=\"postheader\" valign=\"center\">" \ - "<a href=\"qtcreator-manual.html\">" \ - "<font color=\"#004faf\">Home</font></a>" \ - "</td>\n" \ - "<td align=\"right\" valign=\"top\" width=\"230\"></td></tr></table><br>" - -HTML.footer = "<p /><address><hr /><div align=\"center\">\n" \ - "<table width=\"100%\" cellspacing=\"0\" border=\"0\"><tr class=\"address\">\n" \ - "<td width=\"30%\" align=\"left\">Copyright © 2009 Nokia</td>\n" \ - "<td width=\"40%\" align=\"center\"> </td>\n" \ - "<td width=\"30%\" align=\"right\"><div align=\"right\">Qt Creator 1.1.80</div></td>\n" \ - "</tr></table></div></address>" diff --git a/examples/blackjack/bj.qrc b/examples/blackjack/bj.qrc deleted file mode 100644 index 6e39934..0000000 --- a/examples/blackjack/bj.qrc +++ /dev/null @@ -1,5 +0,0 @@ -<RCC> - <qresource prefix="/" > - <file>blackjack.scxml</file> - </qresource> -</RCC> diff --git a/examples/blackjack/blackjack.pro b/examples/blackjack/blackjack.pro deleted file mode 100644 index 71c4409..0000000 --- a/examples/blackjack/blackjack.pro +++ /dev/null @@ -1,14 +0,0 @@ -# ------------------------------------------------- -# Project created by QtCreator 2008-12-16T16:32:05 -# ------------------------------------------------- -QT += script -DEPENDPATH += . -INCLUDEPATH += . -TARGET = blackjack -CONFIG += console -CONFIG -= app_bundle -TEMPLATE = app -SOURCES += main.cpp -include(../../src/qscxml.pri) -FORMS += blackjack.ui -RESOURCES += bj.qrc diff --git a/examples/blackjack/blackjack.scxml b/examples/blackjack/blackjack.scxml deleted file mode 100644 index 4c73cd4..0000000 --- a/examples/blackjack/blackjack.scxml +++ /dev/null @@ -1,292 +0,0 @@ -<scxml - xmlns="http://www.w3.org/2005/07/scxml" - initial="root" profile="ecmascript"> - <script><![CDATA[ - var Suits = "CDHS"; - var Ranks = "-A23456789TJQK"; - - function Card (r,s) - { - this.rank = r; - this.suit = s; - this.minValue = Math.min(r,10); - this.toString = function() { - return "" + Ranks[this.rank] + Suits[this.suit]; - }; -; - } - - function updateDisplay () - { - cardsLabel.text = "My Cards: " + myDeck + " Dealer Cards: " + dealerCards; - } - - - - - function Deck() - { - this.draw = function() - { - return this.cards.pop(); - }; - this.cards = new Array(); - this.reset = function() - { - this.clear (); - for (var i=1; i <= 13; ++i) - for (var j = 0; j < 4; ++j) - this.cards.push(new Card(i,j)); - this.cards.sort(function (a,b) - { - return Math.random() * 3 - 1; - }); - }; - - this.clear = function() - { - this.cards = new Array; - }; - this.evalMin = function () - { - var minVal = 0; - var cardCount = this.cards.length; - for (c in this.cards) { - minVal += this.cards[c].minValue; - } - if (cardCount > 4 && minVal < 22) - minVal = 21; - return minVal; - }; - - this.evalBest = function() - { - var bestVal = this.evalMin(); - if (bestVal > 21) - return 0; - else if (bestVal == 21) - return bestVal; - - for (i in this.cards) { - if (this.cards[i].rank == 1) - { - var v = bestVal + 10; - if (v <= 21) - bestVal = v; - } - } - return bestVal; - - }; - this.toString = function() - { - var s = ""; - for (i in this.cards) - s += this.cards[i].toString() + ":"; - - return s; - }; - - this.drawFrom = function(d) - { - var c = d.draw (); - this.cards.push(c); - updateDisplay (); - }; - } - - - function hitMe () - { - myDeck.drawFrom (availDeck); - } - ]]></script> - <final id="exit" /> - <state id="root" initial="newgame"> - <onentry> - <script> - var myDeck = new Deck; - var dealerCards = new Deck; - var availDeck = new Deck; - var pot = 0; - var points = 1000; - - </script> - - </onentry> - <invoke type="q-bindings"> - <content> - [[welcomeLabel,"text","Welcome to Blackjack"]] - </content> - </invoke> - <transition event="q-signal:newGameButton.clicked()" target="newgame" /> - <state id="newgame"> - <onentry> - <script> - points = 1000; - pointsLabel.text = points; - </script> - </onentry> - <transition target="newround" /> - </state> - <state id="quitdlg"> - <invoke type="q-messagebox"> - <content> - { - "parent" : gameWidget, - "icon" : QMessageBox.Question, - "windowTitle" : "Exit Blackjack", - "text" : "Are you sure?", - "standardButtons" : QMessageBox.Yes|QMessageBox.No - } - </content> - </invoke> - <transition event="q-messagebox.finished" target="exit" cond="_event.data[0]==QMessageBox.Yes" /> - <transition event="q-messagebox.finished" target="gamestate" cond="_event.data[0]==QMessageBox.No" /> - </state> - <state id="game"> - <history type="deep" id="gamestate" /> - <transition event="q-signal:exitButton.clicked()" target="quitdlg" /> - <state id="newround"> - <onentry> - <script> - pot = 0; - availDeck.reset (); - myDeck.clear (); - dealerCards.clear(); - dealerCards.drawFrom(availDeck); - hitMe (); - hitMe (); - </script> - </onentry> - <transition target="waitForBet" /> - </state> - <state id="waitForBet"> - <invoke type="q-bindings"><content> - [ - [betEdit,"enabled",true], - [betButton,"enabled",true], - [surrenderButton,"enabled",true], - [welcomeLabel,"text","Please place your bet"] - ] - </content></invoke> - <transition event="q-signal:betButton.clicked()" target="testCards" cond="parseInt(betEdit.text) <= points"> - <script> - pot = betEdit.text; - points -= pot; - pointsLabel.text = points; - </script> - </transition> - <transition event="q-signal:betButton.clicked()" target="betTooHigh" cond="parseInt(betEdit.text) > points"> - </transition> - <transition event="q-signal:surrenderButton.clicked()" target="newround" /> - </state> - <state id="betTooHigh"> - <invoke type="q-messagebox"> - <content> - { - "parent" : betEdit, - "icon" : QMessageBox.Warning, - "windowTitle" : "Bet is Too High", - "text" : "Please Place Another Bet", - "standardButtons" : - QMessageBox.Ok - } - </content> - </invoke> - <transition event="q-messagebox.finished" target="waitForBet" /> - <transition event="bth-mb-timeout" target="waitForBet" /> - <onentry> - <send event="'bth-mb-timeout'" delay="'1500ms'" /> - </onentry> - </state> - <state id="testCards"> - <transition target="loss" cond="myDeck.evalBest() == 0" /> - <transition target="getDealerCards" cond="myDeck.evalBest() == 21" /> - <transition target="waitForAction" cond="myDeck.evalBest() %21 != 0" /> - </state> - - <state id="waitForAction"> - <transition event="q-signal:hitButton.clicked()" target="testCards"> - <script>hitMe (); </script> - </transition> - <transition event="q-signal:standButton.clicked()" target="getDealerCards" /> - <invoke type="q-bindings"><content> - [ - [welcomeLabel,"text","Hit/Stand?"], - [hitButton,"enabled",true], - [standButton,"enabled",true] - ] - </content></invoke> - </state> - - <state id="getDealerCards"> - <onentry> - <script><![CDATA[ - while (dealerCards.evalBest() > 0 && dealerCards.evalBest() < 17) - { - dealerCards.drawFrom(availDeck); - } - ]]></script> - <raise event="doneWithCards" /> - </onentry> - <transition target="checkWinner" /> - </state> - - <state id="checkWinner"> - <onentry> - <script> - _global.diff = myDeck.evalBest() - dealerCards.evalBest(); - </script> - </onentry> - - <transition cond="diff>0" target="win" /> - <transition cond="diff<0" target="loss" /> - <transition cond="diff==0" target="draw" /> - </state> - <state id="endGame"> - <invoke type="q-bindings"><content>[[welcomeLabel,"text","Game Over"]]</content></invoke> - <transition event="timeout" target="newgame" /> - <onentry> - <send event="'timeout'" delay="'3s'" /> - </onentry> - </state> - <state id="endRound"> - <invoke type="q-bindings"><content>[[newRoundButton,"enabled",true]]</content></invoke> - <transition event="q-signal:newRoundButton.clicked()" target="newround" /> - <transition event="timeout" target="newround" /> - <onentry> - <send event="'timeout'" delay="'3s'" /> - </onentry> - - <state id="win"> - <onentry> - <script> - points = parseInt(points) + parseInt(pot) * 2; - pointsLabel.text = points; - </script> - </onentry> - <invoke type="q-bindings"><content>[[welcomeLabel,"text","You Won!"]]</content></invoke> - </state> - <state id="loss"> - <invoke type="q-bindings"><content>[[welcomeLabel,"text","You Lost..."]]</content></invoke> - <transition cond="points == 0" target="endGame" /> - </state> - <state id="draw"> - <invoke type="q-bindings"><content>[[welcomeLabel,"text","You It's a draw."]]</content></invoke> - <onentry> - <script> - points = parseInt(points) + parseInt(pot); - pointsLabel.text = points; - </script> - </onentry> - </state> - </state> - </state> - - </state> - -</scxml> - - - diff --git a/examples/blackjack/blackjack.ui b/examples/blackjack/blackjack.ui deleted file mode 100644 index 187ec62..0000000 --- a/examples/blackjack/blackjack.ui +++ /dev/null @@ -1,174 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<ui version="4.0"> - <class>gameWidget</class> - <widget class="QWidget" name="gameWidget"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>520</width> - <height>173</height> - </rect> - </property> - <property name="windowTitle"> - <string>SCXML Blackjack Example</string> - </property> - <property name="styleSheet"> - <string/> - </property> - <layout class="QVBoxLayout"> - <property name="spacing"> - <number>6</number> - </property> - <property name="margin"> - <number>9</number> - </property> - <item> - <widget class="QLabel" name="welcomeLabel"> - <property name="font"> - <font> - <pointsize>18</pointsize> - </font> - </property> - <property name="text"> - <string/> - </property> - </widget> - </item> - <item> - <widget class="QLabel" name="cardsLabel"> - <property name="font"> - <font> - <pointsize>16</pointsize> - </font> - </property> - <property name="styleSheet"> - <string>color:#660033</string> - </property> - <property name="text"> - <string/> - </property> - </widget> - </item> - <item> - <layout class="QHBoxLayout"> - <property name="spacing"> - <number>6</number> - </property> - <property name="margin"> - <number>0</number> - </property> - <item> - <widget class="QLabel" name="label"> - <property name="text"> - <string>Points:</string> - </property> - </widget> - </item> - <item> - <widget class="QLabel" name="pointsLabel"> - <property name="styleSheet"> - <string>color:#339999</string> - </property> - <property name="text"> - <string/> - </property> - </widget> - </item> - <item> - <widget class="QLineEdit" name="betEdit"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="maxLength"> - <number>10</number> - </property> - <property name="readOnly"> - <bool>false</bool> - </property> - </widget> - </item> - <item> - <widget class="QPushButton" name="betButton"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="text"> - <string>Bet</string> - </property> - </widget> - </item> - </layout> - </item> - <item> - <layout class="QHBoxLayout"> - <property name="spacing"> - <number>6</number> - </property> - <property name="margin"> - <number>0</number> - </property> - <item> - <widget class="QPushButton" name="newGameButton"> - <property name="enabled"> - <bool>true</bool> - </property> - <property name="text"> - <string>New Game</string> - </property> - </widget> - </item> - <item> - <widget class="QPushButton" name="newRoundButton"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="text"> - <string>New Round</string> - </property> - </widget> - </item> - <item> - <widget class="QPushButton" name="surrenderButton"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="text"> - <string>Surrender</string> - </property> - </widget> - </item> - <item> - <widget class="QPushButton" name="hitButton"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="text"> - <string>Hit</string> - </property> - </widget> - </item> - <item> - <widget class="QPushButton" name="standButton"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="text"> - <string>Stand</string> - </property> - </widget> - </item> - <item> - <widget class="QPushButton" name="exitButton"> - <property name="text"> - <string>Exit</string> - </property> - </widget> - </item> - </layout> - </item> - </layout> - </widget> - <resources/> - <connections/> -</ui> diff --git a/examples/blackjack/main.cpp b/examples/blackjack/main.cpp deleted file mode 100644 index 0ee3b9f..0000000 --- a/examples/blackjack/main.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the SCXML project on Trolltech Labs. -** -** This file may be used under the terms of the GNU General Public -** License version 2.0 or 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of -** this file. Please review the following information to ensure GNU -** General Public Licensing requirements will be met: -** http://www.fsf.org/licensing/licenses/info/GPLv2.html and -** http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -****************************************************************************/ -#include <QApplication> -#include <QFileInfo> -#include "ui_blackjack.h" -#include <QDebug> -#include <QMessageBox> -#include <QUrl> -#include <QScriptEngine> -#include "qscxml.h" -#include "time.h" - -int main(int argc, char *argv[]) -{ - QApplication a(argc, argv); - srand(clock()); - QScxml *sm = QScxml::load(":/blackjack.scxml"); - QObject::connect (sm, SIGNAL(finished()), &a, SLOT(quit())); - QMessageBox b; - QWidget* wdg = new QWidget(); - Ui::gameWidget gw; - gw.setupUi(wdg); - sm->registerObject(wdg,"gameWidget",true); - wdg->show(); - sm->start(); - return a.exec(); -} diff --git a/examples/calc/calc.cpp b/examples/calc/calc.cpp deleted file mode 100644 index 83c0f00..0000000 --- a/examples/calc/calc.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ -#include "calc.h" -#include "ui_calc.h" -#include <QSignalMapper> -CalcWidget::CalcWidget(QWidget *parent) - : QWidget(parent) -{ - setupUi(this); - QSignalMapper* mapper = new QSignalMapper(this); - connect (mapper, SIGNAL(mapped(QString)), this, SIGNAL(command(QString))); - QList<QAbstractButton*> buttons = findChildren<QAbstractButton*>(); - foreach (QAbstractButton* b, buttons) { - connect (b, SIGNAL(clicked()), mapper, SLOT(map())); - } - mapper->setMapping(button0,"DIGIT.0"); - mapper->setMapping(button1,"DIGIT.1"); - mapper->setMapping(button2,"DIGIT.2"); - mapper->setMapping(button3,"DIGIT.3"); - mapper->setMapping(button4,"DIGIT.4"); - mapper->setMapping(button5,"DIGIT.5"); - mapper->setMapping(button6,"DIGIT.6"); - mapper->setMapping(button7,"DIGIT.7"); - mapper->setMapping(button8,"DIGIT.8"); - mapper->setMapping(button9,"DIGIT.9"); - mapper->setMapping(buttonEq,"EQUALS"); - mapper->setMapping(buttonCE,"CE"); - mapper->setMapping(buttonC,"C"); - mapper->setMapping(buttonPoint,"POINT"); - mapper->setMapping(buttonPlus,"OPER.PLUS"); - mapper->setMapping(buttonStar,"OPER.STAR"); - mapper->setMapping(buttonMinus,"OPER.MINUS"); - mapper->setMapping(buttonDiv,"OPER.DIV"); -} -CalcWidget::~CalcWidget() -{ -} diff --git a/examples/calc/calc.h b/examples/calc/calc.h deleted file mode 100644 index 4d7c18e..0000000 --- a/examples/calc/calc.h +++ /dev/null @@ -1,28 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ -#ifndef CALC_H -#define CALC_H - -#include <QtGui/QWidget> -#include "ui_calc.h" - -class CalcWidget : public QWidget, public Ui::CalcClass -{ - Q_OBJECT - -public: - CalcWidget(QWidget *parent = 0); - ~CalcWidget(); - -Q_SIGNALS: - void command(const QString &); -}; - -#endif // CALC_H diff --git a/examples/calc/calc.pro b/examples/calc/calc.pro deleted file mode 100644 index f20233e..0000000 --- a/examples/calc/calc.pro +++ /dev/null @@ -1,16 +0,0 @@ -# ------------------------------------------------- -# Project created by QtCreator 2008-12-25T19:50:44 -# ------------------------------------------------- - -TARGET = calc -TEMPLATE = app -win32: CONFIG += console -mac:CONFIG -= app_bundle -QT = core gui script -include($$PWD/../../src/qscxml.pri) - -# Input -SOURCES += main.cpp calc.cpp -HEADERS += calc.h -FORMS += calc.ui -RESOURCES += calc.qrc diff --git a/examples/calc/calc.qrc b/examples/calc/calc.qrc deleted file mode 100644 index 04b1be3..0000000 --- a/examples/calc/calc.qrc +++ /dev/null @@ -1,5 +0,0 @@ -<RCC> - <qresource prefix="/" > - <file>calc.scxml</file> - </qresource> -</RCC> diff --git a/examples/calc/calc.scxml b/examples/calc/calc.scxml deleted file mode 100644 index ec732c7..0000000 --- a/examples/calc/calc.scxml +++ /dev/null @@ -1,210 +0,0 @@ -<scxml - initial="on" profile="ecma" name="calc"> - <script> - function insertDigit () - { - insert (_event.name.charAt(_event.name.lastIndexOf('.')+1)); - } - function insert(c) - { - short_expr += c; - updateDisplay(); - } - function negate () - { - short_expr = "-"; - updateDisplay (); - } - - function updateDisplay () - { - if (short_expr == "") - dispLbl.text = _data.res; - else - dispLbl.text = short_expr; - } - function subcalc () - { - if (short_expr != "") - _data.long_expr += "(" + short_expr + ")"; - _data.res = eval(_data.long_expr); - short_expr = ""; - updateDisplay (); - return true; - } - - function insertOp () - { - var sc = subcalc (); - var op = ''; - if (_event.name == "OPER.PLUS") - op = '+'; - else if (_event.name == "OPER.MINUS") - op = '-'; - else if (_event.name == "OPER.STAR") - op = '*'; - else if (_event.name == "OPER.DIV") - op = '/'; - _data.long_expr += op; - return sc; - } - function reset () - { - short_expr = ""; - } - function calc () - { - if (subcalc ()) { - short_expr = "" + _data.res; - _data.long_expr = ""; - _data.res = 0; - return true; - } else - return false; - } - </script> - <state id="on" initial="ready"> - <datamodel> - <data id="long_expr" /> - <data id="res" >0</data> - </datamodel> - <onentry> - <script> - var short_expr = 0; - _data.res = 0; - _data.long_expr = ""; - updateDisplay(); - </script> - </onentry> - <state id="ready" initial="begin"> - <state id="begin"> - <transition event="OPER.MINUS" target="negated1" /> - <onentry> - <script> - updateDisplay (); - </script> - </onentry> - </state> - <state id="result"> - </state> - <transition event="OPER" target="opEntered" /> - <transition event="DIGIT.0" target="zero1"> - <script> - reset (); - </script> - </transition> - <transition event="DIGIT" target="int1"> - <script> - reset (); - </script> - </transition> - <transition event="POINT" target="frac1"> - <script> - reset (); - </script> - </transition> - </state> - <state id="negated1"> - <onentry> - <script> - negate (); - </script> - </onentry> - <transition event="DIGIT.0" target="zero1" /> - <transition event="DIGIT" target="int1" /> - <transition event="POINT" target="frac1" /> - </state> - <state id="operand1"> - <state id="zero1"> - <transition event="DIGIT" cond="_event.name != 'DIGIT.0'" target="int1" /> - <transition event="POINT" target="frac1" /> - </state> - <state id="int1"> - <transition event="POINT" target="frac1" /> - <transition event="DIGIT"> - <script> - insertDigit (); - </script> - </transition> - <onentry> - <script> - insertDigit (); - </script> - </onentry> - </state> - <state id="frac1"> - <onentry> - <script> - insert ('.'); - </script> - </onentry> - <transition event="DIGIT"> - <script> - insertDigit (); - </script> - </transition> - </state> - <transition event="CE" target="ready" /> - <transition event="OPER" target="opEntered" /> - </state> - <state id="error" /> - <state id="opEntered"> - <transition event="OPER.MINUS" target="negated2" /> - <transition event="POINT" target="frac2" /> - <transition event="DIGIT.0" target="zero2" /> - <transition event="DIGIT" target="int2" /> - <onentry> - <script> - insertOp (); - </script> - </onentry> - </state> - <state id="negated2"> - <onentry> - <script> - negate (); - </script> - </onentry> - <transition event="CE" target="opEntered" /> - <transition event="DIGIT.0" target="zero2" /> - <transition event="DIGIT" target="int2" /> - <transition event="POINT" target="frac2" /> - </state> - <state id="operand2"> - <state id="zero2"> - <transition event="DIGIT" cond="_event.name != 'DIGIT.0'" target="int2" /> - <transition event="POINT" target="frac2" /> - </state> - <state id="int2"> - <transition event="DIGIT"> - <script> - insertDigit (); - </script> - </transition> - <onentry> - <script> - insertDigit (); - </script> - </onentry> - <transition event="POINT" target="frac2" /> - </state> - <state id="frac2"> - <onentry> - <script> - insert ('.'); - </script> - </onentry> - <transition event="DIGIT"> - <script> - insertDigit (); - </script> - </transition> - </state> - <transition event="OPER" cond="!insertOp()" target="error" /> - <transition event="OPER" target="opEntered" /> - <transition event="EQUALS" cond="!calc()" target="error" /> - <transition event="EQUALS" target="result" /> - </state> - <transition event="C" target="on" /> - </state> -</scxml> diff --git a/examples/calc/calc.ui b/examples/calc/calc.ui deleted file mode 100644 index 0e2a651..0000000 --- a/examples/calc/calc.ui +++ /dev/null @@ -1,187 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<ui version="4.0"> - <class>CalcClass</class> - <widget class="QWidget" name="CalcClass"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>419</width> - <height>156</height> - </rect> - </property> - <property name="maximumSize"> - <size> - <width>419</width> - <height>400</height> - </size> - </property> - <property name="windowTitle"> - <string>SCXML Calculator</string> - </property> - <property name="styleSheet"> - <string notr="true">* {background-color:black;color:white} -button {border-width:3; }</string> - </property> - <layout class="QVBoxLayout" name="verticalLayout"> - <item> - <widget class="QLabel" name="dispLbl"> - <property name="styleSheet"> - <string notr="true"> -background-color: #CCCCCC; -color: black; -font: 12pt "Courier New";</string> - </property> - <property name="text"> - <string/> - </property> - <property name="alignment"> - <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> - </property> - </widget> - </item> - <item> - <layout class="QGridLayout" name="gridLayout"> - <property name="horizontalSpacing"> - <number>6</number> - </property> - <item row="3" column="0"> - <widget class="QPushButton" name="button4"> - <property name="text"> - <string>4</string> - </property> - </widget> - </item> - <item row="4" column="0"> - <widget class="QPushButton" name="button1"> - <property name="text"> - <string>1</string> - </property> - </widget> - </item> - <item row="1" column="4"> - <widget class="QPushButton" name="buttonCE"> - <property name="styleSheet"> - <string notr="true">color:red;font-weight:bold</string> - </property> - <property name="text"> - <string>CE</string> - </property> - </widget> - </item> - <item row="1" column="2"> - <widget class="QPushButton" name="button9"> - <property name="text"> - <string>9</string> - </property> - </widget> - </item> - <item row="3" column="1"> - <widget class="QPushButton" name="button5"> - <property name="text"> - <string>5</string> - </property> - </widget> - </item> - <item row="1" column="0"> - <widget class="QPushButton" name="button7"> - <property name="text"> - <string>7</string> - </property> - </widget> - </item> - <item row="4" column="1"> - <widget class="QPushButton" name="button2"> - <property name="text"> - <string>2</string> - </property> - </widget> - </item> - <item row="5" column="0" colspan="2"> - <widget class="QPushButton" name="button0"> - <property name="text"> - <string>0</string> - </property> - </widget> - </item> - <item row="3" column="2"> - <widget class="QPushButton" name="button6"> - <property name="text"> - <string>6</string> - </property> - </widget> - </item> - <item row="4" column="2"> - <widget class="QPushButton" name="button3"> - <property name="text"> - <string>3</string> - </property> - </widget> - </item> - <item row="5" column="2"> - <widget class="QPushButton" name="buttonPoint"> - <property name="text"> - <string>.</string> - </property> - </widget> - </item> - <item row="3" column="3"> - <widget class="QPushButton" name="buttonPlus"> - <property name="text"> - <string>+</string> - </property> - </widget> - </item> - <item row="3" column="4"> - <widget class="QPushButton" name="buttonMinus"> - <property name="text"> - <string>-</string> - </property> - </widget> - </item> - <item row="4" column="3"> - <widget class="QPushButton" name="buttonStar"> - <property name="text"> - <string>*</string> - </property> - </widget> - </item> - <item row="4" column="4"> - <widget class="QPushButton" name="buttonDiv"> - <property name="text"> - <string>/</string> - </property> - </widget> - </item> - <item row="5" column="3" colspan="2"> - <widget class="QPushButton" name="buttonEq"> - <property name="text"> - <string>=</string> - </property> - </widget> - </item> - <item row="1" column="1"> - <widget class="QPushButton" name="button8"> - <property name="text"> - <string>8</string> - </property> - </widget> - </item> - <item row="1" column="3"> - <widget class="QPushButton" name="buttonC"> - <property name="styleSheet"> - <string notr="true">color: red; font-weight:bold</string> - </property> - <property name="text"> - <string>C</string> - </property> - </widget> - </item> - </layout> - </item> - </layout> - </widget> - <layoutdefault spacing="6" margin="11"/> - <resources/> - <connections/> -</ui> diff --git a/examples/calc/main.cpp b/examples/calc/main.cpp deleted file mode 100644 index 33188b4..0000000 --- a/examples/calc/main.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the SCXML project on Trolltech Labs. -** -** This file may be used under the terms of the GNU General Public -** License version 2.0 or 3.0 as published by the Free Software Foundation -** and appearing in the file LICENSE.GPL included in the packaging of -** this file. Please review the following information to ensure GNU -** General Public Licensing requirements will be met: -** http://www.fsf.org/licensing/licenses/info/GPLv2.html and -** http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -****************************************************************************/ - -#include <QtGui/QApplication> -#include "calc.h" -#include "qscxml.h" -int main(int argc, char *argv[]) -{ - QApplication a(argc, argv); - QScxml *sm = QScxml::load(":/calc.scxml"); - CalcWidget w; - sm->registerObject(&w,"",true); - QObject::connect (&w, SIGNAL(command(QString)), sm, SLOT(postNamedEvent(QString))); - w.show(); - sm->start(); - return a.exec(); -} diff --git a/examples/examples.pro b/examples/examples.pro deleted file mode 100644 index 53d0ca3..0000000 --- a/examples/examples.pro +++ /dev/null @@ -1,2 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS += blackjack calc mediaplayer
\ No newline at end of file diff --git a/examples/mediaplayer/main.cpp b/examples/mediaplayer/main.cpp deleted file mode 100644 index c510114..0000000 --- a/examples/mediaplayer/main.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ -#include "qscxml.h" -#include "spview.h" -#include "spmodel.h" -#include "spengine.h" -#include "spharvester.h" -#include "math.h" -#include "time.h" -#include <QDebug> -#include <QApplication> -#include <QLabel> -#include <QPushButton> -#include <QScriptEngine> -#include <QVBoxLayout> -#include <QHBoxLayout> -#include <QFileInfo> -#include <QScriptContext> -#include <QScriptEngine> -#include <QMenu> -#include <QMainWindow> - - -int main( int argc, char **argv) -{ - QApplication app(argc, argv); - QString dir; - bool recurse; - if (argc > 1) { - dir = QString(argv[1]); - if (argc > 2) - { - recurse = !strcmp(argv[2],"-recurse"); - } - } else { - printf("Usage: stateplayer directory [-recurse]"); - return 0; - } - - app.setApplicationName("SCXML-mediaplayer"); - - SPView* view = new SPView(NULL); - QScxml *sm = QScxml::load(":/mediaplayer.scxml"); - QObject::connect (sm, SIGNAL(finished()), &app, SLOT(quit())); - SPModel* model= new SPModel(NULL); - view->setModel(model); - model->setObjectName("model"); - SPEngine* engine = new SPEngine(sm); - engine->setObjectName("engine"); - SPHarvester* harvester = new SPHarvester (view); - QObject::connect (harvester, SIGNAL(foundTrack(SongData)), model, SLOT(addSong(SongData))); - harvester->harvest(dir,recurse); - view->setObjectName("view"); - sm->registerObject(model); - sm->registerObject(engine); - sm->registerObject(view,"",true); - view->show (); - sm->start (); - return app.exec (); -} diff --git a/examples/mediaplayer/mediaplayer.pro b/examples/mediaplayer/mediaplayer.pro deleted file mode 100644 index 70c06f1..0000000 --- a/examples/mediaplayer/mediaplayer.pro +++ /dev/null @@ -1,23 +0,0 @@ -TEMPLATE = app -TARGET = scxmlplayer -QT += script \ - sql \ - phonon -include(../../src/qscxml.pri) - -HEADERS += spmodel.h \ - spengine.h \ - spview.h \ - spharvester.h \ - songdata.h -SOURCES += main.cpp \ - spmodel.cpp \ - spengine.cpp \ - spview.cpp \ - spharvester.cpp -FORMS += mediaplayer.ui -RESOURCES += mediaplayer.qrc -win32:CONFIG += console -mac:CONFIG -= app_bundle -INCLUDEPATH += . -DEPENDPATH += . diff --git a/examples/mediaplayer/mediaplayer.qrc b/examples/mediaplayer/mediaplayer.qrc deleted file mode 100644 index ff8226f..0000000 --- a/examples/mediaplayer/mediaplayer.qrc +++ /dev/null @@ -1,5 +0,0 @@ -<RCC> - <qresource> - <file>mediaplayer.scxml</file> - </qresource> -</RCC> diff --git a/examples/mediaplayer/mediaplayer.scxml b/examples/mediaplayer/mediaplayer.scxml deleted file mode 100644 index 323d9c9..0000000 --- a/examples/mediaplayer/mediaplayer.scxml +++ /dev/null @@ -1,240 +0,0 @@ -<scxml xmlns="http://www.w3.org/2005/07/scxml" initial="root"> - <parallel id="root"> - <state initial="gui"> - <invoke targettype="q-bindings"> - <content>[[listView,'styleSheet','QListView {font-size:20px}']]</content> - </invoke> - <state id="gui" initial="menu_tree"> - <transition event="q-signal:backButton.clicked()" anchor="lastmenupos" /> - <transition event="q-signal:homeButton.clicked()" target="mainmenu" /> - <state id="menu_tree" initial="mainmenu"> - <invoke type="q-binding"><content>[[stackedWidget,"currentIndex",0]]</content></invoke> - <state id="mainmenu"> - <anchor type="lastmenupos" /> - <onentry><script> - homeButton.enabled = false; - selectButton.enabled = false; - </script></onentry> - <onexit><script> - homeButton.enabled = true; - selectButton.enabled = true; - </script></onexit> - <invoke type="q-menu"> - <content> - { "parent" : listView, "windowTitle" : - "Music Player", "styleSheet" : "QMenu {font-size:24px; width: 505;height:1000;}" + - "QMenu::item:hover {background-color: blue;color: black;}", - "children": function() { var c = [ - {"type" : "action","id" : "artists", "text" : "Artists" }, - {"type" : "action", "id" : "albums", "text" : "Albums" }, - {"type" : "action", "id" : "genres", "text" : "Genres" }, - {"type" : "action", "id" : "allsongs", "text" : "All Songs" }]; - if (model.currentSongTitle != '') - c[c.length] = {type: "action", id: "curplaying", text: model.currentSongTitle}; - return c; }() - }</content> - </invoke> - <transition event="menu.action.artists" target="artists" /> - <transition event="menu.action.albums" target="albums"> - <script>model.clearAlbumFilter ();</script> - </transition> - <transition event="menu.action.genres" target="genres" /> - <transition event="menu.action.curplaying" target="playingwin" /> - <transition event="menu.action.allsongs" target="songs"> - <script>model.clearSongFilter ();</script> - </transition> - </state> - <state id="artists"> - <anchor type="lastmenupos" /> - <onentry> - <script>model.loadArtists (); view.showArtists();</script> - </onentry> - <transition event="q-signal:model.artistChanged(QString)"> - - <script>model.loadArtists();</script> - </transition> - <transition event="q-signal:selectButton.clicked()" target="albums" cond="view.currentIndex >=0"> - <script> - model.filterAlbumsByArtist(view.currentItem); - </script> - </transition> - </state> - <state id="albums"> - <onentry> - <script>model.loadAlbums ();</script> - </onentry> - <transition cond="model.albumCount==1" target="songs" /> - <transition cond="model.albumCount > 1" target="show_albums" /> - <transition cond="model.albumCount==0" target="songs" /> - </state> - <state id="show_albums"> - <anchor type="lastmenupos" /> - <transition event="q-signal:model.albumChanged(QString)"> - - <script>model.loadAlbums();</script> - </transition> - <transition event="q-signal:selectButton.clicked()" cond="view.currentIndex >=0" target="songs"> - <script> - model.filterSongsByAlbum(view.currentItem);</script> - </transition> - <onentry> - <script>view.showAlbums ();</script> - </onentry> - </state> - <state id="genres"> - <anchor type="lastmenupos" /> - <onentry> - <script>model.loadGenres (); view.showGenres - ();</script> - </onentry> - <transition event="q-signal:model.genreChanged(QString)"> - - <script>model.loadGenres();</script> - </transition> - <transition event="q-signal:selectButton.clicked()" cond="view.currentIndex >=0" target="songs"> - <script> - model.filterSongsByGenre(view.currentItem);</script> - </transition> - </state> - <state id="songs"> - <anchor type="lastmenupos" /> - <onentry> - <script>model.loadSongs (); view.showSongs - ();</script> - </onentry> - <transition event="q-signal:model.songListChanged()"> - <script>model.loadSongs();</script> - </transition> - <transition event="q-signal:selectButton.clicked()" cond="view.currentIndex >=0" target="playingwin"> - <script> - model.selectSong (view.currentItem); - engine.setTrack(model.currentSong); - </script> - <raise event="playIntent" /> - <raise event="songSelected" /> - </transition> - </state> - </state> - <state id="playingwin"> - <anchor type="lastmenupos" /> - <invoke type="q-bindings"> - <content>[ - [selectButton,"enabled",false], - [playingLabel,"text",model.currentSongTitle], - [midLabel,"text",model.currentSongArtist], - [posSlider,"minimum",0], - [posSlider,"maximum",engine.totalTime], - [stackedWidget,"currentIndex",1] - ]</content> - </invoke> - <onentry> - <script>view.showPlayer ();</script> - </onentry> - <transition event="q-signal:model.songChanged()"> - <script> - midLabel.text = model.currentSongArtist + ' / ' + model.currentSongAlbum; - playingLabel.text = model.currentSongTitle; - </script> - </transition> - </state> - </state> - </state> - <state id="engine" initial="idle"> - <onentry><script> - volumeSlider.value = engine.volume; - </script></onentry> - - <transition event="q-signal:model.songChanged()"> - <script>engine.setTrack(model.currentSong);</script> - <raise event="playIntent" /> - <raise event="songChanged" /> - </transition> - <state id="idle"> - <transition event="playIntent" target="playing" /> - <transition event="q-signal:playButton.clicked()"> - <raise event="playIntent" /> - </transition> - <invoke type="q-bindings"> - <content>[[stopButton,"enabled",false]]</content> - </invoke> - </state> - <state id="active" initial="playing"> - <invoke type="q-bindings"> - <content>[[stopButton,"enabled",true]]</content> - </invoke> - <transition event="q-signal:stopButton.clicked()" - target="idle"> - <script>engine.stop ();</script> - </transition> - <state id="playing"> - <invoke type="q-bindings"> - <content>[[playButton,"text","Pause"]]</content> - </invoke> - <onentry> - <script>engine.play ();</script> - </onentry> - <transition event="q-signal:playButton.clicked()" - target="paused" /> - <transition event="songChanged"> - <script>engine.play();</script> - </transition> - <transition event="q-signal:engine.tick(qint64)"> - <script>view.setCurrentTime(_event.data[0]);</script> - </transition> - <transition event="q-signal:engine.totalTimeChanged(qint64)"> - <script>view.setTotalTime(_event.data[0]);</script> - </transition> - </state> - <state id="paused"> - <onentry> - <script>engine.pause();</script> - </onentry> - <transition event="q-signal:playButton.clicked()" - target="playing" /> - </state> - <transition event="q-signal:model.endOfList()" - target="idle"> - <script>engine.stop (); model.reset ();</script> - </transition> - </state> - <transition event="q-signal:engine.aboutToFinish()"> - <raise event="nextSong" /> - </transition> - <transition event="nextSong"> - <script> - model.next(); - engine.enqueue(model.currentSong); - </script> - </transition> - <transition event="q-signal:nextButton.clicked()"> - <script>model.gotoNext();</script> - </transition> - <transition event="q-signal:prevButton.clicked()"> - <script>model.gotoPrev();</script> - </transition> - <transition event="q-signal:posSlider.sliderMoved(int)"> - <script>engine.seek(_event.data[0]);</script> - </transition> - <transition event="q-signal:volumeSlider.sliderMoved(int)"> - <script>engine.volume = _event.data[0];</script> - </transition> - <transition event="q-signal:engine.volumeChanged(int)"> - <script>volumeSlider.value = _event.data[0];</script> - </transition> - </state> - <state id="selection_state" initial="no_song_selected"> - <state id="no_song_selected"> - <transition event="songSelected" target="song_selected" /> - <invoke type="q-bindings"> - <content>[[stopButton,"enabled",false], - [playButton,"enabled",false], - [prevButton,"enabled",false], - [nextButton,"enabled",false]]</content> - </invoke> - </state> - <state id="song_selected"> - <transition event="endOfList" target="no_song_selected" /> - </state> - </state> - </parallel> -</scxml> diff --git a/examples/mediaplayer/mediaplayer.ui b/examples/mediaplayer/mediaplayer.ui deleted file mode 100644 index dbbc6fd..0000000 --- a/examples/mediaplayer/mediaplayer.ui +++ /dev/null @@ -1,145 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<ui version="4.0"> - <class>mediaPlayerWidget</class> - <widget class="QWidget" name="mediaPlayerWidget"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>394</width> - <height>287</height> - </rect> - </property> - <property name="windowTitle"> - <string>SCXML Media Player</string> - </property> - <layout class="QHBoxLayout" name="horizontalLayout"> - <item> - <widget class="QStackedWidget" name="stackedWidget"> - <property name="currentIndex"> - <number>0</number> - </property> - <widget class="QWidget" name="page"> - <layout class="QVBoxLayout" name="verticalLayout_2"> - <item> - <widget class="QListView" name="listView"/> - </item> - </layout> - </widget> - <widget class="QWidget" name="playerPage"> - <widget class="QLabel" name="playingLabel"> - <property name="geometry"> - <rect> - <x>0</x> - <y>50</y> - <width>291</width> - <height>61</height> - </rect> - </property> - <property name="styleSheet"> - <string>QLabel {font-size: 24px; color: #336699}</string> - </property> - <property name="text"> - <string>TextLabel</string> - </property> - </widget> - <widget class="QLabel" name="midLabel"> - <property name="geometry"> - <rect> - <x>0</x> - <y>120</y> - <width>291</width> - <height>21</height> - </rect> - </property> - <property name="text"> - <string>TextLabel</string> - </property> - </widget> - <widget class="QSlider" name="posSlider"> - <property name="geometry"> - <rect> - <x>0</x> - <y>180</y> - <width>301</width> - <height>16</height> - </rect> - </property> - <property name="maximum"> - <number>0</number> - </property> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - </widget> - </widget> - </widget> - </item> - <item> - <widget class="QWidget" name="widget1" native="true"> - <layout class="QVBoxLayout" name="verticalLayout"> - <item> - <widget class="QToolButton" name="homeButton"> - <property name="text"> - <string>Home</string> - </property> - </widget> - </item> - <item> - <widget class="QToolButton" name="playButton"> - <property name="text"> - <string>Play</string> - </property> - </widget> - </item> - <item> - <widget class="QToolButton" name="prevButton"> - <property name="text"> - <string>Prev</string> - </property> - </widget> - </item> - <item> - <widget class="QToolButton" name="nextButton"> - <property name="text"> - <string>Next</string> - </property> - </widget> - </item> - <item> - <widget class="QToolButton" name="stopButton"> - <property name="text"> - <string>Stop</string> - </property> - </widget> - </item> - <item> - <widget class="QSlider" name="volumeSlider"> - <property name="orientation"> - <enum>Qt::Vertical</enum> - </property> - </widget> - </item> - <item> - <widget class="QToolButton" name="selectButton"> - <property name="text"> - <string>Select</string> - </property> - </widget> - </item> - <item> - <widget class="QToolButton" name="backButton"> - <property name="text"> - <string>Back</string> - </property> - </widget> - </item> - </layout> - </widget> - </item> - </layout> - </widget> - <layoutdefault spacing="6" margin="11"/> - <resources/> - <connections/> -</ui> diff --git a/examples/mediaplayer/songdata.h b/examples/mediaplayer/songdata.h deleted file mode 100644 index 0e2a644..0000000 --- a/examples/mediaplayer/songdata.h +++ /dev/null @@ -1,24 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ -#ifndef SONGDATA_H -#define SONGDATA_H - -#include <QStringList> - -struct SongData -{ - QString url; - QString title; - QString album; - QString artist; - QStringList genres; - int trackNumber; -}; -#endif diff --git a/examples/mediaplayer/spengine.cpp b/examples/mediaplayer/spengine.cpp deleted file mode 100644 index bd4b555..0000000 --- a/examples/mediaplayer/spengine.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ -#include "spengine.h" -#include <phonon> - -using namespace Phonon; - -class SPEnginePvt -{ - public: - MediaObject* mediaObject; - AudioOutput* audioOutput; -}; -void SPEngine::clearQueue() -{ - pvt->mediaObject->clearQueue(); -} - -int SPEngine::currentTime() const -{ - return pvt->mediaObject->currentTime (); -} -int SPEngine::totalTime() const -{ - return pvt->mediaObject->totalTime(); -} - -void SPEngine::enqueue (const QUrl & u) -{ - pvt->mediaObject->enqueue(MediaSource(u)); -} -void SPEngine::setTrack(const QUrl & u) -{ - pvt->mediaObject->setCurrentSource(MediaSource(u)); -} -void SPEngine::play() -{ - pvt->mediaObject->play (); -} - -void SPEngine::pause() -{ - pvt->mediaObject->pause (); -} - -void SPEngine::stop() -{ - pvt->mediaObject->stop(); -} - -void SPEngine::seek(qint64 pos) -{ - pvt->mediaObject->seek(pos); -} - -void SPEngine::setVolume(int v) -{ - pvt->audioOutput->setVolume((qreal)v/100); -} - -void SPEngine::onVolumeChanged(qreal r) -{ - emit volumeChanged(r*100); -} -int SPEngine::volume() const -{ - return pvt->audioOutput->volume()*100; -} - -SPEngine::SPEngine(QObject* p) : QObject(p) -{ - pvt = new SPEnginePvt; - pvt->mediaObject = new Phonon::MediaObject(this); - pvt->audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this); - createPath (pvt->mediaObject, pvt->audioOutput); - pvt->mediaObject->setTickInterval(500); - connect (pvt->mediaObject, SIGNAL(aboutToFinish()), this, SIGNAL(aboutToFinish())); - connect (pvt->mediaObject, SIGNAL(tick(qint64)), this, SIGNAL(tick(qint64))); - connect (pvt->mediaObject, SIGNAL(totalTimeChanged(qint64)), this, SIGNAL(totalTimeChanged(qint64))); - connect (pvt->audioOutput, SIGNAL(volumeChanged(qreal)), this, SLOT(onVolumeChanged(qreal))); -} - -SPEngine::~SPEngine () -{ - delete pvt; -} diff --git a/examples/mediaplayer/spengine.h b/examples/mediaplayer/spengine.h deleted file mode 100644 index cf69e16..0000000 --- a/examples/mediaplayer/spengine.h +++ /dev/null @@ -1,50 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ -#ifndef SPENGINE_H -#define SPENGINE_H -#include <QObject> -#include <QUrl> -class SPEngine : public QObject -{ - Q_OBJECT - Q_PROPERTY(int totalTime READ totalTime) - Q_PROPERTY(int currentTime READ currentTime) - Q_PROPERTY(int volume READ volume WRITE setVolume) - - Q_SIGNALS: - void aboutToFinish(); - void tick(qint64); - void totalTimeChanged(qint64); - void volumeChanged(int); - - public Q_SLOTS: - void clearQueue(); - void enqueue (const QUrl &); - void setTrack(const QUrl &); - void play(); - void pause(); - void seek(qint64); - void stop (); - - protected Q_SLOTS: - void onVolumeChanged(qreal); - - public: - SPEngine(QObject*); - virtual ~SPEngine (); - int currentTime () const; - int totalTime () const; - void setVolume(int); - int volume () const; - - private: - class SPEnginePvt* pvt; -}; -#endif diff --git a/examples/mediaplayer/spharvester.cpp b/examples/mediaplayer/spharvester.cpp deleted file mode 100644 index dd7a110..0000000 --- a/examples/mediaplayer/spharvester.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ -#include "spharvester.h" -#include <QDir> -#include <phonon> -#include <QQueue> -#include <QFile> -#include <QUrl> - -using namespace Phonon; - -struct SPHarvesterPvt -{ - MediaObject* mediaObject; - QQueue<QString> pathQueue; -}; - -SPHarvester::SPHarvester(QObject* o) : QObject(o) -{ - pvt = new SPHarvesterPvt; - pvt->mediaObject = new MediaObject(this); - connect (pvt->mediaObject, SIGNAL(metaDataChanged()), this, SLOT(readMetaData ())); -} - -SPHarvester::~SPHarvester() -{ - delete pvt; -} - -void SPHarvester::harvest (const QString & directory, bool recurse) -{ - QDir d (directory); - QFileInfoList l = d.entryInfoList(QStringList() << "*.mp3",recurse ? QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Files : QDir::Files); - foreach (QFileInfo fi, l) { - if (fi.isDir()) { - harvest (fi.absoluteFilePath(), recurse); - } else { - pvt->pathQueue.enqueue(fi.absoluteFilePath()); - } - } - harvestNext (); -} - -void SPHarvester::harvestNext () -{ - if (pvt->pathQueue.empty()) - emit done(); - else { - QString s = pvt->pathQueue.dequeue(); - pvt->mediaObject->setCurrentSource(MediaSource(s)); - } -} - -void SPHarvester::readMetaData () -{ - QStringList albums = pvt->mediaObject->metaData("ALBUM"); - QStringList titles = pvt->mediaObject->metaData("TITLE"); - QStringList artists = pvt->mediaObject->metaData("ARTIST"); - QStringList trackNums = pvt->mediaObject->metaData("TRACKNUMBER"); - SongData sd; - sd.url = pvt->mediaObject->currentSource().url().toString(); - sd.album = albums.count() ? albums[0] : "Unknown Album"; - sd.artist = artists.count() ? artists[0] : "Unknown Artist"; - sd.trackNumber = trackNums.count() ? trackNums[0].toInt() : 0; - sd.genres = pvt->mediaObject->metaData("GENRE"); - sd.title = titles.count() ? titles[0] : QFileInfo(sd.url).baseName(); - - emit foundTrack(sd); - harvestNext (); -} diff --git a/examples/mediaplayer/spharvester.h b/examples/mediaplayer/spharvester.h deleted file mode 100644 index 5a5ea65..0000000 --- a/examples/mediaplayer/spharvester.h +++ /dev/null @@ -1,34 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ -#ifndef SPHARVESTER_H -#define SPHARVESTER_H - -#include "songdata.h" -class SPHarvester : public QObject -{ - Q_OBJECT -public: - SPHarvester(QObject* o = NULL); - virtual ~SPHarvester (); -public slots: - void harvest (const QString & directory, bool recurse = true); - -private slots: - void harvestNext (); - void readMetaData(); -signals: - void foundTrack (const SongData & d); - void done (); - -private: - class SPHarvesterPvt* pvt; -}; - -#endif // _H diff --git a/examples/mediaplayer/spmodel.cpp b/examples/mediaplayer/spmodel.cpp deleted file mode 100644 index cb549a8..0000000 --- a/examples/mediaplayer/spmodel.cpp +++ /dev/null @@ -1,283 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ -#include "spmodel.h" -#include <QSqlQueryModel> -#include <QtSql> -#include <QStandardItemModel> -#include <QMessageBox> -// an SQL query model that always as column (0) as uid and column (1) as display -class SPSqlQueryModel : public QSqlQueryModel -{ - Q_OBJECT - public: - SPSqlQueryModel (QObject* o = NULL): QSqlQueryModel (o) {} - virtual QVariant data(const QModelIndex & index, int role) const - { - QModelIndex idx(index); - if (role == Qt::DisplayRole && query().record().count() > 1) { - idx = idx.sibling(idx.row(),1); - } else if (role == Qt::UserRole) - role = Qt::DisplayRole; - return QSqlQueryModel::data(idx,role); - } -}; - - -class SPModelPvt -{ - public: - SPSqlQueryModel - artistModel, - albumModel, - songModel, - playlistModel, genreModel; - - QSqlQuery artistQuery, albumQuery, songQuery, playlistQuery, genreQuery, playingQuery; - -}; - -SPModel::SPModel(QObject* o) - :QObject(o) -{ - QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); - db.setDatabaseName("sqlite.db"); - if (!db.open()) { - QMessageBox::critical(0, qApp->tr("Cannot open database"), - qApp->tr("Unable to establish a database connection.\n" - "This example needs SQLite support. Please read " - "the Qt SQL driver documentation for information how " - "to build it.\n\n" - "Click Cancel to exit."), QMessageBox::Cancel); - } - - db.exec("CREATE TABLE IF NOT EXISTS songs (song_url VARCHAR(1024) PRIMARY KEY, song_title VARCHAR(1024), song_artist VARCHAR(1024), song_album VARCHAR(1024), song_track_index SMALLINT)"); - db.exec("DROP TABLE genres"); - db.exec("CREATE TABLE IF NOT EXISTS genres (genre_title VARCHAR(64), genre_song_url VARCHAR(1024))"); -// db.exec("CREATE TABLE IF NOT EXISTS playlists (playlist_id VARACHAR(256) PRIMARY KEY, playlist_title VARCHAR(1024))"); -// db.exec("CREATE TABLE IF NOT EXISTS playlist_songs (playlist_song_id BIGINT PRIMARY KEY, playlist_song_playlist - - pvt = new SPModelPvt; - pvt->artistQuery = QSqlQuery("SELECT DISTINCT song_artist FROM songs"); - pvt->albumQuery = QSqlQuery("SELECT DISTINCT song_album FROM songs"); - pvt->playlistQuery = QSqlQuery("SELECT playlist_url, playlist_title FROM playlists"); - pvt->songQuery = QSqlQuery("SELECT song_url, song_title from songs"); - pvt->genreQuery = QSqlQuery("SELECT DISTINCT genre_title from genres"); - QSqlQuery q; -// q.exec("SELECT DISTINCT song_url,song_title FROM songs, genres WHERE genre_song_url=song_url AND genre_title='All'"); - q.exec("SELECT * from genres"); - while (q.next()) { - qDebug () << q.value(0); - } -} - -void SPModel::addSong ( const SongData & data) -{ - - QSqlQuery q; - q.prepare("SELECT count(*) FROM songs WHERE song_url=:url"); - q.bindValue(":url",data.url); - bool inserting = true; - if (q.exec()) { - q.next(); - inserting = q.value(0).toInt() == 0; - } - if (inserting) { - q.prepare ("INSERT INTO songs (song_url, song_title, song_artist, song_album, song_track_index) VALUES (:url, :title, :artist, :album, :track)"); - } else { - q.prepare("UPDATE songs SET song_title=:title, song_album=:album, song_track_index=:track WHERE song_url=:url "); - } - q.bindValue(":url",data.url); - q.bindValue(":title",data.title); - q.bindValue(":artist",data.artist); - q.bindValue(":album",data.album); - q.bindValue(":track",data.trackNumber); - q.exec(); - - q.prepare ("DELETE FROM genres WHERE genre_song_url=:url"); - q.bindValue(":url",data.url); - q.exec(); - - q.prepare ("INSERT INTO genres (genre_song_url, genre_title) VALUES(:url, :genre)"); - q.bindValue(":url",data.url); - QStringList gn = data.genres; - gn << "All"; - foreach (QString g, gn) { - q.bindValue(":genre",g); - q.exec (); - } - - if (inserting) { - emit albumChanged(data.album); - emit songListChanged(); - emit artistChanged(data.artist); - foreach (QString g, data.genres) { - emit genreChanged(g); - } - } - - -} - - -SPModel::~SPModel() -{ - delete pvt; -} - -int SPModel::albumCount() const -{ - return pvt->albumModel.rowCount(); -} - -void SPModel::clearAlbumFilter () -{ - pvt->albumQuery = QSqlQuery ("SELECT DISTINCT song_album FROM songs "); -} -void SPModel::clearSongFilter () -{ - pvt->songQuery = QSqlQuery ("SELECT song_url, song_title FROM songs"); -} -void SPModel::loadArtists () -{ - pvt->artistQuery.exec (); - pvt->artistModel.setQuery(pvt->artistQuery); -} -void SPModel::filterAlbumsByArtist(const QString & artist) -{ - pvt->albumQuery.prepare("SELECT DISTINCT song_album FROM songs WHERE song_artist=:artist"); - pvt->albumQuery.bindValue(":artist",artist); -} -void SPModel::filterSongsByAlbum(const QString & album) -{ - pvt->albumQuery.prepare("SELECT song_url,song_title, song_track_index FROM songs WHERE song_album=:album ORDER BY song_track_index"); - pvt->albumQuery.bindValue(":album",album); -} -void SPModel::loadGenres () -{ - pvt->genreQuery.exec(); - pvt->genreModel.setQuery(pvt->genreQuery); -} - -void SPModel::filterSongsByGenre(const QString & genre) -{ - pvt->songQuery.prepare ("SELECT DISTINCT song_url,song_title FROM songs, genres WHERE genre_song_url=song_url AND genre_title=:genre"); - pvt->songQuery.bindValue(":genre",genre); -} -void SPModel::loadPlaylists() -{ - pvt->playlistQuery.exec (); - pvt->playlistModel.setQuery(pvt->playlistQuery); -} -void SPModel::loadAlbums() -{ - pvt->albumQuery.exec (); - pvt->albumModel.setQuery(pvt->albumQuery); -} -void SPModel::filterSongsByPlaylist(const QString & uid) -{ - pvt->songQuery.prepare("SELECT DISTINCT song_url, song_title, playlist_song_index FROM playlist_songs INNER JOIN songs ON playlist_song_url=song_url WHERE playlist_id=:playlist ORDER BY playlist_song_index"); - pvt->songQuery.bindValue(":playlist",uid); -} -void SPModel::loadSongs () -{ - pvt->songQuery.exec (); - pvt->songModel.setQuery(pvt->songQuery); -} -QUrl SPModel::currentSong() -{ - if (pvt->playingQuery.isValid()) - return QUrl(pvt->playingQuery.value(0).toString()); - else - return QUrl(); -} -QString SPModel::currentSongTitle() -{ - if (pvt->playingQuery.isValid()) - return pvt->playingQuery.value(1).toString(); - else - return QString(); -} -QString SPModel::currentSongArtist() -{ - QSqlQuery q; - q.prepare("SELECT song_artist FROM songs WHERE song_url=:url"); - q.bindValue(":url",currentSong().toString()); - q.exec(); - q.next(); - return q.value(0).toString(); -} -QString SPModel::currentSongAlbum() -{ - QSqlQuery q; - q.prepare("SELECT song_album FROM songs WHERE song_url=:url"); - q.bindValue(":url",currentSong().toString()); - q.exec(); - q.next(); - return q.value(0).toString(); -} - -void SPModel::selectSong (const QString & s) -{ - pvt->playingQuery = QSqlQuery(pvt->songQuery.executedQuery ()); - - while (pvt->playingQuery.next()) { - if (pvt->playingQuery.value(0).toString() == s) { - emit songChanged (); - return; - } - } - emit endOfList (); -} - -void SPModel::reset () -{ - pvt->playingQuery = QSqlQuery(pvt->songQuery.executedQuery ()); - pvt->playingQuery.exec(); -} - -void SPModel::gotoNext() -{ - if (pvt->playingQuery.next()) { - emit songChanged (); - }else - emit endOfList (); -} -void SPModel::gotoPrev() -{ - if (pvt->playingQuery.previous()) - emit songChanged (); - else - emit endOfList (); -} - - - -QAbstractItemModel* SPModel::albumsItemModel() const -{ - return &pvt->albumModel; -} -QAbstractItemModel* SPModel::genresItemModel() const -{ - return &pvt->genreModel; -} -QAbstractItemModel* SPModel::songsItemModel() const -{ - return &pvt->songModel; -} -QAbstractItemModel* SPModel::playlistsItemModel() const -{ - return &pvt->playlistModel; -} -QAbstractItemModel* SPModel::artistsItemModel() const -{ - return &pvt->artistModel; -} - -#include <spmodel.moc> diff --git a/examples/mediaplayer/spmodel.h b/examples/mediaplayer/spmodel.h deleted file mode 100644 index 0ba4560..0000000 --- a/examples/mediaplayer/spmodel.h +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ -#ifndef SPMODEL_H -#define SPMODEL_H -#include <QObject> -#include <QUrl> -#include <QAbstractItemModel> -#include "songdata.h" - -class SPModel : public QObject -{ - Q_OBJECT - - Q_PROPERTY(QUrl currentSong READ currentSong) - Q_PROPERTY(QString currentSongTitle READ currentSongTitle) - Q_PROPERTY(QString currentSongArtist READ currentSongArtist) - Q_PROPERTY(QString currentSongAlbum READ currentSongAlbum) - Q_PROPERTY(int albumCount READ albumCount) - - - public slots: - void clearAlbumFilter (); - void clearSongFilter (); - void loadArtists (); - void filterAlbumsByArtist(const QString & name); - void loadGenres (); - void filterSongsByGenre(const QString & genre); - void loadPlaylists(); - void loadAlbums(); - void filterSongsByPlaylist(const QString & uid); - void filterSongsByAlbum(const QString & name); - void loadSongs (); - void selectSong (const QString &); - void gotoNext(); - void gotoPrev(); - void addSong (const SongData &); - void reset (); - - signals: - void albumChanged(const QString &); - void artistChanged(const QString &); - void genreChanged(const QString &); - void songListChanged(); - void songChanged (); - void endOfList (); - - public: - SPModel(QObject*); - virtual ~SPModel (); - - QUrl currentSong(); - QString currentSongTitle (); - QString currentSongArtist(); - QString currentSongAlbum(); - QAbstractItemModel* albumsItemModel() const; - QAbstractItemModel* genresItemModel() const; - QAbstractItemModel* songsItemModel() const; - QAbstractItemModel* playlistsItemModel() const; - QAbstractItemModel* artistsItemModel() const; - int albumCount() const; - - private: - class SPModelPvt* pvt; -}; - -#endif diff --git a/examples/mediaplayer/spview.cpp b/examples/mediaplayer/spview.cpp deleted file mode 100644 index e74e64d..0000000 --- a/examples/mediaplayer/spview.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ -#include "spview.h" -#include "spmodel.h" -#include <QDebug> -#include <QItemDelegate> - -class SPViewPvt -{ - public: - SPModel* model; -}; - - -class SPItemDelegate : public QItemDelegate -{ - Q_OBJECT - -public: - SPItemDelegate(QObject* o) : QItemDelegate(o) {} - - virtual void paint (QPainter* p, QStyleOptionViewItem & option, const QModelIndex & index) const - { - QString disp = index.data(Qt::DisplayRole).toString(); - drawBackground(p,option,index); - drawDisplay(p,option,option.rect,disp); - } -}; - -void SPView::setModel (SPModel* m) -{ - pvt->model = m; -} - -void SPView::showAlbums () -{ - listView->setModel (pvt->model->albumsItemModel()); -} - -void SPView::showArtists () -{ - listView->setModel (pvt->model->artistsItemModel()); -} - -void SPView::showGenres () -{ - QAbstractItemModel* model = pvt->model->genresItemModel(); - listView->setModel (model); -} - -void SPView::showSongs () -{ - listView->setModel (pvt->model->songsItemModel()); -} - -void SPView::showPlaylists() -{ - listView->setModel (pvt->model->playlistsItemModel()); -} - - -SPView::SPView(QWidget* w) : QWidget (w) -{ - pvt = new SPViewPvt; - setupUi(this); - listView->setItemDelegate(new SPItemDelegate(this)); -} - -QString SPView::currentItem() const -{ - QVariant v = listView->model()->data(listView->currentIndex(),Qt::UserRole); - if (v.isNull()) - v = listView->currentIndex().data(Qt::DisplayRole); - return v.toString (); -} - -int SPView::itemCount () const -{ - return listView->model()->rowCount (); -} -int SPView::currentIndex() const -{ - return listView->currentIndex().row(); -} - -void SPView::setTotalTime (int t) -{ - posSlider->setMaximum(t); -} -void SPView::setCurrentTime (int t) -{ - posSlider->setValue (t); -} - -SPView::~SPView () -{ - delete pvt; -} -#include "spview.moc" diff --git a/examples/mediaplayer/spview.h b/examples/mediaplayer/spview.h deleted file mode 100644 index 3b855bb..0000000 --- a/examples/mediaplayer/spview.h +++ /dev/null @@ -1,46 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ - -#ifndef SPVIEW_H -#define SPVIEW_H -#include <QObject> -#include <QUrl> -#include "spmodel.h" -#include "ui_mediaplayer.h" - -class SPView : public QWidget, public virtual Ui::mediaPlayerWidget -{ - Q_OBJECT - Q_PROPERTY(QString currentItem READ currentItem) - Q_PROPERTY(int itemCount READ itemCount) - Q_PROPERTY(int currentIndex READ currentIndex) - public slots: - void setModel (SPModel*); - void showAlbums (); - void showArtists (); - void showGenres (); - void showSongs (); - void showPlaylists(); - void setTotalTime (int); - void setCurrentTime (int); - - - public: - SPView(QWidget*); - virtual ~SPView (); - QString currentItem () const; - int itemCount () const; - int currentIndex() const; - - private: - class SPViewPvt* pvt; -}; - -#endif diff --git a/qscxml.pro b/qscxml.pro deleted file mode 100644 index 67fed9e..0000000 --- a/qscxml.pro +++ /dev/null @@ -1,2 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS += src examples
\ No newline at end of file diff --git a/scc/README b/scc/README deleted file mode 100644 index 35e0ee0..0000000 --- a/scc/README +++ /dev/null @@ -1,13 +0,0 @@ -To build: - qmake - make - make install - -To use: - Add to your .pro file: - CONFIG += scc - STATECHARTS += path-to-my-statechart.scxml - -See the examples, and the documentation (currently only in doc.txt) - - diff --git a/scc/doc.txt b/scc/doc.txt deleted file mode 100644 index 6c82ebb..0000000 --- a/scc/doc.txt +++ /dev/null @@ -1,78 +0,0 @@ -This document describes the expected behaviour of SCC (the Qt State Chart Compiler) in regards to SCXML tags and features. - -SCXML - Ignored: version, profile, exmode - -STATE - Ignored: src - -TRANSITION - Ignored: anchor - Additional: Qt:animation, a location expression that points to a QPropertyAnimation* object - Notes: An event in a transition translates to a Qt signal in the state machine object. "*" would occur on any event. Prefix matching is not supported, but * and done events are supported. - Conditions are C++ boolean expressions. -PARALLEL - Ignored: src - -HISTORY: - Notes: The history's default transition cannot have executable content. - -LOG: - Notes: the level of the log translates to QtMsgType. expr is a c++ expression. - -SEND: - Partially supported: target (only "_internal") - Ignored attributes: type, idlocation, hints - Notes: The target attribute can be either empty for a regular event, "_internal" for an internal-queue event, or a location expression to emit a signal in an object. - -CANCEL: - Notes: ID is a string literal, not an expression - -DATA: - Ignored attributes: src - Additional: Qt:type, to define a C++ type for this data element - Notes: A data element is converted to a Qt property of the state-machine object. expr/text are C++ expressions - -ASSIGN: - Notes: If dataid is present rather than location, the generated code would use the Qt property system to assign the value. expr is a c++ expression. - -PARAM - Notes: either name, expr or inline-text can appear, as the parameters are translated to a QVariantList. - -SCRIPT - Notes: raw C++ code - -Fully supported: - INITIAL, FINAL, ONENTRY, ONEXIT, IF, ELSEIF, ELSE, LOG, CANCEL, DATAMODEL - -Unsupported: - INVOKE, CONTENT, DONEDATA, FINALIZE, ANCHOR, VALIDATE - -Qt:property - object - property - value - -Qt:cpp - text() - -system variables - _event - _data - _name - - -INVOKE -CONTENT -VALIDATE -DONEDATA - - -script -Qt:cpp -cond -(variables) -param -log -if/elseif/else -assign diff --git a/scc/examples/algotest/algotest.pro b/scc/examples/algotest/algotest.pro deleted file mode 100644 index e5a1eba..0000000 --- a/scc/examples/algotest/algotest.pro +++ /dev/null @@ -1,6 +0,0 @@ -TEMPLATE = app -SOURCES += main.cpp -OTHER_FILES += test.scxml -STATECHARTS += test.scxml -CONFIG += scc console -QT -= gui diff --git a/scc/examples/algotest/main.cpp b/scc/examples/algotest/main.cpp deleted file mode 100644 index c8b74e1..0000000 --- a/scc/examples/algotest/main.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at http://www.qtsoftware.com/contact. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "sc_test.h" -#include <QCoreApplication> -#include <QTimer> -int main(int argc, char *argv[]) -{ - QCoreApplication a(argc, argv); - SMClass_test stateMachine; - stateMachine.setupStateMachine(); - stateMachine.start(); - QObject::connect(stateMachine.state_Test2Sub1,SIGNAL(entered()),&stateMachine,SIGNAL(event_Event2())); - QObject::connect(&stateMachine,SIGNAL(finished()),&a,SLOT(quit())); - QTimer::singleShot(100,&stateMachine,SIGNAL(event_Event1())); - return a.exec(); -} - diff --git a/scc/examples/algotest/test.scxml b/scc/examples/algotest/test.scxml deleted file mode 100644 index e17f9bf..0000000 --- a/scc/examples/algotest/test.scxml +++ /dev/null @@ -1,145 +0,0 @@ -<?xml version="1.0" encoding="UTF8"?> -<!-- A wrapper state that contains all other states in this file -- it represents the complete state machine --> <scxml xmlns="http://www.w3.org/2005/07/scxml" - version="1.0" - initial="Main"> - <state id="Main"> - <!-- its initial state is Test1 --> - <initial> - <transition target="Test1"/> - </initial> - - <!-- Really simple state showing the basic syntax. --> - <state id="Test1"> - <initial> - <transition target="Test1Sub1"/> - </initial> - <!-- Runs before we go into the substate --> - <onentry> - <log expr=""Inside Test1""/> - </onentry> - - <!-- Here is our first substate --> - <state id="Test1Sub1"> - <onentry> - <log expr=""Inside Test1Sub1.""/> - </onentry> - <onexit> - <log expr=""Leaving Test1Sub1""/> - </onexit> - <!-- Go to Sub2 on Event1 --> - <transition event="Event1" target="Test1Sub2"/> - </state> - - <!-- Here is the second substate - It is final, so Test1 is done when we get here --> - <final id="Test1Sub2"/> - - <!-- We get this event when we reach Test1Sub2. --> - <transition event="done.state.Test1" target="Test2"/> - - <!-- We run this on the way out of Test1 --> - <onexit> - <log expr=""Leaving Test1...""/> - </onexit> - </state> - - <state id="Test2"> - <initial> - <transition target="Test2Sub1"/> - </initial> - - <!-- This time we reference a state - defined in an external file. Note that we could have - loaded the entire file by leaving off the #Test2Sub1, - but in that case we would need to rename one of the - Test2Sub1 states (here or in the external file) to - avoid the name collision --> - <state id="Test2Sub1"> - <onentry> - <log expr=""Inside Test2Sub1""/> - </onentry> - <transition event="Event2" target="Test2Sub2"/> - </state> - <final id="Test2Sub2"/> - - <!-- Test2Sub2 is defined as final, so this - event is generated when we reach it --> - <transition event="done.state.Test2" target="Test3"/> - </state> - - <state id="Test3"> - <initial> - <transition target="Test3Sub1"/> - </initial> - - <state id="Test3Sub1"> - <onentry> - <log expr=""Inside Test3Sub1...""/> - <!-- Send our self an event in 5s --> - <send event="Timer" delay="1500"/> - </onentry> - <!-- Transition on to Test4. - This will exit both us and our parent. --> - <transition event="Timer" target="Test4"/> - <onexit> - <log expr=""Leaving Test3Sub1...""/> - </onexit> - </state> - - <onexit> - <log expr=""Leaving Test3...""/> - </onexit> - </state> - - <state id="Test4"> - <onentry> - <log expr=""Inside Test4...""/> - </onentry> - <initial> - <transition target="Test4Sub1"/> - </initial> - - <state id="Test4Sub1"> - <onexit> - <log expr=""Leaving Test4Sub1...""/> - </onexit> - <!-- This transition causes the state to exit immediately - after entering Test4Sub1. The transition has no event - or guard so it is always active --> - <transition target="Test5"/> - </state> - </state> - - <state id="Test5"> - <onentry> - <log expr=""Inside Test5...""/> - </onentry> - <initial> - <transition target="Test5P"/> - </initial> - - <!-- Fire off our parallel states --> - <parallel id="Test5P"> - <final id="Test5PSub1"/> - <final id="Test5PSub2"/> - <onexit> - <log expr=""all parallel states done""/> - </onexit> - </parallel> - - <!-- The parallel states are all final, so this - event is generated immediately. Although not shown, - compound states (i.e., <state>s with content) - are permitted within <parallel> as well. --> - <transition event="done.state.Test5P" target="Done"/> - </state> - - <!-- This final state is an immediate child of Main - - when we get here, done.state.Main is generated. --> - <final id="Done"/> - <!-- End of Main > --> - <transition event="done.state.Main" target="final" /> - </state> - <final id="final"/> -</scxml> diff --git a/scc/examples/animations/animations.pro b/scc/examples/animations/animations.pro deleted file mode 100644 index d501c13..0000000 --- a/scc/examples/animations/animations.pro +++ /dev/null @@ -1,6 +0,0 @@ -TEMPLATE = app -OTHER_FILES += animations.scxml -STATECHARTS += animations.scxml -CONFIG += scc console -SOURCES += main.cpp -TARGET = animations diff --git a/scc/examples/animations/animations.scxml b/scc/examples/animations/animations.scxml deleted file mode 100644 index 0aabb64..0000000 --- a/scc/examples/animations/animations.scxml +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-1"?> -<scxml xmlns="http://www.w3.org/2005/07/scxml" xmlns:Qt="http://www.qtsoftware.com scxml-ext" - initial="hist"> - <datamodel> - <data id="anim" Qt:type="QPropertyAnimation*" expr="NULL" /> - <data id="indicator" Qt:type="QObject*" expr="NULL" /> - </datamodel> - <history id="hist" type="deep"> - <transition target="idle" /> - </history> - <state id="idle"> - <Qt:property object="_data.indicator" property="opacity" value="0" /> - <transition target="active" event="ev1()" Qt:animation="_data.anim" /> - </state> - <state id="active"> - <Qt:property object="_data.indicator" property="opacity" value="1" /> - <transition target="idle" event="ev1()" Qt:animation="_data.anim" /> - </state> -</scxml> diff --git a/scc/examples/animations/main.cpp b/scc/examples/animations/main.cpp deleted file mode 100644 index cf816bc..0000000 --- a/scc/examples/animations/main.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at http://www.qtsoftware.com/contact. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "sc_animations.h" -#include <QApplication> -#include <QGraphicsView> -#include <QLabel> -#include <QGraphicsProxyWidget> -#include <QShortcut> -#include <QGraphicsScene> -#include <QPushButton> -#include <QVBoxLayout> -int main(int argc, char *argv[]) -{ - QApplication a(argc, argv); - SMClass_animations stateMachine; - QGraphicsView* gv = new QGraphicsView(); - QPushButton* b = new QPushButton(); - QWidget* w = new QWidget(); - QVBoxLayout* lyt = new QVBoxLayout(); - lyt->addWidget(gv); - lyt->addWidget(b); - b->setText("Push Me"); - QObject::connect(b,SIGNAL(clicked()),&stateMachine,SIGNAL(event_ev1())); - w->setLayout(lyt); - gv->setScene(new QGraphicsScene()); - gv->setInteractive(true); - gv->setFocus(); - QGraphicsProxyWidget* wdg = gv->scene()->addWidget(new QLabel("Hello World!")); - wdg->setOpacity(0); - QPropertyAnimation* anim = new QPropertyAnimation(); - anim->setPropertyName("opacity"); - anim->setTargetObject(wdg); - anim->setDuration(1000); - anim->setEasingCurve(QEasingCurve(QEasingCurve::InOutCubic)); - stateMachine.set_indicator(wdg); - stateMachine.set_anim(anim); - stateMachine.setupStateMachine(); - w->show(); - stateMachine.start(); - return a.exec(); -} - diff --git a/scc/examples/examples.pro b/scc/examples/examples.pro deleted file mode 100644 index 39b6dbb..0000000 --- a/scc/examples/examples.pro +++ /dev/null @@ -1,2 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = loginmvc animations algotest diff --git a/scc/examples/loginmvc/controller.scxml b/scc/examples/loginmvc/controller.scxml deleted file mode 100644 index 8bffc1a..0000000 --- a/scc/examples/loginmvc/controller.scxml +++ /dev/null @@ -1,105 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-1"?> -<scxml xmlns="http://www.w3.org/2005/07/scxml" - xmlns:Qt="http://www.qtsoftware.com scxml-ext" - initial="root"> - <datamodel> - <data id="username" Qt:type="QString" /> - <data id="password" Qt:type="QString" /> - <data id="loginTimeout" Qt:type="int" expr="10000" /> - <data id="firstTime" Qt:type="bool" expr="true" /> - <data id="loginButton" Qt:type="QObject*" expr="NULL" /> - <data id="logoutButton" Qt:type="QObject*" expr="NULL" /> - <data id="cancelButton" Qt:type="QObject*" expr="NULL" /> - </datamodel> - <parallel id="root"> - <state id="business_logic"> - <initial> - <transition target="idle"> - <if cond="_data.firstTime"> - <send event="notify_welcome()" /> - <if cond="!_data.username.isEmpty()"> - <send event="notify_hello(QString)"> - <param expr="_data.username" /> - </send> - </if> - <assign dataid="firstTime" expr="false" /> - </if> - </transition> - </initial> - <state id="idle"> - <onentry><log level="0" label="Info" expr=""Now in Idle"" /><raise event="in_idle" /></onentry> - <onexit><log level="0" label="Info" expr=""Now not in Idle"" /><raise event="not_in_idle" /></onexit> - <transition target="trying_to_login" event="intent_login()" /> - <Qt:property object="_data.cancelButton" property="enabled" value="false" /> - </state> - <state id="trying_to_login"> - <Qt:property object="_data.cancelButton" property="enabled" value="true" /> - <transition event="cancel_login()" target="idle" /> - <transition event="login_timeout()" target="loginTimeout" /> - <onentry> - <log level="0" label="Info" expr=""Trying to log in"" /> - <send event="login_action(QString,QString)"> - <param expr="_data.username" /> - <param expr="_data.password" /> - </send> - <send id="cancel_login_timeout" event="login_timeout()" delay="_data.loginTimeout" /> - </onentry> - <onexit> - <cancel id="cancel_login_timeout" /> - </onexit> - <transition event="login_complete(bool)" cond="_event.data[0].toBool()" target="loggedIn" /> - <transition event="login_complete(bool)" cond="!_event.data[0].toBool()" target="loginError" /> - </state> - <state id="error" initial="loginError"> - <Qt:property object="_data.cancelButton" property="enabled" value="false" /> - <transition event="intent_continue()" target="idle" /> - <onentry> - <raise event="error.login()" /> - </onentry> - <state id="cancelled"> - <onentry> - <send event="notify_cancel()" /> - </onentry> - </state> - <state id="loginError"> - <onentry> - <log label="Error" level="1" expr="_data.username + ' ' + _data.password" /> - <send event="notify_error()" /> - </onentry> - </state> - <state id="loginTimeout"> - <onentry> - <log label="Error" level="1" expr="_data.username + ' ' + _data.password" /> - <send event="notify_timeout()" /> - </onentry> - </state> - </state> - <state id="loggedIn"> - <onentry> - <send event="notify_loggedIn()" /> - </onentry> - <transition event="intent_continue()" target="active" /> - </state> - <state id="active"> - <transition event="intent_logout()" target="idle" /> - <Qt:property object="_data.cancelButton" property="enabled" value="false" /> - </state> - <final id="exit" /> - </state> - <state id="gui" initial="hist"> - <history id="hist" type="deep"> - <transition target="gui_idle" /> - </history> - <state id="gui_idle"> - <Qt:property object="_data.loginButton" property="enabled" value="true" /> - <Qt:property object="_data.logoutButton" property="enabled" value="false" /> - <transition target="gui_active" cond="!In(idle)" /> - </state> - <state id="gui_active"> - <transition target="gui_idle" cond="In(idle)" /> - <Qt:property object="_data.loginButton" property="enabled" value="false" /> - <Qt:property object="_data.logoutButton" property="enabled" value="true" /> - </state> - </state> - </parallel> -</scxml> diff --git a/scc/examples/loginmvc/frame.ui b/scc/examples/loginmvc/frame.ui deleted file mode 100644 index 4b57955..0000000 --- a/scc/examples/loginmvc/frame.ui +++ /dev/null @@ -1,123 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<ui version="4.0"> - <class>Frame</class> - <widget class="QFrame" name="Frame"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>337</width> - <height>158</height> - </rect> - </property> - <property name="windowTitle"> - <string>Login Workflow</string> - </property> - <property name="frameShape"> - <enum>QFrame::StyledPanel</enum> - </property> - <property name="frameShadow"> - <enum>QFrame::Raised</enum> - </property> - <layout class="QFormLayout" name="formLayout"> - <property name="fieldGrowthPolicy"> - <enum>QFormLayout::AllNonFixedFieldsGrow</enum> - </property> - <item row="0" column="0"> - <widget class="QLabel" name="label"> - <property name="text"> - <string>Username</string> - </property> - </widget> - </item> - <item row="0" column="1"> - <widget class="QLineEdit" name="usernameEdit"/> - </item> - <item row="1" column="0"> - <widget class="QLabel" name="label_2"> - <property name="text"> - <string>Password</string> - </property> - </widget> - </item> - <item row="1" column="1"> - <widget class="QLineEdit" name="passwordEdit"> - <property name="echoMode"> - <enum>QLineEdit::Password</enum> - </property> - </widget> - </item> - <item row="2" column="0"> - <widget class="QLabel" name="label_3"> - <property name="text"> - <string>Timeout</string> - </property> - </widget> - </item> - <item row="2" column="1"> - <widget class="QSlider" name="timeoutSlider"> - <property name="maximum"> - <number>20000</number> - </property> - <property name="singleStep"> - <number>500</number> - </property> - <property name="pageStep"> - <number>2000</number> - </property> - <property name="value"> - <number>10000</number> - </property> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - </widget> - </item> - <item row="4" column="1"> - <widget class="QWidget" name="widget" native="true"> - <layout class="QHBoxLayout" name="horizontalLayout_2"> - <item> - <spacer name="horizontalSpacer"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>40</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item> - <widget class="QPushButton" name="loginButton"> - <property name="text"> - <string>Log In</string> - </property> - </widget> - </item> - <item> - <widget class="QPushButton" name="logoutButton"> - <property name="text"> - <string>Logout</string> - </property> - </widget> - </item> - <item> - <widget class="QPushButton" name="cancelButton"> - <property name="text"> - <string>Cancel</string> - </property> - </widget> - </item> - </layout> - </widget> - </item> - <item row="5" column="1"> - <layout class="QHBoxLayout" name="horizontalLayout"/> - </item> - </layout> - </widget> - <resources/> - <connections/> -</ui> diff --git a/scc/examples/loginmvc/loginmvc.pro b/scc/examples/loginmvc/loginmvc.pro deleted file mode 100644 index 9af965a..0000000 --- a/scc/examples/loginmvc/loginmvc.pro +++ /dev/null @@ -1,8 +0,0 @@ -TEMPLATE = app -CONFIG += console scc -SOURCES = main.cpp -FORMS += frame.ui -QT += network -STATECHARTS += controller.scxml -OTHER_FILES += controller.scxml -CONFIG -= app_bundle diff --git a/scc/examples/loginmvc/main.cpp b/scc/examples/loginmvc/main.cpp deleted file mode 100644 index 25b68d1..0000000 --- a/scc/examples/loginmvc/main.cpp +++ /dev/null @@ -1,193 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at http://www.qtsoftware.com/contact. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QApplication> -#include "sc_controller.h" -#include <QLabel> -#include <QMessageBox> -#include "ui_frame.h" -#include <QNetworkAccessManager> -#include <QNetworkReply> -#include <QSslSocket> -class AbstractModel : public QObject -{ - Q_OBJECT - public: - AbstractModel(QObject* o = NULL) : QObject(o) - { - } - public slots: - virtual void login(const QString & u, const QString & p) = 0; - signals: - void loginComplete(bool); -}; - -class DummyModel : public AbstractModel -{ - Q_OBJECT - public: - DummyModel(QObject* o = NULL) : AbstractModel(o) - { - } - public slots: - void test() - { - emit loginComplete(user == "user" && password == "password"); - } - virtual void login(const QString & u, const QString & p) - { - user = u; password = p; - QTimer::singleShot(5000,this,SLOT(test())); - } - signals: - void loginComplete(bool); - private: - QString user,password; - QNetworkAccessManager netAccess; -}; -class GMailModel : public AbstractModel -{ - Q_OBJECT - public: - GMailModel(QObject* o = NULL) : AbstractModel(o) - { - } - public slots: - void loginFinished() - { - QNetworkReply* rep = qobject_cast<QNetworkReply*>(sender()); - rep->deleteLater(); - qDebug() << rep->error() << rep->errorString(); - emit loginComplete(rep->error() == QNetworkReply::NoError); - } - virtual void login(const QString & u, const QString & p) - { - QNetworkRequest req; - QUrl url("https://mail.google.com/mail/feed/atom"); - url.setUserName(u); - url.setPassword(p); - req.setUrl(url); - QNetworkReply* reply = netAccess.get(req); - reply->ignoreSslErrors(); - connect(reply,SIGNAL(finished()),this,SLOT(loginFinished())); - } - private: - QNetworkAccessManager netAccess; -}; - -class MyView : public QFrame, public virtual Ui::Frame -{ - Q_OBJECT - public: - QString welcomeText; - MyView(QWidget* o = NULL) : QFrame(o) - { - setupUi(this); - connect(loginButton,SIGNAL(clicked()),this,SIGNAL(loginIntent())); - connect(logoutButton,SIGNAL(clicked()),this,SIGNAL(logoutIntent())); - connect(cancelButton,SIGNAL(clicked()),this,SIGNAL(cancelIntent())); - } - - public slots: - - void notifyLogin() - { - QMessageBox::information(this,"Logged In","You are now logged in!"); - emit contIntent(); - } - void notifyTimeout() - { - QMessageBox::information(this,"Timeout...","Sorry, login has timed out"); - emit contIntent(); - } - void notifyWelcome() - { - QMessageBox::information(this,"Welcome!",welcomeText); - } - void notifyError() - { - qDebug() << "notifyError"; - QMessageBox::warning(this,"Not Logged in","Login has failed..."); - emit contIntent(); - } - - void notifyHello(const QString & name) - { - QMessageBox::information(this,"Welcome",QString("Hello ") + name); - } - - signals: - void loginIntent(); - void logoutIntent(); - void cancelIntent(); - void contIntent(); -}; -int main(int argc, char *argv[]) -{ - QApplication a(argc, argv); - bool use_gmail = QSslSocket::supportsSsl () && !a.arguments().contains("--dummy"); - AbstractModel* model = use_gmail ? (AbstractModel*)new GMailModel() : (AbstractModel*)new DummyModel(); - MyView* view = new MyView(); - SMClass_controller *controller = new SMClass_controller(); - controller->setupStateMachine(); - controller->set_loginButton(view->loginButton); - controller->set_logoutButton(view->logoutButton); - controller->set_cancelButton(view->cancelButton); - view->welcomeText = (use_gmail ?"Please enter your GMail user/password":"Username=user, Password=password"); - QObject::connect(controller,SIGNAL(event_login_action(QString,QString)),model,SLOT(login(QString,QString))); - QObject::connect(controller,SIGNAL(event_notify_loggedIn()),view,SLOT(notifyLogin())); - QObject::connect(controller,SIGNAL(event_notify_error()),view,SLOT(notifyError())); - QObject::connect(controller,SIGNAL(event_notify_hello(QString)),view,SLOT(notifyHello(QString))); - QObject::connect(controller,SIGNAL(event_notify_welcome()),view,SLOT(notifyWelcome())); - QObject::connect(controller,SIGNAL(event_notify_timeout()),view,SLOT(notifyTimeout())); - QObject::connect(model,SIGNAL(loginComplete(bool)),controller,SIGNAL(event_login_complete(bool))); - QObject::connect(view,SIGNAL(loginIntent()),controller,SIGNAL(event_intent_login())); - QObject::connect(view,SIGNAL(cancelIntent()),controller,SIGNAL(event_cancel_login())); - QObject::connect(view,SIGNAL(logoutIntent()),controller,SIGNAL(event_intent_logout())); - QObject::connect(view,SIGNAL(contIntent()),controller,SIGNAL(event_intent_continue())); - QObject::connect(view->usernameEdit,SIGNAL(textChanged(QString)),controller,SLOT(set_username(QString))); - QObject::connect(view->passwordEdit,SIGNAL(textChanged(QString)),controller,SLOT(set_password(QString))); - QObject::connect(view->timeoutSlider,SIGNAL(valueChanged(int)),controller,SLOT(set_loginTimeout(int))); - controller->start(); - view->show(); - return a.exec(); -} -#include <main.moc> diff --git a/scc/main.cpp b/scc/main.cpp deleted file mode 100644 index e5f4206..0000000 --- a/scc/main.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at http://www.qtsoftware.com/contact. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QCoreApplication> -#include <QXmlQuery> -#include <QUrl> -#include <QStringList> -#include <QFile> -#include <QFileInfo> -#include <QDir> -#include <QDebug> -#include <QXmlSchema> -#include <QXmlSchemaValidator> -void usage() -{ - printf("scc [--no-comments] -i input-file -o output-file"); - exit(-1); -} -int main(int argc, char *argv[]) -{ - QCoreApplication a(argc, argv); - QXmlQuery query(QXmlQuery::XSLT20); - if (a.arguments().count() < 3 || a.arguments().contains("--help")) - { - usage(); - } - int idxOfInput = a.arguments().indexOf("-i")+1; - int idxOfOutput = a.arguments().indexOf("-o")+1; - if (idxOfInput <= 1 && idxOfOutput <= 1) - { - usage(); - } - QString input = a.arguments().at(idxOfInput); - QString output = a.arguments().at(idxOfOutput); - QUrl target = QUrl::fromLocalFile(QDir::current().absoluteFilePath(".")).resolved(QUrl(input)); -// QXmlSchema schema; -// QFile schemaFile(":/scxml.xsd"); -// schemaFile.open(QIODevice::ReadOnly); -// schema.load(&schemaFile); -// QXmlSchemaValidator validator; -// if (!validator.validate(target)) { -// return -1; -// } - query.setFocus(target); - QFile q(":/scc/scc.xslt"); - q.open(QIODevice::ReadOnly); - query.bindVariable("target",QXmlItem(QFileInfo(target.toLocalFile()).baseName())); - query.bindVariable("comments",QXmlItem(!a.arguments().contains("--no-comments"))); - query.setQuery(QString(q.readAll())); - if (!query.isValid()) - return -1; - - QString s; - query.evaluateTo(&s); - s = s.replace("<","<").replace(""","\"").replace(">",">").replace("&","&"); - QFile f(output); - f.open(QIODevice::WriteOnly); - f.write(s.toUtf8()); - return 0; -// return a.exec(); -} diff --git a/scc/scc.prf b/scc/scc.prf deleted file mode 100644 index b6ecc21..0000000 --- a/scc/scc.prf +++ /dev/null @@ -1,21 +0,0 @@ -isEmpty(QMAKE_SCC) { - win32:QMAKE_SCC = $$[QT_INSTALL_BINS]\scc.exe - else:QMAKE_SCC = $$[QT_INSTALL_BINS]/scc -} - -isEmpty(QMAKE_MOD_SCC):QMAKE_MOD_SCC = sc_ - -scc.output = $$QMAKE_MOD_SCC${QMAKE_FILE_BASE}.h -scc.commands = $$QMAKE_SCC -i ${QMAKE_FILE_NAME} -o ${QMAKE_FILE_OUT} -scc.depends = ${QMAKE_FILE_NAME} $$QMAKE_SCC -scc.input = STATECHARTS -scc.variable_out = SCC_HEADERS HEADERS GENERATED_FILES -QMAKE_EXTRA_COMPILERS += scc -load(moc) -scc_moc.commands = $$moc_header.commands -scc_moc.output = $$moc_header.output -scc_moc.input = SCC_HEADERS -scc_moc.variable_out = GENERATED_SOURCES -scc_moc.name = $$moc_header.name -QMAKE_EXTRA_COMPILERS += scc_moc - diff --git a/scc/scc.pro b/scc/scc.pro deleted file mode 100644 index 32008bb..0000000 --- a/scc/scc.pro +++ /dev/null @@ -1,16 +0,0 @@ -# ------------------------------------------------- -# Project created by QtCreator 2009-08-02T10:07:01 -# ------------------------------------------------- -QT += xmlpatterns -QT -= gui -TARGET = scc -CONFIG += console -CONFIG -= app_bundle -TEMPLATE = app -SOURCES += main.cpp -RESOURCES += scc.qrc -target.path = $$[QT_INSTALL_PREFIX]/bin -prf.files = scc.prf -prf.path = $$[QMAKE_MKSPECS]/features -INSTALLS += target prf -OTHER_FILES += scc.prf diff --git a/scc/scc.qrc b/scc/scc.qrc deleted file mode 100644 index 0e4ffa0..0000000 --- a/scc/scc.qrc +++ /dev/null @@ -1,5 +0,0 @@ -<RCC> - <qresource prefix="/scc"> - <file>scc.xslt</file> - </qresource> -</RCC> diff --git a/scc/scc.xslt b/scc/scc.xslt deleted file mode 100644 index e023e96..0000000 --- a/scc/scc.xslt +++ /dev/null @@ -1,374 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-1"?> -<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:s="http://www.w3.org/2005/07/scxml" - xmlns:Qt="http://www.qtsoftware.com scxml-ext"> -<xsl:template name="smname"><xsl:choose><xsl:when test="string(/s:scxml/@name)=''"><xsl:value-of select="$target" /></xsl:when> - <xsl:otherwise><xsl:value-of select="/sLscxml/@name" /></xsl:otherwise></xsl:choose> -</xsl:template> -<xsl:template name="comment"><xsl:if test="$comments"> - /* - <xsl:element name="{name()}"> - <xsl:for-each select="@*"><xsl:attribute name="{name()}"> - <xsl:value-of select="string()" /></xsl:attribute></xsl:for-each><xsl:value-of select="text()" /></xsl:element> - */ -</xsl:if></xsl:template> -<xsl:template mode="stateid" match="s:scxml|s:state|s:parallel|s:final|s:initial|s:history" priority="2"> - <xsl:choose> - <xsl:when test="name()='scxml'">this</xsl:when> - <xsl:when test="string(@id) != ''" >state_<xsl:value-of select="@id" /></xsl:when> - <xsl:otherwise>state_<xsl:value-of select="generate-id()" /></xsl:otherwise> - </xsl:choose> -</xsl:template> -<xsl:template mode="execContext" match="s:if"> -<xsl:call-template name="comment" /> - if (<xsl:value-of select="@cond" />) { - <xsl:apply-templates mode="execContext" /> - } -</xsl:template> -<xsl:template mode="execContext" match="s:else"> -<xsl:call-template name="comment" /> - } else { -</xsl:template> -<xsl:template mode="execContext" match="s:elseif"> -<xsl:call-template name="comment" /> - } else if (<xsl:value-of select="@cond" />) { -</xsl:template> -<xsl:template mode="execContext" match="s:log"> -<xsl:call-template name="comment" /> - QDebug((QtMsgType)<xsl:if test="string(@level)=''">0</xsl:if><xsl:value-of select="@level" />) <xsl:if test="string(@label)!=''"><< "<xsl:value-of select="@label" />" </xsl:if><< <xsl:value-of select="@expr" />; -</xsl:template> -<xsl:template mode="execContext" match="s:assign"><xsl:call-template name="comment" /> -<xsl:choose> - - <xsl:when test="string(@dataid) != ''"> - set_<xsl:value-of select="@dataid" />(<xsl:value-of select="@expr" />); - </xsl:when> - <xsl:when test="string(@location) != ''"> - <xsl:value-of select="@location" /> = (<xsl:value-of select="@expr" />); - </xsl:when> -</xsl:choose> -</xsl:template> -<xsl:template mode="execContext" match="s:raise|s:send"> -<xsl:call-template name="comment" /> - <xsl:choose> - <xsl:when test="name()='raise' or target='_internal'">postInternalEvent(</xsl:when> - <xsl:otherwise><xsl:if test="string(@id)!=''"> - _eventSenders["<xsl:value-of select="@id" />"] = </xsl:if>new SCC_EventSender(this,<xsl:if test="string(@delay)=''">0</xsl:if> - <xsl:value-of select="@delay" />, - </xsl:otherwise> - </xsl:choose> - new QSignalEvent(<xsl:if - test="string(@target)=''">this</xsl:if><xsl:value-of - select="@target" />,metaObject()->indexOfSignal(QMetaObject::normalizedSignature("event_<xsl:value-of select="replace(@event,'\.','__')" /><xsl:if test="not(contains(@event,')'))">()</xsl:if>")),QVariantList()<xsl:for-each - select="s:param"><xsl:text><![CDATA[<<]]></xsl:text> QVariant(<xsl:choose> - <xsl:when test="string(@expr)!=''"><xsl:value-of select="@expr" /></xsl:when> - <xsl:when test="string(@name)!=''">get_<xsl:value-of select="@name" />()</xsl:when> - <xsl:otherwise><xsl:value-of select="text()" /></xsl:otherwise> - </xsl:choose>) - </xsl:for-each>)); -</xsl:template> -<xsl:template mode="execContext" match="s:cancel"> -<xsl:call-template name="comment" /><![CDATA[ - { - QPointer<SCC_EventSender> es = _eventSenders["]]><xsl:value-of select="@id" />"]; - if (es) - es->cancel(); - } -</xsl:template> - -<xsl:template match="/"> -#ifndef __SMCLASS_<xsl:call-template name="smname" />_H -#define __SMCLASS_<xsl:call-template name="smname" />_H -#include "QStateMachine" -#include "QSignalTransition" -#include "QTimer" -#include "QMetaMethod" -#include "QPointer" -#include "QVariant" -<xsl:if test="count(//s:final)!=0"> - - #include "QFinalState" -</xsl:if> -<xsl:if test="count(//s:history)!=0"> - #include "QHistoryState" -</xsl:if> -#include "QHash" -#include "QSignalEvent" -#include "QEventTransition" -<xsl:if test="count(//s:log)!=0"> -#include "QDebug" -</xsl:if> -<xsl:if test="count(//s:transition[string(@Qt:animation)!=''])!=0"> -#include "QPropertyAnimation" -</xsl:if> - -#define In(state) (configuration().contains(state_##state)) - -<xsl:value-of select="/s:scxml/Qt:cpp/text()" /> - -class SMClass_<xsl:call-template name="smname" />; - <xsl:if test="count(//s:transition[string(@event)='' and string(@cond)=''])!=0"> - class SCC_UnconditionalTransition : public QAbstractTransition - { - public: - SCC_UnconditionalTransition(QState* s) - : QAbstractTransition(s) {} - protected: - void onTransition(QEvent *) {} - bool eventTest(QEvent *) { return true; } - }; - </xsl:if> - <xsl:if test="count(//s:send[string(@target)!='_internal'])!=0"> - <![CDATA[ - #define ARG_FROM_VAR(I) \ - (acount > I \ - ? QGenericArgument(((QSignalEvent*)event)->arguments()[I].typeName(),((QSignalEvent*)event)->arguments()[I].data()) \ - : QGenericArgument()) - - - class SCC_EventSender : public QTimer - { - Q_OBJECT - private: - QStateMachine* machine; - QSignalEvent* event; - public: - SCC_EventSender(QStateMachine* m=NULL, int delay=0, QSignalEvent* e=NULL) : QTimer(m), machine(m), event(e) - { - setInterval(delay); - setSingleShot(true); - connect(this,SIGNAL(timeout()),this,SLOT(send())); - start(); - } - public Q_SLOTS: - void cancel() { stop(); deleteLater(); } - void send() { - QVariantList args = event->arguments(); - int acount = args.count(); - event->sender()->metaObject()->method(event->signalIndex()).invoke(event->sender(), - ARG_FROM_VAR(0),ARG_FROM_VAR(1),ARG_FROM_VAR(2),ARG_FROM_VAR(3),ARG_FROM_VAR(4), - ARG_FROM_VAR(5),ARG_FROM_VAR(6),ARG_FROM_VAR(7),ARG_FROM_VAR(8),ARG_FROM_VAR(9)); - deleteLater(); - } - }; - ]]></xsl:if> - <xsl:if test="count(//s:transition[string(@cond) != '' or @event='*']) !=0"> -namespace { - <xsl:for-each select="//s:transition[string(@cond) != '' or @event='*']"> - <xsl:call-template name="comment" /> - class Transition_<xsl:value-of select="generate-id()" /> : public QSignalTransition - { - SMClass_<xsl:call-template name="smname" />* stateMachine; - public: - Transition_<xsl:value-of select="generate-id()" />(QState* parent) - : QSignalTransition(parent->machine(),<xsl:choose><xsl:when test="@event='*'">SIGNAL(destroyed())</xsl:when><xsl:otherwise>SIGNAL(event_<xsl:value-of select="@event" />)</xsl:otherwise></xsl:choose>,parent) - ,stateMachine((SMClass_<xsl:call-template name="smname" />*)parent->machine()) - { - } - - protected: - bool eventTest(QEvent* e); - }; - - </xsl:for-each> -}; - </xsl:if> -class SMClass_<xsl:call-template name="smname" /> : public QStateMachine -{ - Q_OBJECT -<xsl:for-each select="//s:datamodel/s:data"> - <xsl:call-template name="comment" /> - Q_PROPERTY(<xsl:value-of select="concat(@Qt:type,' ')" /> <xsl:value-of select="@id" /> READ get_<xsl:value-of select="@id" /> WRITE set_<xsl:value-of select="@id" /> NOTIFY <xsl:value-of select="@id" />_changed) -</xsl:for-each> -<xsl:for-each select="//s:transition/Qt:animation"> - <xsl:call-template name="comment" /> - Q_PROPERTY(QPropertyAnimation* <xsl:value-of select="string()" /> READ anim_<xsl:value-of select="string()" /> WRITE setAnim_<xsl:value-of select="string()" />) -</xsl:for-each> - - public: - SMClass_<xsl:call-template name="smname" />(QObject* o = NULL) - : QStateMachine(o) - { -<xsl:for-each select="//s:datamodel/s:data[string-length(concat(string(text()),string(@expr)))!=0]"> - <xsl:call-template name="comment" /> - <xsl:if test="string(@expr) != ''"> - _data.<xsl:value-of select="@id" /> = <xsl:value-of select="@expr"/><xsl:value-of select="text()"/>; - </xsl:if> -</xsl:for-each> - } - <xsl:for-each select="//s:state|//s:parallel|//s:initial"> - <xsl:call-template name="comment" /> - QState* <xsl:apply-templates mode="stateid" select="." />;</xsl:for-each> - <xsl:for-each select="//s:final"> - <xsl:call-template name="comment" /> - QFinalState* <xsl:apply-templates mode="stateid" select="." />; - </xsl:for-each> - <xsl:for-each select="//s:history"> - <xsl:call-template name="comment" /> - QHistoryState* <xsl:apply-templates mode="stateid" select="." />; - </xsl:for-each> - <xsl:for-each select="//s:transition[string(@cond) != '']"> - <xsl:call-template name="comment" /> - inline bool testCondition_<xsl:value-of select="generate-id()" />() - { - return <xsl:if test="string(@cond)=''">true</xsl:if><xsl:value-of select="@cond"/>; - } - </xsl:for-each> - <xsl:for-each select="//s:datamodel/s:data"> - <xsl:call-template name="comment" /> - <xsl:text> </xsl:text><xsl:value-of select="@Qt:type" /> get_<xsl:value-of select="@id" />() const - { - return _data.<xsl:value-of select="@id" />; - } - </xsl:for-each> - <xsl:if test="count(//s:datamodel/s:data) != 0"><![CDATA[ - protected: - struct { - ]]><xsl:for-each select="//s:datamodel/s:data"> - <xsl:call-template name="comment" /> - <xsl:text> </xsl:text><xsl:value-of select="@Qt:type" /><xsl:text> </xsl:text><xsl:value-of select="@id" />; - </xsl:for-each> - } _data; - </xsl:if> - struct { - QString name; - QVariantList data; - } _event; - QString _name; - <xsl:if test="(count(//s:datamodel/s:data)+count(/s:scxml/s:script))!=0"> - public Q_SLOTS: -</xsl:if> -<xsl:for-each select="//s:datamodel/s:data"> - <xsl:call-template name="comment" /> - void set_<xsl:value-of select="@id" />(<xsl:value-of select="@Qt:type" /> const & value) - { - _data.<xsl:value-of select="@id" /> = value; - emit <xsl:value-of select="@id" />_changed(value); - } - </xsl:for-each> - private Q_SLOTS: -#ifndef QT_NO_PROPERTIES - void assignProperties() - { - <xsl:for-each select="//Qt:property"> - <xsl:call-template name="comment" /> -<xsl:text> </xsl:text><xsl:apply-templates mode="stateid" select=".." />->assignProperty(<xsl:value-of - select="@object" />,"<xsl:value-of select="@property" />",QVariant(<xsl:value-of select="@value" />)); - </xsl:for-each> -#endif - } - <xsl:for-each select="//s:transition|//s:onentry|//s:onexit"><xsl:if test="count(*) != 0"> - <xsl:for-each select="..|."><xsl:call-template name="comment" /></xsl:for-each> - void exec_<xsl:value-of select="generate-id()" />() - { - <xsl:apply-templates mode="execContext" /> - } - </xsl:if></xsl:for-each> - Q_SIGNALS:<xsl:for-each select="distinct-values(//node()[not (starts-with(@event,'done.state.') or @event='*' or contains(@event,':'))]/@event)"> - void event_<xsl:value-of select="replace(string(),'\.','__')" /><xsl:if test="not(contains(string(),')'))">()</xsl:if>;</xsl:for-each> - <xsl:for-each select="//s:datamodel/s:data"> - <xsl:call-template name="comment" /> - void <xsl:value-of select="@id" />_changed(<xsl:value-of select="@Qt:type" /> const &); - </xsl:for-each> - <xsl:if test="count(//Qt:property)!=0"><![CDATA[ - protected: - virtual void beginSelectTransitions(QEvent *event) - { - if (event && !event->type() == QEvent::None) { - switch (event->type()) { - case QEvent::Signal: { - QSignalEvent* e = (QSignalEvent*)event; - _event.data = e->arguments(); - _event.name = e->sender()->metaObject()->method(e->signalIndex()).signature(); - if (e->sender() == this) - _event.name = _event.name.mid(6); - } break; - default: - break; - } - } else { - _event.name = ""; - _event.data.clear(); - } - ]]> - assignProperties(); - } -</xsl:if> -<xsl:if test="count(//s:send[string(@target)!='internal']) != 0"> - private: - <xsl:text><![CDATA[QHash<QString,QPointer<SCC_EventSender> >]]></xsl:text> _eventSenders; -</xsl:if> - protected: - public: - void setupStateMachine() - { - _name = "<xsl:call-template name="smname" />"; - setObjectName(_name); - <xsl:for-each select="//s:state|//s:parallel|//s:final|//s:history|//s:initial"> - <xsl:call-template name="comment" /> - <xsl:text> </xsl:text><xsl:apply-templates mode="stateid" select="." /> = new <xsl:choose> - <xsl:when test="name()='final'">QFinalState</xsl:when> - <xsl:when test="name()='history'">QHistoryState</xsl:when> - <xsl:otherwise>QState</xsl:otherwise> - </xsl:choose>(<xsl:apply-templates mode="stateid" select=".." />); - <xsl:if test="string(@id)!=''"><xsl:apply-templates mode="stateid" select="." />->setObjectName("<xsl:value-of select="@id" />");</xsl:if> - <xsl:if - test="name()='initial' or @id=../@initial"> - <xsl:apply-templates mode="stateid" select=".." />->setInitialState(<xsl:apply-templates mode="stateid" select="." />); - </xsl:if> - <xsl:if test="name()='parallel'"> - <xsl:apply-templates mode="stateid" select="." />->setChildMode(ParallelStates); - </xsl:if> - <xsl:if test="name()='history'"> - <xsl:apply-templates mode="stateid" select="." />->setHistoryType(QHistoryState::<xsl:choose> - <xsl:when test="@type='deep'">Deep</xsl:when> - <xsl:otherwise>Shallow</xsl:otherwise> - </xsl:choose>History); - </xsl:if> - </xsl:for-each> - QAbstractTransition* transition;<xsl:for-each select="//s:transition[../name()!='history']"> - <xsl:call-template name="comment" /> - transition = new <xsl:choose> - <xsl:when test="@event='*' or string(@cond)!=''">Transition_<xsl:value-of - select="generate-id()" />(</xsl:when> - <xsl:when test="starts-with(@event,'q-event:')">QEventTransition(<xsl:value-of - select="substring-after(@event,'q-event:')" />,</xsl:when> - <xsl:when test="starts-with(@event,'done.state.')">QSignalTransition(state_<xsl:value-of - select="substring-after(@event,'done.state.')" />,SIGNAL(finished()),</xsl:when> - <xsl:when test="string(@event)!=''">QSignalTransition(this,SIGNAL(event_<xsl:value-of select="replace(@event,'\.','__')" /><xsl:if test="not(ends-with(@event,')'))">()</xsl:if>),</xsl:when> - <xsl:otherwise>SCC_UnconditionalTransition(</xsl:otherwise></xsl:choose><xsl:apply-templates mode="stateid" select=".." />);<xsl:if test="count(*) != 0"> - connect(transition,SIGNAL(triggered()),this,SLOT(exec_<xsl:value-of select="generate-id()" />()));</xsl:if> - <xsl:if test="string(@Qt:animation) != ''"> - transition->addAnimation(<xsl:value-of select="@Qt:animation" />);</xsl:if><xsl:if - test="string(@target) != ''"></xsl:if> - <xsl:choose> - <xsl:when test="string(@target)=''" /> - <xsl:when test="count(tokenize(@target,'\s+'))=1"> - transition->setTargetState(state_<xsl:value-of select="@target" />);</xsl:when> - <xsl:otherwise>(*transition).setTargetStates(QList<QAbstractState*>()<xsl:for-each - select="tokenize(@target,'\s+')"> << state_<xsl:value-of select="." /></xsl:for-each>);</xsl:otherwise> - </xsl:choose> - </xsl:for-each> - <xsl:for-each select="//s:history/s:transition"> - <xsl:apply-templates mode="stateid" select=".." />->setDefaultState(state_<xsl:value-of select="@target" />); - </xsl:for-each> - <xsl:for-each select="//s:onentry|//s:onexit"><xsl:if test="count(*) != 0"> - connect(<xsl:apply-templates mode="stateid" select=".." />, SIGNAL(<xsl:choose> - <xsl:when test="name()='onentry'">entered</xsl:when> - <xsl:when test="name()='onexit'">exited</xsl:when> - </xsl:choose>()),this,SLOT(exec_<xsl:value-of select="generate-id()" />()));</xsl:if></xsl:for-each> - <xsl:value-of select="/s:scxml/s:script/text()" /> - } -}; - <xsl:for-each select="//s:transition[@event='*' or string(@cond) != '']"> - <xsl:call-template name="comment" /> - bool Transition_<xsl:value-of select="generate-id()" />::eventTest(QEvent* e) - { - return <xsl:choose><xsl:when test="@event!='*'">Q<xsl:if test="string(@event) != ''">Signal</xsl:if>Transition::eventTest(e) - </xsl:when><xsl:otherwise>(*e).type() != QEvent::None</xsl:otherwise></xsl:choose><xsl:if test="string(@cond)!=''">&& stateMachine->testCondition_<xsl:value-of - select="generate-id()" />()</xsl:if>; - } - </xsl:for-each> -#endif - </xsl:template> - -</xsl:stylesheet> diff --git a/src/qscxml.cpp b/src/qscxml.cpp deleted file mode 100644 index daa1ec6..0000000 --- a/src/qscxml.cpp +++ /dev/null @@ -1,1618 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ -/*! - \class QScxml - - \brief The QScxml class provides a way to use scripting with the Qt State Machine Framework. - - Though can be used alone, QScxml is mainly a runtime helper to using the - state-machine framework with SCXML files. - - - \sa QStateMachine -*/ -#ifndef QT_NO_STATEMACHINE - -#include "qscxml.h" -#include <QScriptEngine> -#include <QScriptValueIterator> -#include <QDebug> -#include <QTimer> -#include <QSignalMapper> -#include <QUuid> -#include <QHash> -#include <QXmlStreamReader> -#include <QFileInfo> -#include <QDir> -#include <QSet> -#include <QStack> -#include <QHistoryState> -#include <QFinalState> -#include <QState> -#include <QMetaMethod> -#ifdef QT_GUI_LIB -#include "qscxmlgui.h" -#endif - - - -class QtScxmlSnoopInternal : public QObject - { - Q_OBJECT - - friend class QtScxmlSnoop; - - QtScxmlSnoopInternal(QObject* o) :QObject(o) { } - ~QtScxmlSnoopInternal() { - if (parent()) parent()->deleteLater(); - } - - signals: - void signal (const QVariantList &); - }; - class QtScxmlSnoop: public QObject - { - public: - QtScxmlSnoopInternal* inobj; - QtScxmlSnoop(QObject *obj, const char *aSignal):QObject(obj) - { -#ifdef Q_CC_BOR - const int memberOffset = QObject::staticMetaObject.methodCount(); -#else - static const int memberOffset = QObject::staticMetaObject.methodCount(); -#endif - Q_ASSERT(obj); - Q_ASSERT(aSignal); - - if (aSignal[0] - '0' != QSIGNAL_CODE) { - qWarning("QtScxmlSnoop: Not a valid signal, use the SIGNAL macro"); - return; - } - - QByteArray ba = QMetaObject::normalizedSignature(aSignal + 1); - const QMetaObject *mo = obj->metaObject(); - int sigIndex = mo->indexOfMethod(ba.constData()); - if (sigIndex < 0) { - qWarning("QtScxmlSnoop: No such signal: '%s'", ba.constData()); - return; - } - - if (!QMetaObject::connect(obj, sigIndex, this, memberOffset, - Qt::QueuedConnection, 0)) { - qWarning("QtScxmlSnoop: QMetaObject::connect returned false. Unable to connect."); - return; - } - sig = ba; - QMetaMethod member = mo->method(sigIndex); - QList<QByteArray> params = member.parameterTypes(); - for (int i = 0; i < params.count(); ++i) { - int tp = QMetaType::type(params.at(i).constData()); - if (tp == QMetaType::Void) - qWarning("Don't know how to handle '%s', use qRegisterMetaType to register it.", - params.at(i).constData()); - args << tp; - } - inobj = new QtScxmlSnoopInternal (this); - } - - inline bool isValid() const { return !sig.isEmpty(); } - inline QByteArray signal() const { return sig; } - - - int qt_metacall(QMetaObject::Call call, int id, void **a) - { - id = QObject::qt_metacall(call, id, a); - if (id < 0) - return id; - - if (call == QMetaObject::InvokeMetaMethod) { - if (id == 0) { - QVariantList list; - for (int i = 0; i < args.count(); ++i) { - QMetaType::Type type = static_cast<QMetaType::Type>(args.at(i)); - QVariant v(type, a[i + 1]); - list << v; - - } - emit inobj->signal (list); - } - --id; - } - return id; - } - - - - // the full, normalized signal name - QByteArray sig; - // holds the QMetaType types for the argument list of the signal - QList<int> args; - - }; - -QObject* q_snoopConnect ( - QObject* sender, - const char* signal, - QObject* receiver, - const char* method - ) -{ - QtScxmlSnoop* o = new QtScxmlSnoop(sender,signal); - if (o->isValid()) { - QObject::connect (o->inobj, SIGNAL(signal(QVariantList)),receiver,method); - QObject::connect (receiver, SIGNAL(destroyed()), o, SLOT(deleteLater())); - } - return o; -} - -class QScxmlPrivate -{ - public: - - enum { MaxSnapshots = 200}; - - struct AnchorSnapshot - { - QAbstractState* state; - QString location; - QScriptValue snapshot; - QString anchorType; - }; - - void initScriptEngine(QScxml* thiz); - - - QScriptEngine* scriptEng; - QList<QScxmlInvokerFactory*> invokerFactories; - QUrl burl; - QString sessionID; - QString startScript; - - - QStack<AnchorSnapshot> snapshotStack; - QMultiHash<QString,QAbstractTransition*> anchorTransitions; - QHash<QString,AnchorSnapshot> curSnapshot; - - - static QHash<QString,QScxml*> sessions; -}; -QHash<QString,QScxml*> QScxmlPrivate::sessions; - -class QScxmlTimer : public QObject -{ - Q_OBJECT - public: - QScxmlTimer(QScriptEngine* engine, const QScriptValue & scr, int delay) : QObject(engine),script(scr) - { - QTimer::singleShot(delay,this,SLOT(exec())); - } - protected Q_SLOTS: - void exec() - { - if (script.isFunction()) - script.call(); - else if (script.isString()) - script.engine()->evaluate(script.toString()); - deleteLater(); - } - - private: - QScriptValue script; - -}; - -static QScriptValue _q_deepCopy(const QScriptValue & val) -{ - if (val.isObject() || val.isArray()) { - QScriptValue v = val.isArray() ? val.engine()->newArray() : val.engine()->newObject(); - v.setData(val.data()); - QScriptValueIterator it (val); - while (it.hasNext()) { - it.next(); - v.setProperty(it.name(), _q_deepCopy(it.value())); - } - return v; - } else - return val; -} -class QScxmlSignalReceiver : public QObject -{ - Q_OBJECT - QScxml* scxml; - QString eventName; - public: - QScxmlSignalReceiver(QScxml* s, QString ename) : QObject(s),scxml(s),eventName(ename) - { - } - public Q_SLOTS: - void receiveSignal(const QVariantList & pvals) - { - QStringList pnames; - for (int i=0; i < pvals.count(); ++i) { - pnames << QString::number(i); - } - QScxmlEvent* ev = new QScxmlEvent(eventName,pnames,pvals,QScriptValue()); - ev->metaData.kind = QScxmlEvent::MetaData::Platform; - scxml->postEvent(ev); - } -}; -struct QScxmlFunctions -{ -static QScriptValue connectSignalToEvent(QScriptContext* context, QScriptEngine*) -{ - QScxml* scxml = qobject_cast<QScxml*>(context->thisObject().toQObject()); - if (scxml) { - QObject* obj = context->argument(0).toQObject(); - QString sig = ('0'+QSIGNAL_CODE)+context->argument(1).toString(); - QString ename = context->argument(2).toString(); - - if (obj) - { - q_snoopConnect(obj,sig.toAscii().constData(),new QScxmlSignalReceiver(scxml,ename),SLOT(receiveSignal(QVariantList))); - } - } - return QScriptValue(); -} - -static QScriptValue cssTime(QScriptContext *context, QScriptEngine *engine) -{ - QString str; - if (context->argumentCount() > 0) - str = context->argument(0).toString(); - if (str == "") { - return qScriptValueFromValue<int>(engine,0); - } - else if (str.endsWith("ms")) { - return qScriptValueFromValue<int>(engine,(str.left(str.length()-2).toInt())); - } - else if (str.endsWith("s")) { - return qScriptValueFromValue<int>(engine,(str.left(str.length()-1).toInt())*1000); - } - else { - return qScriptValueFromValue<int>(engine, (str.toInt())); - } -} -static QScriptValue setTimeout(QScriptContext *context, QScriptEngine *engine) -{ - if (context->argumentCount() < 2) - return QScriptValue(); - int timeout = context->argument(1).toInt32(); - QScxmlTimer* tmr = new QScxmlTimer(engine,context->argument(0),timeout); - return engine->newQObject(tmr); -} -static QScriptValue script_print(QScriptContext *context, QScriptEngine *) -{ - if (context->argumentCount() > 0) - qDebug() << context->argument(0).toString(); - return QScriptValue(); -} -static QScriptValue clearTimeout(QScriptContext *context, QScriptEngine *) -{ - if (context->argumentCount() > 0) { - QObject* obj = context->argument(0).toQObject(); - obj->deleteLater(); - } - return QScriptValue(); -} - -static QScriptValue deepCopy(QScriptContext *context, QScriptEngine *) -{ - if (context->argumentCount() == 0) - return QScriptValue(); - else - return _q_deepCopy(context->argument(0)); -} - -static QScriptValue postEvent(QScriptContext *context, QScriptEngine *) -{ - QScxml* scxml = qobject_cast<QScxml*>(context->thisObject().toQObject()); - if (scxml) { - QString eventName,target,type; - QStringList pnames; - QVariantList pvals; - QScriptValue cnt; - if (context->argumentCount() > 0) - eventName = context->argument(0).toString(); - if (context->argumentCount() > 1) - target = context->argument(1).toString(); - if (context->argumentCount() > 2) - type = context->argument(2).toString(); - - if (!eventName.isEmpty() || !target.isEmpty()) { - if (context->argumentCount() > 3) - qScriptValueToSequence<QStringList>(context->argument(3),pnames); - if (context->argumentCount() > 4) { - QScriptValueIterator it (context->argument(4)); - while (it.hasNext()) { - it.next(); - pvals.append(it.value().toVariant()); - } - } if (context->argumentCount() > 5) - cnt = context->argument(5); - QScxmlEvent* ev = new QScxmlEvent(eventName,pnames,pvals,cnt); - if (type == "scxml" || type == "") { - bool ok = true; - if (target == "_internal") { - ev->metaData.kind = QScxmlEvent::MetaData::Internal; - scxml->postInternalEvent(ev); - } else if (target == "scxml" || target == "") { - ev->metaData.kind = QScxmlEvent::MetaData::External; - scxml->postEvent(ev); - } else if (target == "_parent") { - QScxmlInvoker* p = qobject_cast<QScxmlInvoker*>(scxml->parent()); - if (p) - p->postParentEvent(ev); - else - ok = false; - } else { - QScxml* session = QScxmlPrivate::sessions[target]; - if (session) { - session->postEvent(ev); - } else - ok = false; - } - if (!ok) - scxml->postNamedEvent("error.targetunavailable"); - - } else { - scxml->postNamedEvent("error.send.typeinvalid"); - } - } - } - return QScriptValue(); -} - -// scxml.invoke (type, target, paramNames, paramValues, content) -static QScriptValue invoke(QScriptContext *context, QScriptEngine *engine) -{ - QScxml* scxml = qobject_cast<QScxml*>(context->thisObject().toQObject()); - if (scxml) { - QString type,target; - QStringList pnames; - QVariantList pvals; - QScriptValue cnt; - if (context->argumentCount() > 0) - type = context->argument(0).toString(); - if (type.isEmpty()) - type = "scxml"; - if (context->argumentCount() > 1) - target = context->argument(1).toString(); - if (context->argumentCount() > 2) - qScriptValueToSequence<QStringList>(context->argument(2),pnames); - if (context->argumentCount() > 3) { - QScriptValueIterator it (context->argument(3)); - while (it.hasNext()) { - it.next(); - pvals.append(it.value().toVariant()); - } - } if (context->argumentCount() > 4) - cnt = context->argument(4); - - QScxmlInvokerFactory* invf = NULL; - for (int i=0; i < scxml->pvt->invokerFactories.count() && invf == NULL; ++i) - if (scxml->pvt->invokerFactories[i]->isTypeSupported(type)) - invf = scxml->pvt->invokerFactories[i]; - if (invf) { - QScxmlEvent* ev = new QScxmlEvent("",pnames,pvals,cnt); - ev->metaData.origin = scxml->baseUrl(); - ev->metaData.target = target; - ev->metaData.targetType = type; - ev->metaData.originType = "scxml"; - ev->metaData.kind = QScxmlEvent::MetaData::External; - QScxmlInvoker* inv = invf->createInvoker(ev,scxml); - if (inv) - inv->activate(); - return engine->newQObject(inv); - } else { - scxml->postNamedEvent("error.invalidtargettype"); - } - - } - return QScriptValue(); -} - - -static QScriptValue isInState(QScriptContext *context, QScriptEngine *engine) -{ - QScxml* scxml = qobject_cast<QScxml*>(context->thisObject().toQObject()); - if (scxml) { - if (context->argumentCount() > 0) { - QString name = context->argument(0).toString(); - if (!name.isEmpty()) { - QSet<QAbstractState*> cfg = scxml->configuration(); - foreach (QAbstractState* st, cfg) { - if (st->objectName() == name) - return qScriptValueFromValue<bool>(engine,true); - } - } - } - } - return qScriptValueFromValue<bool>(engine,false); - -} - -}; - -void QScxmlPrivate::initScriptEngine(QScxml* thiz) -{ - QScriptValue glob = scriptEng->globalObject(); - QScriptValue scxmlObj = scriptEng->newQObject(thiz); - glob.setProperty("In",scriptEng->newFunction(QScxmlFunctions::isInState)); -// glob.setProperty("_rcvSig",scriptEng->newFunction(QScxmlFunctions::receiveSignal)); - scxmlObj.setProperty("print",scriptEng->newFunction(QScxmlFunctions::script_print)); - scxmlObj.setProperty("postEvent",scriptEng->newFunction(QScxmlFunctions::postEvent)); - scxmlObj.setProperty("invoke",scriptEng->newFunction(QScxmlFunctions::invoke)); - scxmlObj.setProperty("cssTime",scriptEng->newFunction(QScxmlFunctions::cssTime)); - scxmlObj.setProperty("clone",scriptEng->newFunction(QScxmlFunctions::deepCopy)); - scxmlObj.setProperty("setTimeout",scriptEng->newFunction(QScxmlFunctions::setTimeout)); - scxmlObj.setProperty("clearTimeout",scriptEng->newFunction(QScxmlFunctions::clearTimeout)); - scxmlObj.setProperty("connectSignalToEvent",scriptEng->newFunction(QScxmlFunctions::connectSignalToEvent)); - QScriptValue dmObj = scriptEng->newObject(); - glob.setProperty("_data",scriptEng->newObject()); - glob.setProperty("_global",scriptEng->globalObject()); - glob.setProperty("scxml",scxmlObj); -} - -/*! - \class QScxmlEvent - \brief The QScxmlEvent class stands for a general named event with a list of parameter names and parameter values. - - Encapsulates an event that conforms to the SCXML definition of events. - - -*/ -/*! \enum QScxmlEvent::MetaData::Kind - - This enum specifies the kind (or context) of the event. - \value Platform An event coming from the itself, such as a script error. - \value Internal An event sent with a <raise> or <send target="_internal">. - \value External An event sent from an invoker, directly from C++, or from a <send target="scxml"> element. -*/ - -/*! - Returns the name of the event. - */ - QString QScxmlEvent::eventName() const -{ - return ename; -} - /*! - Return a list containing the parameter names. - */ -QStringList QScxmlEvent::paramNames () const -{ - return pnames; -} - /*! - Return a list containing the parameter values. - */ -QVariantList QScxmlEvent::paramValues () const -{ - return pvals; -} - /*! - Return a QtScript object that can be passed as an additional parameter. - */ -QScriptValue QScxmlEvent::content () const -{ - return cnt; -} - /*! - Returns the parameter value equivalent to parameter \a name. - */ -QVariant QScxmlEvent::param (const QString & name) const -{ - int idx = pnames.indexOf(name); - if (idx >= 0) - return pvals[idx]; - else - return QVariant(); -} -/*! - Creates a QScxmlEvent named \a name, with parameter names \a paramNames, parameter values \a paramValues, and - a QtScript object \a content as an additional parameter. -*/ -QScxmlEvent::QScxmlEvent( - const QString & name, - const QStringList & paramNames, - const QVariantList & paramValues, - const QScriptValue & content) - - : QEvent(QScxmlEvent::eventType()),ename(name),pnames(paramNames),pvals(paramValues),cnt(content) -{ - metaData.kind = MetaData::Internal; -} - -/*! \class QScxmlTransition - \brief The QScxmlTransition class stands for a transition that responds to QScxmlEvent, and can be made conditional with a \l conditionExpression. - Equivalent to the SCXML transition tag. - - */ - - -/*! \property QScxmlTransition::eventPrefix - The event prefix to be used when testing if the transition needs to be invoked. - Uses SCXML prefix matching. Use * to handle any event. - */ -/*! \property QScxmlTransition::conditionExpression - A QtScript expression that's evaluated to test whether the transition needs to be invoked. - */ - -/*! - Creates a new QScxmlTransition from \a state, that uses \a machine to evaluate the conditions. - */ -QScxmlTransition::QScxmlTransition (QState* state,QScxml* machine) - : QAbstractTransition(state),scxml(machine) -{ -} -/*! - \reimp -*/ -void QScxmlTransition::onTransition(QEvent*) -{ -} -/*! - \internal - */ -bool QScxmlTransition::eventTest(QEvent *e) -{ - QScriptEngine* engine = scxml->scriptEngine(); - QString ev; - - if (e) { - if (e->type() == QScxmlEvent::eventType()) { - ev = ((QScxmlEvent*)e)->eventName(); - } - if (!(eventPrefix() == "*" || eventPrefix() == ev || ev.startsWith(eventPrefix()+"."))) - return false; - } - - - if (!conditionExpression().isEmpty()) { - - - QScriptValue v = engine->evaluate(conditionExpression(),scxml->baseUrl().toLocalFile()); - if (engine->hasUncaughtException()) { - - QScxmlEvent* e = new QScxmlEvent("error.illegalcond", - QStringList()<< "error" << "expr" << "line" << "backtrace", - QVariantList() - << QVariant(engine->uncaughtException().toString()) - << QVariant(conditionExpression()) - << QVariant(engine->uncaughtExceptionLineNumber()) - << QVariant(engine->uncaughtExceptionBacktrace())); - qDebug() << engine->uncaughtException().toString(); - e->metaData.kind = QScxmlEvent::MetaData::Platform; - scxml->postEvent(e); - engine->clearExceptions(); - return false; - } - return v.toBoolean(); - } - - return true; -} - -class QScxmlDefaultInvoker : public QScxmlInvoker -{ - Q_OBJECT - - - public: - QScxmlDefaultInvoker(QScxmlEvent* ievent, QScxml* p) : QScxmlInvoker(ievent,p),cancelled(false),childSm(0) - { - childSm = QScxml::load (ievent->metaData.origin.resolved(ievent->metaData.target).toLocalFile(),this); - if (childSm == NULL) { - postParentEvent("error.targetunavailable"); - } else { - connect(childSm,SIGNAL(finished()),this,SLOT(deleteLater())); - - } - } - - - - static void initInvokerFactory(QScxml*) {} - - static bool isTypeSupported(const QString & t) { return t.isEmpty() || t.toLower() == "scxml"; } - - public Q_SLOTS: - void activate () - { - if (childSm) - childSm->start(); - } - - void cancel () - { - cancelled = true; - if (childSm) - childSm->stop(); - - } - - private: - bool cancelled; - QScxml* childSm; -}; -class QScxmlBindingInvoker : public QScxmlInvoker -{ - Q_OBJECT - QScriptValue content; - QScriptValue stored; - - public: - QScxmlBindingInvoker(QScxmlEvent* ievent, QScxml* p) : QScxmlInvoker(ievent,p) - { - } - - static void initInvokerFactory(QScxml*) {} - - static bool isTypeSupported(const QString & t) { return t.toLower() == "q-bindings"; } - - public Q_SLOTS: - void activate () - { - QScriptEngine* engine = ((QScxml*)parent())->scriptEngine(); - QScriptValue content = initEvent->content(); - if (content.isArray()) { - stored = content.engine()->newArray(content.property("length").toInt32()); - - QScriptValueIterator it (content); - for (int i=0; it.hasNext(); ++i) { - it.next(); - if (it.value().isArray()) { - QScriptValue object = it.value().property(0); - QString property = it.value().property(1).toString(); - QScriptValue val = it.value().property(2); - QScriptValue arr = engine->newArray(3); - arr.setProperty("0",it.value().property(0)); - arr.setProperty("1",it.value().property(1)); - if (object.isQObject()) { - QObject* o = object.toQObject(); - arr.setProperty("2",engine->newVariant(o->property(property.toAscii().constData()))); - o->setProperty(property.toAscii().constData(),val.toVariant()); - } else if (object.isObject()) { - arr.setProperty("2",object.property(property)); - object.setProperty(property,val); - } - stored.setProperty(i,arr); - } - } - } - } - - void cancel () - { - if (stored.isArray()) { - QScriptValueIterator it (stored); - while (it.hasNext()) { - it.next(); - if (it.value().isArray()) { - QScriptValue object = it.value().property(0); - QString property = it.value().property(1).toString(); - QScriptValue val = it.value().property(2); - if (object.isQObject()) { - QObject* o = object.toQObject(); - o->setProperty(property.toAscii().constData(),val.toVariant()); - } else if (object.isObject()) { - object.setProperty(property,val); - } - } - } - } - } -}; - - -/*! -\fn QScxmlInvoker::~QScxmlInvoker() -*/ - - -/*! -\fn QScxml::eventTriggered(const QString & name) - -This signal is emitted when external event \a name is handled in the state machine. -*/ - -void QScxml::init() -{ - static QScxmlAutoInvokerFactory<QScxmlDefaultInvoker> _s_defaultInvokerFactory; - static QScxmlAutoInvokerFactory<QScxmlBindingInvoker> _s_bindingInvokerFactory; - registerInvokerFactory(&_s_defaultInvokerFactory); - registerInvokerFactory(&_s_bindingInvokerFactory); - connect(this,SIGNAL(started()),this,SLOT(registerSession())); - connect(this,SIGNAL(stopped()),this,SLOT(unregisterSession())); - pvt->initScriptEngine(this); -#ifdef QT_GUI_LIB - static QScxmlAutoInvokerFactory<QScxmlMenuInvoker> _s_menuInvokerFactory; - static QScxmlAutoInvokerFactory<QScxmlMessageBoxInvoker> _s_msgboxInvokerFactory; - registerInvokerFactory(&_s_msgboxInvokerFactory); - registerInvokerFactory(&_s_menuInvokerFactory); -#endif -} -/*! - Creates a new QScxml object, with parent \a parent. - */ - -QScxml::QScxml(QObject* parent) - : QStateMachine(parent) -{ - pvt = new QScxmlPrivate; - pvt->scriptEng = new QScriptEngine(this); - init(); - -} -/*! - Creates a new QScxml object, with parent \a parent. The state machine will operate on script-engine \a eng. - */ - -QScxml::QScxml(QScriptEngine* eng, QObject* parent) - : QStateMachine(parent) -{ - pvt = new QScxmlPrivate; - pvt->scriptEng = eng; - init(); -} - -/*! \internal */ -void QScxml::beginSelectTransitions(QEvent* ev) -{ - QScriptValue eventObj = pvt->scriptEng->newObject(); - if (ev) { - if (ev->type() == QScxmlEvent::eventType()) { - QScxmlEvent* se = (QScxmlEvent*)ev; - eventObj.setProperty("name",qScriptValueFromValue<QString>(pvt->scriptEng,se->eventName())); - eventObj.setProperty("target",QScriptValue(se->metaData.target.toString())); - eventObj.setProperty("targettype",qScriptValueFromValue<QString>(pvt->scriptEng,se->metaData.targetType)); - eventObj.setProperty("invokeid",qScriptValueFromValue<QString>(pvt->scriptEng,se->metaData.invokeID)); - eventObj.setProperty("origin",QScriptValue(se->metaData.origin.toString())); - eventObj.setProperty("originType",qScriptValueFromValue<QString>(pvt->scriptEng,se->metaData.originType)); - switch (se->metaData.kind) { - case QScxmlEvent::MetaData::Internal: - eventObj.setProperty("kind",qScriptValueFromValue<QString>(pvt->scriptEng, "internal")); - break; - case QScxmlEvent::MetaData::External: - eventObj.setProperty("kind",qScriptValueFromValue<QString>(pvt->scriptEng, "external")); - break; - case QScxmlEvent::MetaData::Platform: - eventObj.setProperty("kind",qScriptValueFromValue<QString>(pvt->scriptEng, "platform")); - default: - break; - - } - - QScriptValue dataObj = pvt->scriptEng->newObject(); - int i=0; - foreach (QString s, se->paramNames()) { - QScriptValue v = qScriptValueFromValue(pvt->scriptEng, se->paramValues()[i]); - dataObj.setProperty(QString::number(i),v); - dataObj.setProperty(s,v); - ++i; - } - eventObj.setProperty("data",dataObj); - emit eventTriggered(se->eventName()); - } - } - scriptEngine()->globalObject().setProperty("_event",eventObj); - - QHash<QString,QAbstractState*> curTargets; - - for (int i = pvt->snapshotStack.size()-1; i >= 0 && curTargets.size() < pvt->anchorTransitions.keys().size(); --i) { - if (!curTargets.contains(pvt->snapshotStack.at(i).anchorType)) { - curTargets[pvt->snapshotStack.at(i).anchorType] = pvt->snapshotStack.at(i).state; - } - } - for (QMultiHash<QString,QAbstractTransition*>::const_iterator it = pvt->anchorTransitions.constBegin(); it != pvt->anchorTransitions.constEnd(); ++it) { - it.value()->setTargetState(curTargets[it.key()]); - } - -} - -static QString _q_configToString (QAbstractState* from,int level, const QSet<QAbstractState*> & config) -{ - QString str; - if (from) { - if (level >= 0) { - for (int i=0; i < level; ++i) - str += "\t"; - - QState* p = qobject_cast<QState*>(from->parent()); - char c = '$'; - if (qobject_cast<QHistoryState*>(from)) - c = '^'; - else if (qobject_cast<QFinalState*>(from)) - c = '~'; - else if (p) { - if (p->childMode() == QState::ParallelStates) - c = '{'; - } - str += QString("%1%2 %3\n").arg(config.contains(from)?">":" ").arg(c).arg(from->objectName()); - } - QObjectList ch = from->children(); - foreach (QObject* o, ch) - str += _q_configToString(qobject_cast<QAbstractState*>(o),level+1,config); - } - - return str; -} - -/*! \internal */ - - -void QScxml::endMicrostep(QEvent*) -{ - scriptEngine()->globalObject().setProperty("_event",QScriptValue()); - for (QHash<QString,QScxmlPrivate::AnchorSnapshot>::iterator - it = pvt->curSnapshot.begin(); - it != pvt->curSnapshot.end(); ++it) { - - pvt->snapshotStack.push(it.value()); - - } - if (pvt->snapshotStack.size() > QScxmlPrivate::MaxSnapshots) { - pvt->snapshotStack.remove(0,pvt->snapshotStack.size()-100); - } - pvt->curSnapshot.clear(); - /* - if (e->type() == QScxmlEvent::eventType()) { - qDebug() << "\n" + _q_configToString(rootState(),-1,configuration()); - } - */ -} - -/*! Returns the script engine attached to the state-machine. */ -QScriptEngine* QScxml::scriptEngine () const -{ - return pvt->scriptEng; -} - -/*! - Registers object \a o to the script engine attached to the state machine. - The object can be accessible from global variable \a name. If \a name is not provided, - the object's name is used. If \a recursive is true, all the object's decendants are registered - as global objects, with their respective object names as variable names. -*/ -void QScxml::registerObject (QObject* o, const QString & name, bool recursive) -{ - QString n(name); - if (n.isEmpty()) - n = o->objectName(); - if (!n.isEmpty()) - pvt->scriptEng->globalObject().setProperty(n,pvt->scriptEng->newQObject(o)); - if (recursive) { - QObjectList ol = o->findChildren<QObject*>(); - foreach (QObject* oo, ol) { - if (!oo->objectName().isEmpty()) - registerObject(oo); - } - } -} - -/*! - Posts a QScxmlEvent named \a event, with no payload. - \sa QScxmlEvent - */ -void QScxml::postNamedEvent(const QString & event) -{ - QScxmlEvent* e = new QScxmlEvent(event); - e->metaData.kind = QScxmlEvent::MetaData::External; - postEvent(e); -} -/*! - Executes script \a s in the attached script engine. - If the script fails, a "error.illegalvalue" event is posted to the state machine. -*/ - -void QScxml::executeScript (const QString & s) -{ -// qDebug() << "Executing\n--------------------------\n"<<s; - pvt->scriptEng->evaluate (s,baseUrl().toLocalFile()); - if (pvt->scriptEng->hasUncaughtException()) { - QScxmlEvent* e = new QScxmlEvent("error.illegalvalue", - QStringList()<< "error" << "expr" << "line" << "backtrace", - QVariantList() - << QVariant(pvt->scriptEng->uncaughtException().toString()) - << QVariant(s) - << QVariant(pvt->scriptEng->uncaughtExceptionLineNumber()) - << QVariant(pvt->scriptEng->uncaughtExceptionBacktrace())); - e->metaData.kind = QScxmlEvent::MetaData::Platform; - qDebug() << pvt->scriptEng->uncaughtException().toString(); - postEvent(e); - pvt->scriptEng->clearExceptions(); - } -// qDebug() <<"\n--------------------\n"; -} - -/*! - Enabled invoker factory \a f to be called from <invoke /> tags. - */ - -void QScxml::registerInvokerFactory (QScxmlInvokerFactory* f) -{ - pvt->invokerFactories << f; - f->init(this); -} - -/*! \class QScxmlInvoker - \brief The QScxmlInvoker class an invoker, which the state-machine context can activate or cancel - with an <invoke> tag. - - - An invoker is a object that represents an external component that the state machine - can activate when the encompassing state is entered, or cancel when the encompassing - state is exited from. - */ - -/*! \fn QScxmlInvoker::QScxmlInvoker(QScxmlEvent* ievent, QStateMachine* parent) - When reimplementing the constructor, always use the two parameters (\a ievent and \a parent), - as they're called from QScxmlInvokerFactory. -*/ - -/*! \fn QScxmlInvoker::activate() - This function is called when the encompassing state is entered. - The call to this function from the state-machine context is asynchronous, to make sure - that the state is not exited during the same step in which it's entered. - -*/ - -/*! \fn QScxmlInvoker::cancel() - Reimplement this function to allow for asynchronous cancellation of the invoker. - It's the invoker's responsibility to delete itself after this function has been called. - The default implementation deletes the invoker. -*/ - -/*! \fn QScxml* QScxmlInvoker::parentStateMachine() - Returns the state machine encompassing the invoker. - */ - -/*! - Posts an event \a e to the state machine encompassing the invoker. - */ -void QScxmlInvoker::postParentEvent (QScxmlEvent* e) -{ - e->metaData.origin = initEvent->metaData.target; - e->metaData.target = initEvent->metaData.origin; - e->metaData.originType = initEvent->metaData.targetType; - e->metaData.targetType = initEvent->metaData.originType; - e->metaData.kind = QScxmlEvent::MetaData::External; - e->metaData.invokeID = initEvent->metaData.invokeID; - parentStateMachine()->postEvent(e); -} -/*! \overload - Posts a QScxmlEvent named \a e to the encompassing state machine. - */ -void QScxmlInvoker::postParentEvent(const QString & e) -{ - QScxmlEvent* ev = new QScxmlEvent(e); - ev->metaData.kind = QScxmlEvent::MetaData::External; - postParentEvent(ev); -} -/*! \internal */ -QScxml::~QScxml() -{ - delete pvt; -} -/*! -returns the id for this invoker -*/ -QString QScxmlInvoker::id () const -{ - return initEvent->metaData.invokeID; -} -void QScxmlInvoker::setID(const QString & id) -{ - initEvent->metaData.invokeID = id; -} - -QScxmlInvoker::~QScxmlInvoker() -{ - if (cancelled) - postParentEvent("CancelResponse"); - else - postParentEvent(QString("done.invoke.%1").arg(initEvent->metaData.invokeID)); -} -/*! - \property QScxml::baseUrl - The url used to resolve scripts and invoke urls. -*/ -QUrl QScxml::baseUrl() const -{ - return pvt->burl; -} - -void QScxml::setBaseUrl(const QUrl & u) -{ - pvt->burl = u; -} - -void QScxml::registerSession() -{ - pvt->sessionID = QUuid::createUuid().toString(); - pvt->sessions[pvt->sessionID] = this; - pvt->scriptEng->globalObject().setProperty("_sessionid",qScriptValueFromValue<QString>(scriptEngine(), pvt->sessionID)); - executeScript(pvt->startScript); -} - -void QScxml::unregisterSession() -{ - pvt->scriptEng->globalObject().setProperty("_sessionid",QScriptValue()); - pvt->sessions.remove(pvt->sessionID); -} - -/*! - Returns a statically-generated event type to be used by SCXML events. -*/ -QEvent::Type QScxmlEvent::eventType() -{ - static QEvent::Type _t = (QEvent::Type)QEvent::registerEventType(QEvent::User+200); - return _t; -} -const char SCXML_NAMESPACE [] = "http://www.w3.org/2005/07/scxml"; - - - -struct ScTransitionInfo -{ - - QScxmlTransition* transition; - QStringList targets; - QString anchor; - QString script; - ScTransitionInfo() : transition(NULL) {} -}; - -class QScxmlScriptExec : public QObject -{ - Q_OBJECT - QString script; - QScxml* scxml; - public: - QScxmlScriptExec(const QString & scr, QScxml* scx) : script(scr),scxml(scx) - { - } - public Q_SLOTS: - void exec() - { - scxml->executeScript(script); - } -}; - -struct ScStateInfo -{ - QString initial; -}; - -struct ScHistoryInfo -{ - QHistoryState* hstate; - QString defaultStateID; -}; - -struct ScExecContext -{ - QScxml* sm; - QString script; - enum {None, StateEntry,StateExit,Transition } type; - QScxmlTransition* trans; - QAbstractState* state; - ScExecContext() : sm(NULL),type(None),trans(NULL),state(NULL) - { - } - - void applyScript() - { - if (!script.isEmpty()) { - QScxmlScriptExec* exec = new QScxmlScriptExec(script,sm); - switch(type) { - case StateEntry: - QObject::connect(state,SIGNAL(entered()),exec,SLOT(exec())); - break; - case StateExit: - QObject::connect(state,SIGNAL(exited()),exec,SLOT(exec())); - break; - case Transition: - QObject::connect(trans,SIGNAL(triggered()),exec,SLOT(exec())); - break; - default: - delete exec; - break; - } - } - } -}; - -class QScxmlLoader -{ - public: - QScxml* stateMachine; - - QList<ScTransitionInfo> transitions; - QHash<QState*,ScStateInfo> stateInfo; - QList<ScHistoryInfo> historyInfo; - QHash<QString,QAbstractState*> stateByID; - QSet<QString> signalEvents; - QSet<QState*> statesWithFinal; - void loadState (QState* state, QIODevice* dev, const QString & stateID,const QString & filename); - QScxml* load (QIODevice* device, QObject* obj = NULL, const QString & filename = ""); - - QScriptValue evaluateFile (const QString & fn) - { - QFile f (fn); - f.open(QIODevice::ReadOnly); - return stateMachine->scriptEngine()->evaluate(QString::fromUtf8(f.readAll()),fn); - } -}; - -class QScxmlAnchorSave : public QObject -{ - Q_OBJECT - public: - QScxml* sm; - QScxmlPrivate* pvt; - QScxmlPrivate::AnchorSnapshot anchorSnapshot; - QScxmlAnchorSave(QScxml* p,QScxmlPrivate* pv, - const QString & type, const QString & loc, - QAbstractState* s) : - QObject(p),sm(p),pvt(pv) - { - anchorSnapshot.anchorType = type; - anchorSnapshot.location = loc; - anchorSnapshot.state = s; - } - - public Q_SLOTS: - - void save() - { - if (!anchorSnapshot.location.isEmpty()) { - anchorSnapshot.snapshot = _q_deepCopy(sm->scriptEngine()->evaluate(anchorSnapshot.location)); - } - pvt->curSnapshot[anchorSnapshot.anchorType] = anchorSnapshot; - } -}; - -class QScxmlAnchorRestore : public QObject -{ - Q_OBJECT - public: - QScxml* sm; - QScxmlPrivate* pvt; - QString anchorType; - QScxmlAnchorRestore(QScxml* p,QScxmlPrivate* pv, - const QString & type) : - QObject(p),sm(p),pvt(pv),anchorType(type) - { - - } - - public Q_SLOTS: - void restore () - { - pvt->curSnapshot.clear(); - while (!pvt->snapshotStack.isEmpty()) { - QScxmlPrivate::AnchorSnapshot s = pvt->snapshotStack.pop(); - if (s.anchorType == anchorType) { - if (s.location != "") { - sm->scriptEngine()->globalObject().setProperty("_snapshot",s.snapshot); - sm->scriptEngine()->evaluate(QString ("%1 = _snapshot;").arg(s.location)); - sm->scriptEngine()->globalObject().setProperty("_snapshot",QScriptValue()); - } - break; - } - } - } -}; - -static QString sanitize (const QString & str) -{ - return str; -// return QString("eval(unescape(\"%1\"))"). -// arg(QString::fromAscii(str.trimmed().toUtf8().toPercentEncoding(QByteArray("[]()<>;:#/'`_-., \t@!^&*{}")))); -} -static QString sanitize (const QStringRef & str) -{ - return sanitize(str.toString()); -} - -void QScxmlLoader::loadState ( - QState* stateParam, - QIODevice *dev, - const QString & stateID, - const QString & filename) -{ - QXmlStreamReader r (dev); - QState* curState = NULL; - ScExecContext curExecContext; - curExecContext.sm = stateMachine; - QState* topLevelState = NULL; - QHistoryState* curHistoryState = NULL; - QString initialID = ""; - QString idLocation, target, targetType, eventName, delay, content; - QStringList paramNames, paramVals; - QScxmlTransition* curTransition = NULL; - bool inRoot = true; - while (!r.atEnd()) { - r.readNext(); - if (r.hasError()) { - qDebug() << QString("SCXML read error at line %1, column %2: %3").arg(r.lineNumber()).arg(r. columnNumber()).arg(r.errorString()); - return; - } - if (r.namespaceUri() == SCXML_NAMESPACE || r.namespaceUri() == "") { - if (r.isStartElement()) { - if (r.name().toString().compare("scxml",Qt::CaseInsensitive) == 0) { - if (stateID == "") { - topLevelState = curState = stateParam; - stateInfo[curState].initial = r.attributes().value("initial").toString(); - if (curState == stateMachine) { - stateMachine->scriptEngine()->globalObject().setProperty("_name",qScriptValueFromValue<QString>(stateMachine->scriptEngine(),r.attributes().value("name").toString())); - } - - } - } else if (r.name().toString().compare("state",Qt::CaseInsensitive) == 0 || r.name().toString().compare("parallel",Qt::CaseInsensitive) == 0) { - inRoot = false; - QString id = r.attributes().value("id").toString(); - QState* newState = NULL; - if (curState) { - newState= new QState(r.name().toString().compare("parallel",Qt::CaseInsensitive) == 0 ? QState::ParallelStates : QState::ExclusiveStates, - curState); - } else if (id == stateID) { - topLevelState = newState = stateParam; - - } - if (newState) { - stateInfo[newState].initial = r.attributes().value("initial").toString(); - newState->setObjectName(id); - if (!id.isEmpty() && stateInfo[curState].initial == id) { - - if (curState == stateMachine) - stateMachine->setInitialState(newState); - else - curState->setInitialState(newState); - } - QString src = r.attributes().value("src").toString(); - if (!src.isEmpty()) { - int refidx = src.indexOf('#'); - QString srcfile, refid; - if (refidx > 0) { - srcfile = src.left(refidx); - refid = src.mid(refidx+1); - } else - srcfile = src; - srcfile = QDir::cleanPath( QFileInfo(filename).dir().absoluteFilePath(srcfile)); - QFile newFile (srcfile); - if (newFile.exists()) { - newFile.open(QIODevice::ReadOnly); - loadState(newState,&newFile,refid,srcfile); - } - } - initialID = r.attributes().value("initial").toString(); - stateByID[id] = newState; - curState = newState; - curExecContext.state = newState; - } - - } else if (r.name().toString().compare("initial",Qt::CaseInsensitive) == 0) { - if (curState && stateInfo[curState].initial == "") { - QState* newState = new QState(curState); - curState->setInitialState(newState); - } - } else if (r.name().toString().compare("history",Qt::CaseInsensitive) == 0) { - if (curState) { - QString id = r.attributes().value("id").toString(); - curHistoryState = new QHistoryState(r.attributes().value("type") == "shallow" ? QHistoryState::ShallowHistory : QHistoryState::DeepHistory,curState); - curHistoryState->setObjectName(id); - stateByID[id] = curHistoryState; - } - } else if (r.name().toString().compare("final",Qt::CaseInsensitive) == 0) { - if (curState) { - QString id = r.attributes().value("id").toString(); - QFinalState* f = new QFinalState(curState); - f->setObjectName(id); - curExecContext.state = f; - statesWithFinal.insert(curState); - QState* gp = qobject_cast<QState*>(curState->parentState()); - if (gp) { - if (gp->childMode() == QState::ParallelStates) { - statesWithFinal.insert(gp); - } - } - stateByID[id] = f; - } - } else if (r.name().toString().compare("script",Qt::CaseInsensitive) == 0) { - QString txt = r.readElementText().trimmed(); - if (curExecContext.type == ScExecContext::None && curState == topLevelState) { - stateMachine->executeScript(txt); - } else - curExecContext.script += txt; - } else if (r.name().toString().compare("log",Qt::CaseInsensitive) == 0) { - curExecContext.script += - QString("scxml.print('[' + %1 + '][' + %2 + ']' + %3);") - .arg(sanitize(r.attributes().value("label"))) - .arg(sanitize(r.attributes().value("level"))) - .arg(sanitize(r.attributes().value("expr"))); - - } else if (r.name().toString().compare("assign",Qt::CaseInsensitive) == 0) { - QString locattr = r.attributes().value("location").toString(); - if (locattr.isEmpty()) { - locattr = r.attributes().value("dataid").toString(); - if (!locattr.isEmpty()) - locattr = "_data." + locattr; - } - if (!locattr.isEmpty()) { - curExecContext.script += QString ("%1 = %2;").arg(locattr).arg(sanitize(r.attributes().value("expr"))); - } - } else if (r.name().toString().compare("if",Qt::CaseInsensitive) == 0) { - curExecContext.script += QString("if (%1) {").arg(sanitize(r.attributes().value("cond"))); - } else if (r.name().toString().compare("elseif",Qt::CaseInsensitive) == 0) { - curExecContext.script += QString("} elseif (%1) {").arg(sanitize(r.attributes().value("cond"))); - } else if (r.name().toString().compare("else",Qt::CaseInsensitive) == 0) { - curExecContext.script += " } else { "; - } else if (r.name().toString().compare("cancel",Qt::CaseInsensitive) == 0) { - curExecContext.script += QString("scxml.clearTimeout (%1);").arg(sanitize(r.attributes().value("id"))); - } else if (r.name().toString().compare("onentry",Qt::CaseInsensitive) == 0) { - curExecContext.type = ScExecContext::StateEntry; - curExecContext.script = ""; - } else if (r.name().toString().compare("onexit",Qt::CaseInsensitive) == 0) { - curExecContext.type = ScExecContext::StateExit; - curExecContext.script = ""; - } else if (r.name().toString().compare("raise",Qt::CaseInsensitive) == 0 || r.name().toString().compare("event",Qt::CaseInsensitive) == 0 ) { - eventName = QString("\"%1\"").arg(r.attributes().value("event").toString()); - target = "'_internal'"; - targetType = "scxml"; - content = "{}"; - paramNames.clear(); - paramVals.clear(); - } else if (r.name().toString().compare("send",Qt::CaseInsensitive) == 0) { - paramNames.clear (); - paramVals.clear(); - content = "{}"; - - target = r.attributes().value("target").toString(); - if (target == "") - target = "\"\""; - targetType = r.attributes().value("type").toString(); - eventName = r.attributes().value("event").toString(); - QStringList nameList = r.attributes().value("namelist").toString().split(" "); - foreach (QString name,nameList) { - if (name != "") { - paramNames << name; - paramVals << QString("_data.") + name; - } - } - idLocation = r.attributes().value("idlocation").toString(); - if (idLocation.isEmpty()) - idLocation = r.attributes().value("sendid").toString(); - - delay = r.attributes().value("delay").toString(); - if (delay == "") - delay = "0"; - else - delay = QString("scxml.cssTime(%1)").arg(delay); - - } else if (r.name().toString().compare("invoke",Qt::CaseInsensitive) == 0) { - idLocation = r.attributes().value("idlocation").toString(); - if (idLocation.isEmpty()) - idLocation = r.attributes().value("invokeid").toString(); - QObject::connect (curState, SIGNAL(exited()),new QScxmlScriptExec(QString("_data.invoke_%1.cancel();").arg(curState->objectName()),stateMachine),SLOT(exec())); - - QString type = r.attributes().value("type").toString(); - if (type.isEmpty()) - type = "scxml"; - curExecContext.type = ScExecContext::StateEntry; - curExecContext.state = curState; - paramNames.clear (); - paramVals.clear (); - content = "{}"; - target = r.attributes().value("src").toString(); - if (target == "") - target = "\"\""; - targetType = r.attributes().value("type").toString(); - } else if (r.name().toString().compare("transition",Qt::CaseInsensitive) == 0) { - if (curHistoryState) { - ScHistoryInfo inf; - inf.hstate = curHistoryState; - inf.defaultStateID = r.attributes().value("target").toString(); - historyInfo.append(inf); - } else { - ScTransitionInfo inf; - inf.targets = r.attributes().value("target").toString().split(' '); - curExecContext.type = ScExecContext::Transition; - curExecContext.script = ""; - curTransition = new QScxmlTransition(curState,stateMachine); - curTransition->setConditionExpression(r.attributes().value("cond").toString()); - curTransition->setEventPrefix(r.attributes().value("event").toString()); - curExecContext.trans = curTransition; - QString anc = r.attributes().value("anchor").toString(); - if (!anc.isEmpty()) { - stateMachine->pvt->anchorTransitions.insert(anc,curTransition); - QObject::connect (curTransition, SIGNAL(triggered()),new QScxmlAnchorRestore(stateMachine,stateMachine->pvt,anc),SLOT(restore())); - } - inf.transition = curTransition; - transitions.append(inf); - if (curTransition->eventPrefix().startsWith("q-signal:")) { - signalEvents.insert(curTransition->eventPrefix()); - } - curTransition->setObjectName(QString ("%1 to %2 on %3 if %4 (anchor=%5)").arg(curState->objectName()).arg(inf.targets.join(" ")).arg(curTransition->eventPrefix()).arg(curTransition->conditionExpression()).arg(anc)); - } - } else if (r.name().toString().compare("anchor",Qt::CaseInsensitive) == 0) { - QObject::connect(curState,SIGNAL(exited()),new QScxmlAnchorSave(stateMachine,stateMachine->pvt,r.attributes().value("type").toString(),r.attributes().value("snapshot").toString(),curState),SLOT(save())); - } else if (r.name().toString().compare("data",Qt::CaseInsensitive) == 0) { - QScriptValue val = qScriptValueFromValue<QString>(stateMachine->scriptEngine(),"") ; - QString id = r.attributes().value("id").toString(); - if (r.attributes().value("src").length()) - val = evaluateFile(QFileInfo(filename).dir().absoluteFilePath(r.attributes().value("src").toString())); - else { - if (r.attributes().value("expr").length()) { - val = stateMachine->scriptEngine()->evaluate(r.attributes().value("expr").toString()); - } else { - QString t = r.readElementText(); - if (!t.isEmpty()) - val = stateMachine->scriptEngine()->evaluate(t); - } - } - stateMachine->scriptEngine()->evaluate("_data") - .setProperty(id,val); - } else if (r.name().toString().compare("param",Qt::CaseInsensitive) == 0) { - paramNames << r.attributes().value("name").toString(); - paramVals << r.attributes().value("expr").toString(); - } else if (r.name().toString().compare("content",Qt::CaseInsensitive) == 0) { - content = r.readElementText(); - } - } else if (r.isEndElement()) { - if (r.name().toString().compare("state",Qt::CaseInsensitive) == 0 || r.name().toString().compare("parallel",Qt::CaseInsensitive) == 0) { - if (curState == topLevelState) { - return; - } else { - curState = qobject_cast<QState*>(curState->parent()); - curExecContext.state = curState; - } - } else if (r.name().toString().compare("history",Qt::CaseInsensitive) == 0) { - curHistoryState = NULL; - } else if (r.name().toString().compare("final",Qt::CaseInsensitive) == 0) { - curExecContext.state = (curExecContext.state->parentState()); - } else if (r.name().toString().compare("if",Qt::CaseInsensitive) == 0) { - curExecContext.script += "}\n"; - } else if (r.name().toString().compare("send",Qt::CaseInsensitive) == 0 || r.name().toString().compare("raise",Qt::CaseInsensitive) == 0) { - if (!idLocation.isEmpty()) - curExecContext.script += idLocation + " = "; - QString pnames; - bool first = true; - foreach (QString n, paramNames) { - if (!first) - pnames +=","; - pnames += QString("\"%1\"").arg(n); - first = false; - } - QString innerScript = QString("scxml.postEvent(%1,%2,\"%3\",[%4],[%5],%6);") - .arg(eventName).arg(target).arg(targetType) - .arg(pnames).arg(paramVals.join(",")).arg(content); - if (target == "'_internal'") - curExecContext.script += innerScript; - else - curExecContext.script += QString("scxml.setTimeout(function() {%1}, %2);") - .arg(innerScript).arg(delay); - idLocation = ""; - } else if ( - r.name().toString().compare("onentry",Qt::CaseInsensitive) == 0 - || r.name().toString().compare("onexit",Qt::CaseInsensitive) == 0 - || r.name().toString().compare("scxml",Qt::CaseInsensitive) == 0) { - curExecContext.state = curState; - curExecContext.type = r.name().toString().compare("onexit",Qt::CaseInsensitive)==0 ? ScExecContext::StateExit : ScExecContext::StateEntry; - curExecContext.applyScript(); - curExecContext.type = ScExecContext::None; - } else if (r.name().toString().compare("transition",Qt::CaseInsensitive) == 0) { - if (!curHistoryState) { - curExecContext.trans = curTransition; - curExecContext.type = ScExecContext::Transition; - curExecContext.applyScript(); - } - - ScTransitionInfo* ti = &(transitions.last()); - if (!curExecContext.script.isEmpty() && ti->anchor != "") - ti->script = curExecContext.script; - curExecContext.type = ScExecContext::None; - } else if (r.name().toString().compare("invoke",Qt::CaseInsensitive) == 0) { - QString pnames; - bool first = true; - foreach (QString n, paramNames) { - if (!first) - pnames +=","; - pnames += QString("\"%1\"").arg(n); - first = false; - } - curExecContext.script += QString("_data.invoke_%1 = scxml.invoke(\"%2\",%3,[%4],[%5],%6); _data.invoke_%1.id = \"%1\";").arg(curState->objectName()).arg(targetType).arg(target).arg(pnames).arg(paramVals.join(",")).arg(content); - if (!idLocation.isEmpty()) { - curExecContext.script += QString("%1 = _data.invoke_%2;").arg(idLocation).arg(curState->objectName()); - } - curExecContext.state = curState; - curExecContext.type = ScExecContext::StateEntry; - curExecContext.applyScript(); - idLocation = ""; - curExecContext.type = ScExecContext::None; - } - } - } - } -} - - -QScxml* QScxmlLoader::load(QIODevice* device, QObject* obj, const QString & filename) -{ - if (device->bytesAvailable() == 0) { - qWarning() << QString("File %1 invalid or not found").arg(filename); - return NULL; - } - stateMachine = new QScxml(obj); - // traverse through the states - loadState(stateMachine,device,"",filename); - - // resolve history default state - foreach (ScHistoryInfo h, historyInfo) { - h.hstate->setDefaultState(stateByID[h.defaultStateID]); - } - foreach (QString s, signalEvents) { - QString sig = s; - sig = sig.mid(sig.indexOf(':')+1); -// sig = sig.left(sig.indexOf('(')); - int liop = sig.lastIndexOf('.'); - QString obj = sig.left(liop); - sig = sig.mid(liop+1); - stateMachine->pvt->startScript += QString("scxml.connectSignalToEvent(%1,'%2',\"%3\");").arg(obj).arg(sig).arg(s); - -// QString scr = QString("%1.connect({e:\"%2\"},_rcvSig);\n").arg(sig).arg(s); -/// stateMachine->pvt->startScript += scr; - } - - foreach (QState* s, statesWithFinal) { - QObject::connect(s,SIGNAL(finished()),stateMachine,SLOT(handleStateFinished())); - } - - // resolve transitions - - foreach (ScTransitionInfo t, transitions) { - QList<QAbstractState*> states; - if (!t.targets.isEmpty()) { - foreach (QString s, t.targets) { - if (!s.trimmed().isEmpty()) { - QAbstractState* st = stateByID[s]; - if (st) - states.append(st); - } - } - t.transition->setTargetStates(states); - } - } - - return stateMachine; -} - -void QScxml::handleStateFinished() -{ - QState* state = qobject_cast<QState*>(sender()); - if (state) { - postEvent(new QScxmlEvent("done.state." + state->objectName())); - } -} - -/*! - Loads a state machine from an scxml file located at \a filename, with parent object \a o. - */ -QScxml* QScxml::load (const QString & filename, QObject* o) -{ - QScxmlLoader l; - QFile f (filename); - f.open(QIODevice::ReadOnly); - return l.load(&f,o,filename); -} - -#include "qscxml.moc" -#endif diff --git a/src/qscxml.h b/src/qscxml.h deleted file mode 100644 index fc6b590..0000000 --- a/src/qscxml.h +++ /dev/null @@ -1,170 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ - -#ifndef QSCXML_H -#define QSCXML_H -#ifndef QT_NO_STATEMACHINE - -#include <QStateMachine> -#include <QAbstractTransition> -#include <QVariant> -#include <QEvent> -#include <QStringList> -#include <QScriptValue> -#include <QUrl> - -class QScriptEngine; -class QScxml; - -class QScxmlEvent : public QEvent -{ - public: - static QEvent::Type eventType(); - QString eventName() const; - QStringList paramNames () const; - QVariantList paramValues () const; - QScriptValue content () const; - QVariant param (const QString & name) const; - QScxmlEvent ( - const QString & name, - const QStringList & paramNames = QStringList(), - const QVariantList & paramValues = QVariantList(), - const QScriptValue & content = QScriptValue()); - - struct MetaData - { - QUrl origin,target; - QString originType, targetType; - QString invokeID; - enum Kind { Platform, Internal, External } kind; - }; - - MetaData metaData; - - private: - QString ename; - QStringList pnames; - QVariantList pvals; - QScriptValue cnt; -}; - - -class QScxmlTransition : public QAbstractTransition -{ - Q_OBJECT - Q_PROPERTY(QString conditionExpression READ conditionExpression WRITE setConditionExpression) - Q_PROPERTY(QString eventPrefix READ eventPrefix WRITE setEventPrefix) - - public: - QScxmlTransition (QState* state, QScxml* machine); - - QString conditionExpression () const { return cond; } - void setConditionExpression (const QString & c) { cond = c; } - QString eventPrefix () const { return ev; } - void setEventPrefix (const QString & e) { ev = e; } - - protected: - bool eventTest(QEvent*); - void onTransition (QEvent*); - private: - QScxml* scxml; - QString ev,cond; -}; - -class QScxmlInvoker : public QObject -{ - Q_OBJECT - Q_PROPERTY (QString id READ id WRITE setID) - - protected: - QScxmlInvoker(QScxmlEvent* ievent, QStateMachine* p) : QObject(p), initEvent(ievent),cancelled(false) {} - - public: - virtual ~QScxmlInvoker(); - QString id () const; - void setID(const QString &); - - public Q_SLOTS: - virtual void activate() = 0; - virtual void cancel() { deleteLater(); } - - protected Q_SLOTS: - void postParentEvent (const QString & event); - - protected: - QScxml* parentStateMachine() { return (QScxml*)parent(); } - void postParentEvent (QScxmlEvent* ev); - QScxmlEvent* initEvent; - bool cancelled; - - friend struct QScxmlFunctions; -}; - -struct QScxmlInvokerFactory -{ - virtual QScxmlInvoker* createInvoker (QScxmlEvent* event, QScxml* stateMachine) = 0; - virtual bool isTypeSupported (const QString & type) const = 0; - virtual void init (QScxml*) = 0; -}; - -template <class T> -class QScxmlAutoInvokerFactory : public QScxmlInvokerFactory -{ - QScxmlInvoker* createInvoker (QScxmlEvent* _e, QScxml* _sm) { return new T(_e,_sm); } - bool isTypeSupported(const QString & _s) const { return T::isTypeSupported(_s); } - void init (QScxml* sm) { T::initInvokerFactory(sm); } -}; - - -class QScxml : public QStateMachine -{ - Q_OBJECT - - Q_PROPERTY(QUrl baseUrl READ baseUrl WRITE setBaseUrl) - - - public: - QScxml(QScriptEngine* engine, QObject* o = NULL); - QScxml(QObject* o = NULL); - virtual ~QScxml(); - protected: - // overloaded to store the event for the script environment's use (_event), and to convert - // StateFinished events to "done." named events - virtual void beginSelectTransitions(QEvent*); - virtual void endMicrostep(QEvent*); - - public: - QScriptEngine* scriptEngine () const; - void registerObject (QObject* object, const QString & name = QString(), bool recursive = false); - void registerInvokerFactory (QScxmlInvokerFactory* f); - void setBaseUrl (const QUrl &); - QUrl baseUrl () const; - static QScxml* load (const QString & filename, QObject* o = NULL); - - public Q_SLOTS: - void postNamedEvent(const QString &); - void executeScript (const QString &); - - private Q_SLOTS: - void registerSession(); - void unregisterSession(); - void handleStateFinished(); - - Q_SIGNALS: - void eventTriggered(const QString &); - - private: - class QScxmlPrivate* pvt; - friend class QScxmlLoader; - friend struct QScxmlFunctions; - void init(); -}; -#endif -#endif // QSCXML_H diff --git a/src/qscxml.pri b/src/qscxml.pri deleted file mode 100644 index 873c038..0000000 --- a/src/qscxml.pri +++ /dev/null @@ -1,7 +0,0 @@ -QT += script -SOURCES += $$PWD/qscxml.cpp \ - $$PWD/qscxmlgui.cpp - -HEADERS += $$PWD/qscxml.h \ - $$PWD/qscxmlgui.h -INCLUDEPATH += $$PWD
\ No newline at end of file diff --git a/src/qscxmlgui.cpp b/src/qscxmlgui.cpp deleted file mode 100644 index cb6745f..0000000 --- a/src/qscxmlgui.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ - -#include "qscxmlgui.h" -#include <QMenu> -#include <QDebug> -#include <QMessageBox> -#include <QScriptValueIterator> -#include <QScriptEngine> -#include <QSignalMapper> -/* - - { "parent" : parentObject, - "trackHovers" : true/false - "children": {{"type": "action", "text": "",}, - {"type": "menu"}, - {"type": "separator"} }, - */ -namespace -{ - void traverseMenu (QMenu* menu, QScriptValue value, QSignalMapper* clickMap, QSignalMapper* hoverMap, bool trackHover) - { - QScriptValueIterator it (value); - while (it.hasNext()) { - it.next(); - if (it.name() == "trackHover") { - trackHover = it.value().toBoolean(); - } else if (it.name() == "parent") { - } else if (it.name() == "children") { - QScriptValueIterator cit (it.value()); - while (cit.hasNext()) { - cit.next(); - QString type = cit.value().property("type").toString(); - if (type == "action") { - QAction* act = menu->addAction(""); - QScriptValueIterator ait (cit.value()); - while (ait.hasNext()) { - ait.next(); - if (ait.name() != "type") { - act->setProperty(ait.name().toAscii().constData(),ait.value().toVariant()); - } - } - QObject::connect(act,SIGNAL(triggered()),clickMap,SLOT(map())); - clickMap->setMapping(act,QString("menu.action." + cit.value().property("id").toString())); - if (trackHover) { - QObject::connect(act,SIGNAL(hovered()),hoverMap,SLOT(map())); - hoverMap->setMapping(act,QString("menu.hover." + cit.value().property("id").toString())); - } - } else if (type == "menu") { - traverseMenu(menu->addMenu(""),it.value(),clickMap,hoverMap,trackHover); - } else if (type == "separator") { - menu->addSeparator(); - } - } - } else { - menu->setProperty(it.name().toAscii().constData(),it.value().toVariant()); - } - } - } -}; - -void QScxmlMenuInvoker::activate () -{ - QScxmlEvent* ie = initEvent; - QScriptValue v = ie->content(); - QWidget* parent = qobject_cast<QWidget*>(v.property("parent").toQObject()); - menu = new QMenu(parent); - QSignalMapper* clickMap = new QSignalMapper(this); - QSignalMapper* hoverMap = new QSignalMapper(this); - connect (clickMap,SIGNAL(mapped(QString)), this, SLOT(postParentEvent(QString))); - connect (hoverMap,SIGNAL(mapped(QString)), this, SLOT(postParentEvent(QString))); - traverseMenu(menu,v,clickMap,hoverMap,false); - menu->setParent(parent,Qt::Widget); - menu->move(QPoint(0,0)); - menu->resize(parent->size()); - menu->show(); -} -void QScxmlMenuInvoker::cancel () -{ - if (menu) - menu->deleteLater(); - QScxmlInvoker::cancel(); -} - -Q_SCRIPT_DECLARE_QMETAOBJECT(QMenu,QWidget*) -Q_SCRIPT_DECLARE_QMETAOBJECT(QMessageBox,QWidget*) - void QScxmlMenuInvoker::initInvokerFactory(QScxml* sm) - { - QScriptEngine* se = sm->scriptEngine(); - se->globalObject().setProperty("QMenu",qScriptValueFromQMetaObject<QMenu>(se)); - } - void QScxmlMessageBoxInvoker::initInvokerFactory(QScxml* sm) - { - QScriptEngine* se = sm->scriptEngine(); - se->globalObject().setProperty("QMessageBox",qScriptValueFromQMetaObject<QMessageBox>(se)); - } - -void QScxmlMessageBoxInvoker::onFinished(int n) { - postParentEvent(new QScxmlEvent("q-messagebox.finished",QStringList()<<"result",QVariantList()<<QVariant(n))); -} -/* - { "parent": someWidget, "buttons": ...} - */ -void QScxmlMessageBoxInvoker::activate() -{ - QScriptValue v = initEvent->content(); - QWidget* parent = qobject_cast<QWidget*>(v.property("parent").toQObject()); - messageBox = new QMessageBox(parent); - messageBox->setModal(false); - QScriptValueIterator it (v); - while (it.hasNext()) { - it.next(); - if (it.name() == "standardButtons") { - messageBox->setStandardButtons((QMessageBox::StandardButtons)it.value().toInt32()); - } else if (it.name() == "icon") { - messageBox->setIcon((QMessageBox::Icon)it.value().toInt32()); - } else if (it.name() != "parent") { - messageBox->setProperty(it.name().toAscii().constData(),it.value().toVariant()); - } - } - connect(messageBox,SIGNAL(finished(int)),this,SLOT(onFinished(int))); - messageBox->show (); -} - -void QScxmlMessageBoxInvoker::cancel() -{ - messageBox->deleteLater(); - QScxmlInvoker::cancel(); -} diff --git a/src/qscxmlgui.h b/src/qscxmlgui.h deleted file mode 100644 index ad5744c..0000000 --- a/src/qscxmlgui.h +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008-$THISYEAR$ $TROLLTECH$. All rights reserved. -** -** This file is part of the SCXML project on Trolltech Labs. -** -** $TROLLTECH_GPL_LICENSE$ -** -****************************************************************************/ -#ifndef QSCXMLGUI_H -#define QSCXMLGUI_H - -#include "qscxml.h" -class QMenu; -class QMessageBox; - -class QScxmlMenuInvoker: public QScxmlInvoker -{ - Q_OBJECT - - public: - QScxmlMenuInvoker(QScxmlEvent* ievent, QScxml* p) : QScxmlInvoker(ievent,p),menu(0) - { - } - static void initInvokerFactory(QScxml*); - static bool isTypeSupported (const QString & s) { return s== "q-menu"; } - public Q_SLOTS: - void activate (); - void cancel (); - - private: - QMenu* menu; -}; - - -class QScxmlMessageBoxInvoker: public QScxmlInvoker -{ - Q_OBJECT - - public: - QScxmlMessageBoxInvoker(QScxmlEvent* ievent, QScxml* p) : QScxmlInvoker(ievent,p),messageBox(0) - { - } - - static void initInvokerFactory(QScxml*); - static bool isTypeSupported (const QString & s) { return s== "q-messagebox"; } - public Q_SLOTS: - void activate (); - void cancel (); - - private Q_SLOTS: - void onFinished (int); - private: - QMessageBox* messageBox; -}; - -#endif // QSSMGUIINVOKERS_P_H diff --git a/src/src.pro b/src/src.pro deleted file mode 100644 index df334f7..0000000 --- a/src/src.pro +++ /dev/null @@ -1,10 +0,0 @@ -#------------------------------------------------- -# -# Project created by QtCreator 2009-05-24T14:33:48 -# -#------------------------------------------------- -QT += script -TARGET = qscxml -TEMPLATE = lib -CONFIG += staticlib -include (qscxml.pri)
\ No newline at end of file |