summaryrefslogtreecommitdiffstats
path: root/src/uscxml/Interpreter.h
blob: 2ad1039c157b6102391226390ffbb588a54b6665 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
/**
 *  @file
 *  @author     2012-2013 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)
 *  @copyright  Simplified BSD
 *
 *  @cond
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the FreeBSD license as published by the FreeBSD
 *  project.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 *  You should have received a copy of the FreeBSD license along with this
 *  program. If not, see <http://www.opensource.org/licenses/bsd-license>.
 *  @endcond
 */

#ifndef RUNTIME_H_SQ1MBKGN
#define RUNTIME_H_SQ1MBKGN

// this has to be the first include or MSVC will run amok
#include "uscxml/Common.h"

#include <iostream> // arabica xpath uses cerr without iostream
#include <boost/shared_ptr.hpp>
#include <set>
#include <map>

#include <XPath/XPath.hpp>
#include <DOM/Document.hpp>

#include <DOM/SAX2DOM/SAX2DOM.hpp>
#include <SAX/helpers/CatchErrorHandler.hpp>
#include <DOM/Events/EventTarget.hpp>
#include <DOM/Events/EventListener.hpp>

#include "uscxml/concurrency/BlockingQueue.h"
#include "uscxml/messages/Data.h"
#include "uscxml/messages/SendRequest.h"
#include "uscxml/URL.h"

#include "uscxml/plugins/DataModel.h"
#include "uscxml/plugins/IOProcessor.h"
#include "uscxml/plugins/Invoker.h"
#include "uscxml/plugins/ExecutableContent.h"

#define ERROR_PLATFORM_THROW(msg) \
	Event e; \
	e.name = "error.platform"; \
	e.data.compound["cause"] = Data(msg, Data::VERBATIM); \
	throw e; \
 

#define USCXML_MONITOR_CATCH(callback) \
catch (Event e) { \
	LOG(ERROR) << "Syntax error when calling " #callback " on monitors: " << std::endl << e << std::endl; \
} catch (boost::bad_weak_ptr e) { \
	LOG(ERROR) << "Unclean shutdown " << std::endl << std::endl; \
} catch (...) { \
	LOG(ERROR) << "An exception occured when calling " #callback " on monitors"; \
} \
if (_state == USCXML_DESTROYED) { \
	throw boost::bad_weak_ptr(); \
} \
 

#define USCXML_MONITOR_CALLBACK(callback)\
for(monIter_t monIter = _monitors.begin(); monIter != _monitors.end(); monIter++) { \
	try { \
		(*monIter)->callback(shared_from_this()); \
	} \
	USCXML_MONITOR_CATCH(callback) \
}

#define USCXML_MONITOR_CALLBACK2(callback, arg1)\
for(monIter_t monIter = _monitors.begin(); monIter != _monitors.end(); monIter++) { \
	try { \
		(*monIter)->callback(shared_from_this(), arg1); \
	} \
	USCXML_MONITOR_CATCH(callback) \
}

#define USCXML_MONITOR_CALLBACK3(callback, arg1, arg2)\
for(monIter_t monIter = _monitors.begin(); monIter != _monitors.end(); monIter++) { \
	try { \
		(*monIter)->callback(shared_from_this(), arg1, arg2); \
	} \
	USCXML_MONITOR_CATCH(callback) \
}

namespace uscxml {

class HTTPServletInvoker;
class InterpreterMonitor;
class InterpreterHTTPServlet;
class InterpreterWebSocketServlet;
class Factory;
class DelayedEventQueue;

enum Capabilities {
	CAN_NOTHING = 0,
	CAN_BASIC_HTTP = 1,
	CAN_GENERIC_HTTP = 2,
};

class USCXML_API InterpreterOptions {
public:
	InterpreterOptions() :
		withDebugger(false),
		verbose(false),
		withHTTP(true),
		withHTTPS(true),
		withWS(true),
		logLevel(0),
		httpPort(0),
		httpsPort(0),
		wsPort(0) {
	}

	bool withDebugger;
	bool verbose;
	bool withHTTP;
	bool withHTTPS;
	bool withWS;
	int logLevel;
	unsigned short httpPort;
	unsigned short httpsPort;
	unsigned short wsPort;
	std::string pluginPath;
	std::string certificate;
	std::string privateKey;
	std::string publicKey;
	std::map<std::string, InterpreterOptions*> interpreters;
	std::map<std::string, std::string> additionalParameters;

	std::string error;

	operator bool() {
		return error.length() == 0;
	}

	static void printUsageAndExit(const char* progName);
	static InterpreterOptions fromCmdLine(int argc, char** argv);
	unsigned int getCapabilities();

};

class USCXML_API NameSpaceInfo {
public:
	NameSpaceInfo() : nsContext(NULL) {
		init(std::map<std::string, std::string>());
	}

	NameSpaceInfo(const std::map<std::string, std::string>& nsInfo) : nsContext(NULL) {
		init(nsInfo);
	}

	NameSpaceInfo(const NameSpaceInfo& other) : nsContext(NULL) {
		init(other.nsInfo);
	}

	virtual ~NameSpaceInfo() {
		if (nsContext)
			delete nsContext;
	}

	NameSpaceInfo& operator=( const NameSpaceInfo& other ) {
		init(other.nsInfo);
		return *this;
	}

	void setPrefix(Arabica::DOM::Element<std::string> element) {
		if (nsURL.size() > 0)
			element.setPrefix(nsToPrefix[nsURL]);
	}

	void setPrefix(Arabica::DOM::Attr<std::string> attribute) {
		if (nsURL.size() > 0)
			attribute.setPrefix(nsToPrefix[nsURL]);
	}

	std::string getXMLPrefixForNS(const std::string& ns) const {
		if (nsToPrefix.find(ns) != nsToPrefix.end() && nsToPrefix.at(ns).size())
			return nsToPrefix.at(ns) + ":";
		return "";
	}

	const Arabica::XPath::StandardNamespaceContext<std::string>* getNSContext() {
		return nsContext;
	}

	std::string nsURL;         // ough to be "http://www.w3.org/2005/07/scxml" but maybe empty
	std::string xpathPrefix;   // prefix mapped for xpath, "scxml" is _xmlNSPrefix is empty but _nsURL set
	std::string xmlNSPrefix;   // the actual prefix for elements in the xml file
	std::map<std::string, std::string> nsToPrefix;  // prefixes for a given namespace
	std::map<std::string, std::string> nsInfo;      // all xmlns mappings

private:
	Arabica::XPath::StandardNamespaceContext<std::string>* nsContext;

	void init(const std::map<std::string, std::string>& nsInfo);
};

enum InterpreterState {
	USCXML_DESTROYED      = -2,  ///< destructor ran - users should never see this one
	USCXML_FINISHED       = -1,  ///< machine reached a final configuration and is done
	USCXML_IDLE           = 0,   ///< stable configuration and queues empty
	USCXML_INSTANTIATED   = 1,   ///< nothing really, just instantiated
	USCXML_MICROSTEPPED   = 2,   ///< processed one transition set
	USCXML_MACROSTEPPED   = 4,   ///< processed all transition sets and reached a stable configuration
};


USCXML_API std::ostream& operator<< (std::ostream& os, const InterpreterState& interpreterState);

class USCXML_API InterpreterImpl : public boost::enable_shared_from_this<InterpreterImpl> {
public:

	typedef std::set<InterpreterMonitor*>::iterator monIter_t;

	enum Binding {
		EARLY = 0,
		LATE = 1
	};

	virtual ~InterpreterImpl();

	void copyTo(InterpreterImpl* other);
	void copyTo(boost::shared_ptr<InterpreterImpl> other);

	// TODO: We need to move the destructor to the implementations to make these pure virtual
	virtual InterpreterState interpret() {
		return _state;    ///< Start interpreter blockingly
	}
	virtual InterpreterState step(int waitForMS = 0) {
		return _state;
	}; ///< Perform a single step

	void start(); ///< Start interpretation in a thread
	void stop(); ///< Stop interpreter thread
	void reset(); ///< Reset state machine
	void join();
	bool isRunning();

	InterpreterState getInterpreterState();

	void addMonitor(InterpreterMonitor* monitor)             {
		_monitors.insert(monitor);
	}

	void removeMonitor(InterpreterMonitor* monitor)          {
		_monitors.erase(monitor);
	}

	void setSourceURI(std::string sourceURI)                 {
		_sourceURI = URL(sourceURI);

		URL baseURI(sourceURI);
		URL::toBaseURL(baseURI);
		_baseURI = baseURI;
	}
	std::string getBaseURI()                                         {
		return _baseURI.asString();
	}
	std::string getSourceURI()                                       {
		return _sourceURI.asString();
	}

	void setCmdLineOptions(std::map<std::string, std::string> params);
	Data getCmdLineOptions() {
		return _cmdLineOptions;
	}

	InterpreterHTTPServlet* getHTTPServlet() {
		return _httpServlet;
	}

	DataModel getDataModel()                                 {
		return _dataModel;
	}

	void setParentQueue(uscxml::concurrency::BlockingQueue<SendRequest>* parentQueue) {
		_parentQueue = parentQueue;
	}

	void setFactory(Factory* factory) {
		_factory = factory;
	}
	Factory* getFactory() {
		return _factory;
	}

	Arabica::XPath::NodeSet<std::string> getNodeSetForXPath(const std::string& xpathExpr) {
		return _xpath.evaluate(xpathExpr, _scxml).asNodeSet();
	}

	void setNameSpaceInfo(const NameSpaceInfo& nsInfo) {
		_nsInfo = nsInfo;
		_xpath.setNamespaceContext(*_nsInfo.getNSContext());
	}
	NameSpaceInfo getNameSpaceInfo() const {
		return _nsInfo;
	}

	void receiveInternal(const Event& event);
	void receive(const Event& event, bool toFront = false);

	Event getCurrentEvent() {
		tthread::lock_guard<tthread::recursive_mutex> lock(_mutex);
		return _currEvent;
	}

	virtual bool isInState(const std::string& stateId);

	Arabica::XPath::NodeSet<std::string> getConfiguration()  {
		tthread::lock_guard<tthread::recursive_mutex> lock(_mutex);
		return _configuration;
	}

	Arabica::XPath::NodeSet<std::string> getBasicConfiguration()  {
		tthread::lock_guard<tthread::recursive_mutex> lock(_mutex);
		Arabica::XPath::NodeSet<std::string> basicConfig;
		for (int i = 0; i < _configuration.size(); i++) {
			if (isAtomic(_configuration[i]))
				basicConfig.push_back(_configuration[i]);
		}
		return basicConfig;
	}

	void setInitalConfiguration(const std::list<std::string>& states) {
		_startConfiguration = states;
	}
	void setInvokeRequest(const InvokeRequest& req) {
		_invokeReq = req;
	}

	virtual Arabica::DOM::Document<std::string> getDocument() const {
		return _document;
	}

	void setCapabilities(unsigned int capabilities)          {
		_capabilities = capabilities;
	}

	void setName(const std::string& name);
	const std::string& getName()                             {
		return _name;
	}
	const std::string& getSessionId()                        {
		return _sessionId;
	}

	DelayedEventQueue* getDelayQueue()                       {
		return _sendQueue;
	}

	const std::map<std::string, IOProcessor>& getIOProcessors() {
		return _ioProcessors;
	}

	const std::map<std::string, Invoker>& getInvokers() {
		return _invokers;
	}

	bool runOnMainThread(int fps, bool blocking = true);

	static bool isMember(const Arabica::DOM::Node<std::string>& node, const Arabica::XPath::NodeSet<std::string>& set);

	bool hasLegalConfiguration();
	bool isLegalConfiguration(const Arabica::XPath::NodeSet<std::string>&);
	bool isLegalConfiguration(const std::list<std::string>&);

	static bool isState(const Arabica::DOM::Node<std::string>& state);
	static bool isPseudoState(const Arabica::DOM::Node<std::string>& state);
	static bool isTransitionTarget(const Arabica::DOM::Node<std::string>& elem);
	static bool isTargetless(const Arabica::DOM::Node<std::string>& transition);
	static bool isAtomic(const Arabica::DOM::Node<std::string>& state);
	static bool isFinal(const Arabica::DOM::Node<std::string>& state);
	static bool isHistory(const Arabica::DOM::Node<std::string>& state);
	static bool isParallel(const Arabica::DOM::Node<std::string>& state);
	static bool isCompound(const Arabica::DOM::Node<std::string>& state);
	static bool isDescendant(const Arabica::DOM::Node<std::string>& s1, const Arabica::DOM::Node<std::string>& s2);
	bool isInEmbeddedDocument(const Arabica::DOM::Node<std::string>& node);
	bool isInitial(const Arabica::DOM::Node<std::string>& state);

	static std::string stateToString(InterpreterState state);

	Arabica::DOM::Node<std::string> getState(const std::string& stateId);
	Arabica::XPath::NodeSet<std::string> getStates(const std::list<std::string>& stateIds);
	Arabica::XPath::NodeSet<std::string> getAllStates();

	Arabica::XPath::NodeSet<std::string> getInitialStates(Arabica::DOM::Node<std::string> state = Arabica::DOM::Node<std::string>());
	static Arabica::XPath::NodeSet<std::string> getChildStates(const Arabica::DOM::Node<std::string>& state);
	static Arabica::XPath::NodeSet<std::string> getChildStates(const Arabica::XPath::NodeSet<std::string>& state);
	static Arabica::DOM::Node<std::string> getParentState(const Arabica::DOM::Node<std::string>& element);
	static Arabica::DOM::Node<std::string> getAncestorElement(const Arabica::DOM::Node<std::string>& node, const std::string tagName);
	virtual Arabica::XPath::NodeSet<std::string> getTargetStates(const Arabica::DOM::Node<std::string>& transition);
	virtual Arabica::XPath::NodeSet<std::string> getTargetStates(const Arabica::XPath::NodeSet<std::string>& transitions);
	virtual Arabica::DOM::Node<std::string> getSourceState(const Arabica::DOM::Node<std::string>& transition);

	static Arabica::XPath::NodeSet<std::string> filterChildElements(const std::string& tagname, const Arabica::DOM::Node<std::string>& node, bool recurse = false);
	static Arabica::XPath::NodeSet<std::string> filterChildElements(const std::string& tagName, const Arabica::XPath::NodeSet<std::string>& nodeSet, bool recurse = false);
	static Arabica::XPath::NodeSet<std::string> filterChildType(const Arabica::DOM::Node_base::Type type, const Arabica::DOM::Node<std::string>& node, bool recurse = false);
	static Arabica::XPath::NodeSet<std::string> filterChildType(const Arabica::DOM::Node_base::Type type, const Arabica::XPath::NodeSet<std::string>& nodeSet, bool recurse = false);

	static std::list<std::string> tokenizeIdRefs(const std::string& idRefs);
	static std::string spaceNormalize(const std::string& text);
	static bool nameMatch(const std::string& transitionEvent, const std::string& event);
	Arabica::DOM::Node<std::string> findLCCA(const Arabica::XPath::NodeSet<std::string>& states);
	virtual Arabica::XPath::NodeSet<std::string> getProperAncestors(const Arabica::DOM::Node<std::string>& s1, const Arabica::DOM::Node<std::string>& s2);

protected:

	static void run(void*); // static method for thread to run

	class DOMEventListener : public Arabica::DOM::Events::EventListener<std::string> {
	public:
		void handleEvent(Arabica::DOM::Events::Event<std::string>& event);
		InterpreterImpl* _interpreter;
	};

	InterpreterImpl();
	void init();
	void setupAndNormalizeDOM();
	virtual void setupIOProcessors();

	void initializeData(const Arabica::DOM::Element<std::string>& data);
	void finalizeAndAutoForwardCurrentEvent();

	void setInterpreterState(InterpreterState newState);

	bool _stable;
	tthread::thread* _thread;
	tthread::recursive_mutex _mutex;
	tthread::condition_variable _condVar;
	tthread::recursive_mutex _pluginMutex;

	InterpreterState _state;
	URL _baseURI;
	URL _sourceURI;
	Arabica::DOM::Document<std::string> _document;
	Arabica::DOM::Element<std::string> _scxml;
	Arabica::XPath::XPath<std::string> _xpath;
	NameSpaceInfo _nsInfo;

	bool _topLevelFinalReached;
	bool _isInitialized;
	bool _domIsSetup;

	bool _isStarted;
	bool _isRunning;

	InterpreterImpl::Binding _binding;
	Arabica::XPath::NodeSet<std::string> _configuration;
	Arabica::XPath::NodeSet<std::string> _alreadyEntered;
	Arabica::XPath::NodeSet<std::string> _statesToInvoke;
	std::list<std::string> _startConfiguration;
	InvokeRequest _invokeReq;

	DataModel _dataModel;
	std::map<std::string, Arabica::XPath::NodeSet<std::string> > _historyValue;

	std::list<Event > _internalQueue;
	uscxml::concurrency::BlockingQueue<Event> _externalQueue;
	uscxml::concurrency::BlockingQueue<SendRequest>* _parentQueue;
	DelayedEventQueue* _sendQueue;

	DOMEventListener _domEventListener;

	Event _currEvent;
	Factory* _factory;
	InterpreterHTTPServlet* _httpServlet;
	InterpreterWebSocketServlet* _wsServlet;
	std::set<InterpreterMonitor*> _monitors;

	long _lastRunOnMainThread;
	std::string _name;
	std::string _sessionId;
	unsigned int _capabilities;

	Data _cmdLineOptions;

	virtual void executeContent(const Arabica::DOM::Node<std::string>& content, bool rethrow = false);
	virtual void executeContent(const Arabica::DOM::NodeList<std::string>& content, bool rethrow = false);
	virtual void executeContent(const Arabica::XPath::NodeSet<std::string>& content, bool rethrow = false);

	void processContentElement(const Arabica::DOM::Node<std::string>& element,
	                           Arabica::DOM::Node<std::string>& dom,
	                           std::string& text,
	                           std::string& expr);
	void processParamChilds(const Arabica::DOM::Node<std::string>& element,
	                        std::multimap<std::string, Data>& params);
	void processDOMorText(const Arabica::DOM::Node<std::string>& element,
	                      Arabica::DOM::Node<std::string>& dom,
	                      std::string& text);

	virtual void send(const Arabica::DOM::Node<std::string>& element);
	virtual void invoke(const Arabica::DOM::Node<std::string>& element);
	virtual void cancelInvoke(const Arabica::DOM::Node<std::string>& element);
	virtual void internalDoneSend(const Arabica::DOM::Node<std::string>& state);
	static void delayedSend(void* userdata, std::string eventName);
	void returnDoneEvent(const Arabica::DOM::Node<std::string>& state);

	bool hasConditionMatch(const Arabica::DOM::Node<std::string>& conditional);
	bool isInFinalState(const Arabica::DOM::Node<std::string>& state);
	bool parentIsScxmlState(const Arabica::DOM::Node<std::string>& state);

	IOProcessor getIOProcessor(const std::string& type);

	std::map<std::string, IOProcessor> _ioProcessors;
	std::map<std::string, std::pair<InterpreterImpl*, SendRequest> > _sendIds;
	std::map<std::string, Invoker> _invokers;
	std::map<Arabica::DOM::Node<std::string>, ExecutableContent> _executableContent;

	/// TODO: We need to adapt them when the DOM is operated upon
	std::map<std::string, Arabica::DOM::Node<std::string> > _cachedStates;
	std::map<std::string, URL> _cachedURLs;

	friend class USCXMLInvoker;
	friend class SCXMLIOProcessor;
	friend class Interpreter;
};

class USCXML_API Interpreter {
public:
	static Interpreter fromDOM(const Arabica::DOM::Document<std::string>& dom,
	                           const NameSpaceInfo& nameSpaceInfo);
	static Interpreter fromXML(const std::string& xml);
	static Interpreter fromURI(const std::string& uri);
	static Interpreter fromClone(const Interpreter& other);

	Interpreter() : _impl() {} // the empty, invalid interpreter
	Interpreter(boost::shared_ptr<InterpreterImpl> const impl) : _impl(impl) { }
	Interpreter(const Interpreter& other) : _impl(other._impl) { }
	virtual ~Interpreter() {};

	operator bool() const {
		return (_impl && _impl->_state != USCXML_DESTROYED);
	}
	bool operator< (const Interpreter& other) const     {
		return _impl < other._impl;
	}
	bool operator==(const Interpreter& other) const     {
		return _impl == other._impl;
	}
	bool operator!=(const Interpreter& other) const     {
		return _impl != other._impl;
	}
	Interpreter& operator= (const Interpreter& other)   {
		_impl = other._impl;
		return *this;
	}

	void reset() {
		return _impl->reset();
	}

	void start() {
		return _impl->start();
	}
	void stop() {
		return _impl->stop();
	}
//	void join() {
//		return _impl->join();
//	};
	bool isRunning() {
		return _impl->isRunning();
	}

	void interpret() {
		_impl->interpret();
	};

	InterpreterState step(int waitForMS = 0) {
		return _impl->step(waitForMS);
	};

	InterpreterState step(bool blocking) {
		if (blocking)
			return _impl->step(-1);
		return _impl->step(0);
	};

	InterpreterState getState() {
		return _impl->getInterpreterState();
	}

	void addMonitor(InterpreterMonitor* monitor) {
		return _impl->addMonitor(monitor);
	}

	void removeMonitor(InterpreterMonitor* monitor) {
		return _impl->removeMonitor(monitor);
	}

	void setSourceURI(std::string sourceURI) {
		return _impl->setSourceURI(sourceURI);
	}
	std::string getSourceURI() {
		return _impl->getSourceURI();
	}
	std::string getBaseURI() {
		return _impl->getBaseURI();
	}

	void setNameSpaceInfo(const NameSpaceInfo& nsInfo) {
		_impl->setNameSpaceInfo(nsInfo);
	}
	NameSpaceInfo getNameSpaceInfo() const {
		return _impl->getNameSpaceInfo();
	}

	void setCmdLineOptions(std::map<std::string, std::string> params) {
		return _impl->setCmdLineOptions(params);
	}
	Data getCmdLineOptions() {
		return _impl->getCmdLineOptions();
	}

	InterpreterHTTPServlet* getHTTPServlet() {
		return _impl->getHTTPServlet();
	}

	DataModel getDataModel() {
		return _impl->getDataModel();
	}
	void setParentQueue(uscxml::concurrency::BlockingQueue<SendRequest>* parentQueue) {
		return _impl->setParentQueue(parentQueue);
	}
	void setFactory(Factory* factory) {
		return _impl->setFactory(factory);
	}
	Factory* getFactory() {
		return _impl->getFactory();
	}
	Arabica::XPath::NodeSet<std::string> getNodeSetForXPath(const std::string& xpathExpr) {
		return _impl->getNodeSetForXPath(xpathExpr);
	}

	void inline receiveInternal(const Event& event) {
		return _impl->receiveInternal(event);
	}
	void receive(const Event& event, bool toFront = false) {
		return _impl->receive(event, toFront);
	}

	Event getCurrentEvent() {
		return _impl->getCurrentEvent();
	}

	bool isInState(const std::string& stateId) {
		return _impl->isInState(stateId);
	}

	Arabica::XPath::NodeSet<std::string> getConfiguration() {
		return _impl->getConfiguration();
	}

	Arabica::XPath::NodeSet<std::string> getBasicConfiguration() {
		return _impl->getBasicConfiguration();
	}

	void setInitalConfiguration(const std::list<std::string>& states) {
		return _impl->setInitalConfiguration(states);
	}

//	Arabica::DOM::Node<std::string> getState(const std::string& stateId) {
//		return _impl->getState(stateId);
//	}
//	Arabica::XPath::NodeSet<std::string> getStates(const std::list<std::string>& stateIds) {
//		return _impl->getStates(stateIds);
//	}
//	Arabica::XPath::NodeSet<std::string> getAllStates() {
//		return _impl->getAllStates();
//	}

	Arabica::DOM::Document<std::string> getDocument() const {
		return _impl->getDocument();
	}

	void setCapabilities(unsigned int capabilities) {
		return _impl->setCapabilities(capabilities);
	}

	void setName(const std::string& name) {
		return _impl->setName(name);
	}

	const std::string& getName() {
		return _impl->getName();
	}
	const std::string& getSessionId() {
		return _impl->getSessionId();
	}
	DelayedEventQueue* getDelayQueue() {
		return _impl->getDelayQueue();
	}

	const std::map<std::string, IOProcessor>& getIOProcessors() {
		return _impl->getIOProcessors();
	}

	const std::map<std::string, Invoker>& getInvokers() {
		return _impl->getInvokers();
	}

	bool runOnMainThread(int fps, bool blocking = true) {
		return _impl->runOnMainThread(fps, blocking);
	}

	bool hasLegalConfiguration() {
		return _impl->hasLegalConfiguration();
	}

	bool isLegalConfiguration(const Arabica::XPath::NodeSet<std::string>& config) {
		return _impl->isLegalConfiguration(config);
	}

	bool isLegalConfiguration(const std::list<std::string>& config) {
		return _impl->isLegalConfiguration(config);
	}

	boost::shared_ptr<InterpreterImpl> getImpl() const {
		return _impl;
	}

	static std::map<std::string, boost::weak_ptr<InterpreterImpl> > getInstances();

protected:

	void setInvokeRequest(const InvokeRequest& req) {
		return _impl->setInvokeRequest(req);
	}

	static Interpreter fromInputSource(Arabica::SAX::InputSource<std::string>& source);

	boost::shared_ptr<InterpreterImpl> _impl;
	static std::map<std::string, boost::weak_ptr<InterpreterImpl> > _instances;
	static tthread::recursive_mutex _instanceMutex;
};

class USCXML_API InterpreterMonitor {
public:
	virtual ~InterpreterMonitor() {}

	virtual void beforeProcessingEvent(Interpreter interpreter, const Event& event) {}
	virtual void beforeMicroStep(Interpreter interpreter) {}

	virtual void beforeExitingState(Interpreter interpreter, const Arabica::DOM::Element<std::string>& state, bool moreComing) {}
	virtual void afterExitingState(Interpreter interpreter, const Arabica::DOM::Element<std::string>& state, bool moreComing) {}

	virtual void beforeExecutingContent(Interpreter interpreter, const Arabica::DOM::Element<std::string>& element) {}
	virtual void afterExecutingContent(Interpreter interpreter, const Arabica::DOM::Element<std::string>& element) {}

	virtual void beforeUninvoking(Interpreter interpreter, const Arabica::DOM::Element<std::string>& invokeElem, const std::string& invokeid) {}
	virtual void afterUninvoking(Interpreter interpreter, const Arabica::DOM::Element<std::string>& invokeElem, const std::string& invokeid) {}

	virtual void beforeTakingTransition(Interpreter interpreter, const Arabica::DOM::Element<std::string>& transition, bool moreComing) {}
	virtual void afterTakingTransition(Interpreter interpreter, const Arabica::DOM::Element<std::string>& transition, bool moreComing) {}

	virtual void beforeEnteringState(Interpreter interpreter, const Arabica::DOM::Element<std::string>& state, bool moreComing) {}
	virtual void afterEnteringState(Interpreter interpreter, const Arabica::DOM::Element<std::string>& state, bool moreComing) {}

	virtual void beforeInvoking(Interpreter interpreter, const Arabica::DOM::Element<std::string>& invokeElem, const std::string& invokeid) {}
	virtual void afterInvoking(Interpreter interpreter, const Arabica::DOM::Element<std::string>& invokeElem, const std::string& invokeid) {}

	virtual void afterMicroStep(Interpreter interpreter) {}

	virtual void onStableConfiguration(Interpreter interpreter) {}

	virtual void beforeCompletion(Interpreter interpreter) {}
	virtual void afterCompletion(Interpreter interpreter) {}

};

}

#endif