1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtDeclarative module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "private/qdeclarativexmlhttprequest_p.h"
44 #include <private/qv8engine_p.h>
46 #include "qdeclarativeengine.h"
47 #include "private/qdeclarativeengine_p.h"
48 #include "private/qdeclarativerefcount_p.h"
49 #include "private/qdeclarativeengine_p.h"
50 #include "private/qdeclarativeexpression_p.h"
51 #include "qdeclarativeglobal_p.h"
53 #include <QtCore/qobject.h>
54 #include <QtScript/qscriptvalue.h>
55 #include <QtScript/qscriptcontext.h>
56 #include <QtScript/qscriptengine.h>
57 #include <QtNetwork/qnetworkreply.h>
58 #include <QtCore/qtextcodec.h>
59 #include <QtCore/qxmlstream.h>
60 #include <QtCore/qstack.h>
61 #include <QtCore/qdebug.h>
63 #include <QtCore/QStringBuilder>
65 #ifndef QT_NO_XMLSTREAMREADER
67 // From DOM-Level-3-Core spec
68 // http://www.w3.org/TR/DOM-Level-3-Core/core.html
69 #define INDEX_SIZE_ERR 1
70 #define DOMSTRING_SIZE_ERR 2
71 #define HIERARCHY_REQUEST_ERR 3
72 #define WRONG_DOCUMENT_ERR 4
73 #define INVALID_CHARACTER_ERR 5
74 #define NO_DATA_ALLOWED_ERR 6
75 #define NO_MODIFICATION_ALLOWED_ERR 7
76 #define NOT_FOUND_ERR 8
77 #define NOT_SUPPORTED_ERR 9
78 #define INUSE_ATTRIBUTE_ERR 10
79 #define INVALID_STATE_ERR 11
81 #define INVALID_MODIFICATION_ERR 13
82 #define NAMESPACE_ERR 14
83 #define INVALID_ACCESS_ERR 15
84 #define VALIDATION_ERR 16
85 #define TYPE_MISMATCH_ERR 17
87 #define V8THROW_DOM(error, string) { \
88 v8::Local<v8::Value> v = v8::Exception::Error(v8::String::New(string)); \
89 v->ToObject()->Set(v8::String::New("code"), v8::Integer::New(error)); \
90 v8::ThrowException(v); \
91 return v8::Handle<v8::Value>(); \
94 #define V8THROW_REFERENCE(string) { \
95 v8::ThrowException(v8::Exception::ReferenceError(v8::String::New(string))); \
96 return v8::Handle<v8::Value>(); \
99 #define D(arg) (arg)->release()
100 #define A(arg) (arg)->addref()
104 DEFINE_BOOL_CONFIG_OPTION(xhrDump, QML_XHR_DUMP);
106 struct QDeclarativeXMLHttpRequestData {
107 QDeclarativeXMLHttpRequestData();
108 ~QDeclarativeXMLHttpRequestData();
110 v8::Persistent<v8::Function> nodeFunction;
112 v8::Persistent<v8::Object> namedNodeMapPrototype;
113 v8::Persistent<v8::Object> nodeListPrototype;
114 v8::Persistent<v8::Object> nodePrototype;
115 v8::Persistent<v8::Object> elementPrototype;
116 v8::Persistent<v8::Object> attrPrototype;
117 v8::Persistent<v8::Object> characterDataPrototype;
118 v8::Persistent<v8::Object> textPrototype;
119 v8::Persistent<v8::Object> cdataPrototype;
120 v8::Persistent<v8::Object> documentPrototype;
122 v8::Local<v8::Object> newNode();
125 static inline QDeclarativeXMLHttpRequestData *xhrdata(QV8Engine *engine)
127 return (QDeclarativeXMLHttpRequestData *)engine->xmlHttpRequestData();
130 QDeclarativeXMLHttpRequestData::QDeclarativeXMLHttpRequestData()
134 QDeclarativeXMLHttpRequestData::~QDeclarativeXMLHttpRequestData()
136 qPersistentDispose(nodeFunction);
137 qPersistentDispose(namedNodeMapPrototype);
138 qPersistentDispose(nodeListPrototype);
139 qPersistentDispose(nodePrototype);
140 qPersistentDispose(elementPrototype);
141 qPersistentDispose(attrPrototype);
142 qPersistentDispose(characterDataPrototype);
143 qPersistentDispose(textPrototype);
144 qPersistentDispose(cdataPrototype);
145 qPersistentDispose(documentPrototype);
148 v8::Local<v8::Object> QDeclarativeXMLHttpRequestData::newNode()
150 if (nodeFunction.IsEmpty()) {
151 v8::Local<v8::FunctionTemplate> ft = v8::FunctionTemplate::New();
152 ft->InstanceTemplate()->SetHasExternalResource(true);
153 nodeFunction = qPersistentNew<v8::Function>(ft->GetFunction());
156 return nodeFunction->NewInstance();
165 NodeImpl() : type(Element), document(0), parent(0) {}
166 virtual ~NodeImpl() {
167 for (int ii = 0; ii < children.count(); ++ii)
168 delete children.at(ii);
169 for (int ii = 0; ii < attributes.count(); ++ii)
170 delete attributes.at(ii);
173 // These numbers are copied from the Node IDL definition
179 DocumentFragment = 11,
185 ProcessingInstruction = 7,
190 QString namespaceUri;
198 DocumentImpl *document;
201 QList<NodeImpl *> children;
202 QList<NodeImpl *> attributes;
205 class DocumentImpl : public QDeclarativeRefCount, public NodeImpl
208 DocumentImpl() : root(0) { type = Document; }
209 virtual ~DocumentImpl() {
210 if (root) delete root;
219 void addref() { QDeclarativeRefCount::addref(); }
220 void release() { QDeclarativeRefCount::release(); }
227 static v8::Handle<v8::Value> length(v8::Local<v8::String>, const v8::AccessorInfo& args);
228 static v8::Handle<v8::Value> indexed(uint32_t index, const v8::AccessorInfo& info);
229 static v8::Handle<v8::Value> named(v8::Local<v8::String> property, const v8::AccessorInfo& args);
232 static v8::Handle<v8::Object> prototype(QV8Engine *);
233 static v8::Handle<v8::Value> create(QV8Engine *, NodeImpl *, QList<NodeImpl *> *);
240 static v8::Handle<v8::Value> length(v8::Local<v8::String>, const v8::AccessorInfo& args);
241 static v8::Handle<v8::Value> indexed(uint32_t index, const v8::AccessorInfo& info);
244 static v8::Handle<v8::Object> prototype(QV8Engine *);
245 static v8::Handle<v8::Value> create(QV8Engine *, NodeImpl *);
252 static v8::Handle<v8::Value> nodeName(v8::Local<v8::String>, const v8::AccessorInfo& args);
253 static v8::Handle<v8::Value> nodeValue(v8::Local<v8::String>, const v8::AccessorInfo& args);
254 static v8::Handle<v8::Value> nodeType(v8::Local<v8::String>, const v8::AccessorInfo& args);
256 static v8::Handle<v8::Value> parentNode(v8::Local<v8::String>, const v8::AccessorInfo& args);
257 static v8::Handle<v8::Value> childNodes(v8::Local<v8::String>, const v8::AccessorInfo& args);
258 static v8::Handle<v8::Value> firstChild(v8::Local<v8::String>, const v8::AccessorInfo& args);
259 static v8::Handle<v8::Value> lastChild(v8::Local<v8::String>, const v8::AccessorInfo& args);
260 static v8::Handle<v8::Value> previousSibling(v8::Local<v8::String>, const v8::AccessorInfo& args);
261 static v8::Handle<v8::Value> nextSibling(v8::Local<v8::String>, const v8::AccessorInfo& args);
262 static v8::Handle<v8::Value> attributes(v8::Local<v8::String>, const v8::AccessorInfo& args);
264 //static v8::Handle<v8::Value> ownerDocument(v8::Local<v8::String>, const v8::AccessorInfo& args);
265 //static v8::Handle<v8::Value> namespaceURI(v8::Local<v8::String>, const v8::AccessorInfo& args);
266 //static v8::Handle<v8::Value> prefix(v8::Local<v8::String>, const v8::AccessorInfo& args);
267 //static v8::Handle<v8::Value> localName(v8::Local<v8::String>, const v8::AccessorInfo& args);
268 //static v8::Handle<v8::Value> baseURI(v8::Local<v8::String>, const v8::AccessorInfo& args);
269 //static v8::Handle<v8::Value> textContent(v8::Local<v8::String>, const v8::AccessorInfo& args);
272 static v8::Handle<v8::Object> prototype(QV8Engine *);
273 static v8::Handle<v8::Value> create(QV8Engine *, NodeImpl *);
283 Node &operator=(const Node &);
286 class Element : public Node
290 static v8::Handle<v8::Object> prototype(QV8Engine *);
293 class Attr : public Node
297 static v8::Handle<v8::Value> name(v8::Local<v8::String>, const v8::AccessorInfo& args);
298 static v8::Handle<v8::Value> specified(v8::Local<v8::String>, const v8::AccessorInfo& args);
299 static v8::Handle<v8::Value> value(v8::Local<v8::String>, const v8::AccessorInfo& args);
300 static v8::Handle<v8::Value> ownerElement(v8::Local<v8::String>, const v8::AccessorInfo& args);
301 static v8::Handle<v8::Value> schemaTypeInfo(v8::Local<v8::String>, const v8::AccessorInfo& args);
302 static v8::Handle<v8::Value> isId(v8::Local<v8::String>, const v8::AccessorInfo& args);
305 static v8::Handle<v8::Object> prototype(QV8Engine *);
308 class CharacterData : public Node
312 static v8::Handle<v8::Value> length(v8::Local<v8::String>, const v8::AccessorInfo& args);
315 static v8::Handle<v8::Object> prototype(QV8Engine *);
318 class Text : public CharacterData
322 static v8::Handle<v8::Value> isElementContentWhitespace(v8::Local<v8::String>, const v8::AccessorInfo& args);
323 static v8::Handle<v8::Value> wholeText(v8::Local<v8::String>, const v8::AccessorInfo& args);
326 static v8::Handle<v8::Object> prototype(QV8Engine *);
329 class CDATA : public Text
333 static v8::Handle<v8::Object> prototype(QV8Engine *);
336 class Document : public Node
340 static v8::Handle<v8::Value> xmlVersion(v8::Local<v8::String>, const v8::AccessorInfo& args);
341 static v8::Handle<v8::Value> xmlEncoding(v8::Local<v8::String>, const v8::AccessorInfo& args);
342 static v8::Handle<v8::Value> xmlStandalone(v8::Local<v8::String>, const v8::AccessorInfo& args);
343 static v8::Handle<v8::Value> documentElement(v8::Local<v8::String>, const v8::AccessorInfo& args);
346 static v8::Handle<v8::Object> prototype(QV8Engine *);
347 static v8::Handle<v8::Value> load(QV8Engine *engine, const QByteArray &data);
352 class QDeclarativeDOMNodeResource : public QV8ObjectResource, public Node
354 V8_RESOURCE_TYPE(DOMNodeType);
356 QDeclarativeDOMNodeResource(QV8Engine *e);
358 QList<NodeImpl *> *list; // Only used in NamedNodeMap
361 QDeclarativeDOMNodeResource::QDeclarativeDOMNodeResource(QV8Engine *e)
362 : QV8ObjectResource(e), list(0)
368 Q_DECLARE_METATYPE(Node)
369 Q_DECLARE_METATYPE(NodeList)
370 Q_DECLARE_METATYPE(NamedNodeMap)
374 void NodeImpl::addref()
379 void NodeImpl::release()
384 v8::Handle<v8::Value> Node::nodeName(v8::Local<v8::String>, const v8::AccessorInfo &args)
386 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
387 if (!r) return v8::Undefined();
388 QV8Engine *engine = V8ENGINE();
390 switch (r->d->type) {
391 case NodeImpl::Document:
392 return v8::String::New("#document");
393 case NodeImpl::CDATA:
394 return v8::String::New("#cdata-section");
396 return v8::String::New("#text");
398 return engine->toString(r->d->name);
402 v8::Handle<v8::Value> Node::nodeValue(v8::Local<v8::String>, const v8::AccessorInfo &args)
404 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
405 if (!r) return v8::Undefined();
406 QV8Engine *engine = V8ENGINE();
408 if (r->d->type == NodeImpl::Document ||
409 r->d->type == NodeImpl::DocumentFragment ||
410 r->d->type == NodeImpl::DocumentType ||
411 r->d->type == NodeImpl::Element ||
412 r->d->type == NodeImpl::Entity ||
413 r->d->type == NodeImpl::EntityReference ||
414 r->d->type == NodeImpl::Notation)
417 return engine->toString(r->d->data);
420 v8::Handle<v8::Value> Node::nodeType(v8::Local<v8::String>, const v8::AccessorInfo &args)
422 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
423 if (!r) return v8::Undefined();
424 return v8::Integer::New(r->d->type);
427 v8::Handle<v8::Value> Node::parentNode(v8::Local<v8::String>, const v8::AccessorInfo &args)
429 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
430 if (!r) return v8::Undefined();
431 QV8Engine *engine = V8ENGINE();
433 if (r->d->parent) return Node::create(engine, r->d->parent);
434 else return v8::Null();
437 v8::Handle<v8::Value> Node::childNodes(v8::Local<v8::String>, const v8::AccessorInfo &args)
439 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
440 if (!r) return v8::Undefined();
441 QV8Engine *engine = V8ENGINE();
443 return NodeList::create(engine, r->d);
446 v8::Handle<v8::Value> Node::firstChild(v8::Local<v8::String>, const v8::AccessorInfo &args)
448 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
449 if (!r) return v8::Undefined();
450 QV8Engine *engine = V8ENGINE();
452 if (r->d->children.isEmpty()) return v8::Null();
453 else return Node::create(engine, r->d->children.first());
456 v8::Handle<v8::Value> Node::lastChild(v8::Local<v8::String>, const v8::AccessorInfo &args)
458 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
459 if (!r) return v8::Undefined();
460 QV8Engine *engine = V8ENGINE();
462 if (r->d->children.isEmpty()) return v8::Null();
463 else return Node::create(engine, r->d->children.last());
466 v8::Handle<v8::Value> Node::previousSibling(v8::Local<v8::String>, const v8::AccessorInfo &args)
468 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
469 if (!r) return v8::Undefined();
470 QV8Engine *engine = V8ENGINE();
472 if (!r->d->parent) return v8::Null();
474 for (int ii = 0; ii < r->d->parent->children.count(); ++ii) {
475 if (r->d->parent->children.at(ii) == r->d) {
476 if (ii == 0) return v8::Null();
477 else return Node::create(engine, r->d->parent->children.at(ii - 1));
484 v8::Handle<v8::Value> Node::nextSibling(v8::Local<v8::String>, const v8::AccessorInfo &args)
486 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
487 if (!r) return v8::Undefined();
488 QV8Engine *engine = V8ENGINE();
490 if (!r->d->parent) return v8::Null();
492 for (int ii = 0; ii < r->d->parent->children.count(); ++ii) {
493 if (r->d->parent->children.at(ii) == r->d) {
494 if ((ii + 1) == r->d->parent->children.count()) return v8::Null();
495 else return Node::create(engine, r->d->parent->children.at(ii + 1));
502 v8::Handle<v8::Value> Node::attributes(v8::Local<v8::String>, const v8::AccessorInfo &args)
504 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
505 if (!r) return v8::Undefined();
506 QV8Engine *engine = V8ENGINE();
508 if (r->d->type != NodeImpl::Element)
511 return NamedNodeMap::create(engine, r->d, &r->d->attributes);
514 v8::Handle<v8::Object> Node::prototype(QV8Engine *engine)
516 QDeclarativeXMLHttpRequestData *d = xhrdata(engine);
517 if (d->nodePrototype.IsEmpty()) {
518 d->nodePrototype = qPersistentNew<v8::Object>(v8::Object::New());
519 d->nodePrototype->SetAccessor(v8::String::New("nodeName"), nodeName,
520 0, v8::External::Wrap(engine));
521 d->nodePrototype->SetAccessor(v8::String::New("nodeValue"), nodeValue,
522 0, v8::External::Wrap(engine));
523 d->nodePrototype->SetAccessor(v8::String::New("nodeType"), nodeType,
524 0, v8::External::Wrap(engine));
525 d->nodePrototype->SetAccessor(v8::String::New("parentNode"), parentNode,
526 0, v8::External::Wrap(engine));
527 d->nodePrototype->SetAccessor(v8::String::New("childNodes"), childNodes,
528 0, v8::External::Wrap(engine));
529 d->nodePrototype->SetAccessor(v8::String::New("firstChild"), firstChild,
530 0, v8::External::Wrap(engine));
531 d->nodePrototype->SetAccessor(v8::String::New("lastChild"), lastChild,
532 0, v8::External::Wrap(engine));
533 d->nodePrototype->SetAccessor(v8::String::New("previousSibling"), previousSibling,
534 0, v8::External::Wrap(engine));
535 d->nodePrototype->SetAccessor(v8::String::New("nextSibling"), nextSibling,
536 0, v8::External::Wrap(engine));
537 d->nodePrototype->SetAccessor(v8::String::New("attributes"), attributes,
538 0, v8::External::Wrap(engine));
539 engine->freezeObject(d->nodePrototype);
541 return d->nodePrototype;
544 v8::Handle<v8::Value> Node::create(QV8Engine *engine, NodeImpl *data)
546 QDeclarativeXMLHttpRequestData *d = xhrdata(engine);
547 v8::Local<v8::Object> instance = d->newNode();
549 switch (data->type) {
551 instance->SetPrototype(Attr::prototype(engine));
553 case NodeImpl::Comment:
554 case NodeImpl::Document:
555 case NodeImpl::DocumentFragment:
556 case NodeImpl::DocumentType:
557 case NodeImpl::Entity:
558 case NodeImpl::EntityReference:
559 case NodeImpl::Notation:
560 case NodeImpl::ProcessingInstruction:
561 return v8::Undefined();
562 case NodeImpl::CDATA:
563 instance->SetPrototype(CDATA::prototype(engine));
566 instance->SetPrototype(Text::prototype(engine));
568 case NodeImpl::Element:
569 instance->SetPrototype(Element::prototype(engine));
573 QDeclarativeDOMNodeResource *r = new QDeclarativeDOMNodeResource(engine);
576 instance->SetExternalResource(r);
581 v8::Handle<v8::Object> Element::prototype(QV8Engine *engine)
583 QDeclarativeXMLHttpRequestData *d = xhrdata(engine);
584 if (d->elementPrototype.IsEmpty()) {
585 d->elementPrototype = qPersistentNew<v8::Object>(v8::Object::New());
586 d->elementPrototype->SetPrototype(Node::prototype(engine));
587 d->elementPrototype->SetAccessor(v8::String::New("tagName"), nodeName,
588 0, v8::External::Wrap(engine));
589 engine->freezeObject(d->elementPrototype);
591 return d->elementPrototype;
594 v8::Handle<v8::Object> Attr::prototype(QV8Engine *engine)
596 QDeclarativeXMLHttpRequestData *d = xhrdata(engine);
597 if (d->attrPrototype.IsEmpty()) {
598 d->attrPrototype = qPersistentNew<v8::Object>(v8::Object::New());
599 d->attrPrototype->SetPrototype(Node::prototype(engine));
600 d->attrPrototype->SetAccessor(v8::String::New("name"), name,
601 0, v8::External::Wrap(engine));
602 d->attrPrototype->SetAccessor(v8::String::New("value"), value,
603 0, v8::External::Wrap(engine));
604 d->attrPrototype->SetAccessor(v8::String::New("ownerElement"), ownerElement,
605 0, v8::External::Wrap(engine));
606 engine->freezeObject(d->attrPrototype);
608 return d->attrPrototype;
611 v8::Handle<v8::Value> Attr::name(v8::Local<v8::String>, const v8::AccessorInfo &args)
613 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
614 if (!r) return v8::Undefined();
615 QV8Engine *engine = V8ENGINE();
617 return engine->toString(r->d->name);
620 v8::Handle<v8::Value> Attr::value(v8::Local<v8::String>, const v8::AccessorInfo &args)
622 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
623 if (!r) return v8::Undefined();
624 QV8Engine *engine = V8ENGINE();
626 return engine->toString(r->d->data);
629 v8::Handle<v8::Value> Attr::ownerElement(v8::Local<v8::String>, const v8::AccessorInfo &args)
631 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
632 if (!r) return v8::Undefined();
633 QV8Engine *engine = V8ENGINE();
635 return Node::create(engine, r->d->parent);
638 v8::Handle<v8::Value> CharacterData::length(v8::Local<v8::String>, const v8::AccessorInfo &args)
640 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
641 if (!r) return v8::Undefined();
642 QV8Engine *engine = V8ENGINE();
644 return v8::Integer::New(r->d->data.length());
647 v8::Handle<v8::Object> CharacterData::prototype(QV8Engine *engine)
649 QDeclarativeXMLHttpRequestData *d = xhrdata(engine);
650 if (d->characterDataPrototype.IsEmpty()) {
651 d->characterDataPrototype = qPersistentNew<v8::Object>(v8::Object::New());
652 d->characterDataPrototype->SetPrototype(Node::prototype(engine));
653 d->characterDataPrototype->SetAccessor(v8::String::New("data"), nodeValue,
654 0, v8::External::Wrap(engine));
655 d->characterDataPrototype->SetAccessor(v8::String::New("length"), length,
656 0, v8::External::Wrap(engine));
657 engine->freezeObject(d->characterDataPrototype);
659 return d->characterDataPrototype;
662 v8::Handle<v8::Value> Text::isElementContentWhitespace(v8::Local<v8::String>, const v8::AccessorInfo &args)
664 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
665 if (!r) return v8::Undefined();
666 QV8Engine *engine = V8ENGINE();
668 return v8::Boolean::New(r->d->data.trimmed().isEmpty());
671 v8::Handle<v8::Value> Text::wholeText(v8::Local<v8::String>, const v8::AccessorInfo &args)
673 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
674 if (!r) return v8::Undefined();
675 QV8Engine *engine = V8ENGINE();
677 return engine->toString(r->d->data);
680 v8::Handle<v8::Object> Text::prototype(QV8Engine *engine)
682 QDeclarativeXMLHttpRequestData *d = xhrdata(engine);
683 if (d->textPrototype.IsEmpty()) {
684 d->textPrototype = qPersistentNew<v8::Object>(v8::Object::New());
685 d->textPrototype->SetPrototype(CharacterData::prototype(engine));
686 d->textPrototype->SetAccessor(v8::String::New("isElementContentWhitespace"), isElementContentWhitespace,
687 0, v8::External::Wrap(engine));
688 d->textPrototype->SetAccessor(v8::String::New("wholeText"), wholeText,
689 0, v8::External::Wrap(engine));
690 engine->freezeObject(d->textPrototype);
692 return d->textPrototype;
695 v8::Handle<v8::Object> CDATA::prototype(QV8Engine *engine)
697 QDeclarativeXMLHttpRequestData *d = xhrdata(engine);
698 if (d->cdataPrototype.IsEmpty()) {
699 d->cdataPrototype = qPersistentNew<v8::Object>(v8::Object::New());
700 d->cdataPrototype->SetPrototype(Text::prototype(engine));
701 engine->freezeObject(d->cdataPrototype);
703 return d->cdataPrototype;
706 v8::Handle<v8::Object> Document::prototype(QV8Engine *engine)
708 QDeclarativeXMLHttpRequestData *d = xhrdata(engine);
709 if (d->documentPrototype.IsEmpty()) {
710 d->documentPrototype = qPersistentNew<v8::Object>(v8::Object::New());
711 d->documentPrototype->SetPrototype(Node::prototype(engine));
712 d->documentPrototype->SetAccessor(v8::String::New("xmlVersion"), xmlVersion,
713 0, v8::External::Wrap(engine));
714 d->documentPrototype->SetAccessor(v8::String::New("xmlEncoding"), xmlEncoding,
715 0, v8::External::Wrap(engine));
716 d->documentPrototype->SetAccessor(v8::String::New("xmlStandalone"), xmlStandalone,
717 0, v8::External::Wrap(engine));
718 d->documentPrototype->SetAccessor(v8::String::New("documentElement"), documentElement,
719 0, v8::External::Wrap(engine));
720 engine->freezeObject(d->documentPrototype);
722 return d->documentPrototype;
725 v8::Handle<v8::Value> Document::load(QV8Engine *engine, const QByteArray &data)
729 DocumentImpl *document = 0;
730 QStack<NodeImpl *> nodeStack;
732 QXmlStreamReader reader(data);
734 while (!reader.atEnd()) {
735 switch (reader.readNext()) {
736 case QXmlStreamReader::NoToken:
738 case QXmlStreamReader::Invalid:
740 case QXmlStreamReader::StartDocument:
742 document = new DocumentImpl;
743 document->document = document;
744 document->version = reader.documentVersion().toString();
745 document->encoding = reader.documentEncoding().toString();
746 document->isStandalone = reader.isStandaloneDocument();
748 case QXmlStreamReader::EndDocument:
750 case QXmlStreamReader::StartElement:
753 NodeImpl *node = new NodeImpl;
754 node->document = document;
755 node->namespaceUri = reader.namespaceUri().toString();
756 node->name = reader.name().toString();
757 if (nodeStack.isEmpty()) {
758 document->root = node;
760 node->parent = nodeStack.top();
761 node->parent->children.append(node);
763 nodeStack.append(node);
765 foreach (const QXmlStreamAttribute &a, reader.attributes()) {
766 NodeImpl *attr = new NodeImpl;
767 attr->document = document;
768 attr->type = NodeImpl::Attr;
769 attr->namespaceUri = a.namespaceUri().toString();
770 attr->name = a.name().toString();
771 attr->data = a.value().toString();
773 node->attributes.append(attr);
777 case QXmlStreamReader::EndElement:
780 case QXmlStreamReader::Characters:
782 NodeImpl *node = new NodeImpl;
783 node->document = document;
784 node->type = reader.isCDATA()?NodeImpl::CDATA:NodeImpl::Text;
785 node->parent = nodeStack.top();
786 node->parent->children.append(node);
787 node->data = reader.text().toString();
790 case QXmlStreamReader::Comment:
792 case QXmlStreamReader::DTD:
794 case QXmlStreamReader::EntityReference:
796 case QXmlStreamReader::ProcessingInstruction:
801 if (!document || reader.hasError()) {
802 if (document) D(document);
806 v8::Local<v8::Object> instance = xhrdata(engine)->newNode();
807 QDeclarativeDOMNodeResource *r = new QDeclarativeDOMNodeResource(engine);
809 instance->SetExternalResource(r);
810 instance->SetPrototype(Document::prototype(engine));
819 Node::Node(const Node &o)
830 bool Node::isNull() const
835 v8::Handle<v8::Value> NamedNodeMap::length(v8::Local<v8::String>, const v8::AccessorInfo &args)
837 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
838 if (!r) return v8::Undefined();
839 QV8Engine *engine = V8ENGINE();
841 return v8::Integer::New(r->list->count());
844 v8::Handle<v8::Value> NamedNodeMap::indexed(uint32_t index, const v8::AccessorInfo& args)
846 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
847 if (!r || !r->list) return v8::Undefined();
848 QV8Engine *engine = V8ENGINE();
850 if (index < r->list->count()) {
851 return Node::create(engine, r->list->at(index));
853 return v8::Undefined();
857 v8::Handle<v8::Value> NamedNodeMap::named(v8::Local<v8::String> property, const v8::AccessorInfo& args)
859 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
860 if (!r || !r->list) return v8::Undefined();
861 QV8Engine *engine = V8ENGINE();
863 QString str = engine->toString(property);
864 for (int ii = 0; ii < r->list->count(); ++ii) {
865 if (r->list->at(ii)->name == str) {
866 return Node::create(engine, r->list->at(ii));
870 return v8::Undefined();
873 v8::Handle<v8::Object> NamedNodeMap::prototype(QV8Engine *engine)
875 QDeclarativeXMLHttpRequestData *d = xhrdata(engine);
876 if (d->namedNodeMapPrototype.IsEmpty()) {
877 v8::Local<v8::ObjectTemplate> ot = v8::ObjectTemplate::New();
878 ot->SetAccessor(v8::String::New("length"), length, 0, v8::External::Wrap(engine));
879 ot->SetIndexedPropertyHandler(indexed, 0, 0, 0, 0, v8::External::Wrap(engine));
880 ot->SetFallbackPropertyHandler(named, 0, 0, 0, 0, v8::External::Wrap(engine));
881 d->namedNodeMapPrototype = qPersistentNew<v8::Object>(ot->NewInstance());
882 engine->freezeObject(d->namedNodeMapPrototype);
884 return d->namedNodeMapPrototype;
887 v8::Handle<v8::Value> NamedNodeMap::create(QV8Engine *engine, NodeImpl *data, QList<NodeImpl *> *list)
889 QDeclarativeXMLHttpRequestData *d = xhrdata(engine);
890 v8::Local<v8::Object> instance = d->newNode();
891 instance->SetPrototype(NamedNodeMap::prototype(engine));
892 QDeclarativeDOMNodeResource *r = new QDeclarativeDOMNodeResource(engine);
896 instance->SetExternalResource(r);
900 v8::Handle<v8::Value> NodeList::indexed(uint32_t index, const v8::AccessorInfo& args)
902 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
903 if (!r) return v8::Undefined();
904 QV8Engine *engine = V8ENGINE();
906 if (index < r->d->children.count()) {
907 return Node::create(engine, r->d->children.at(index));
909 return v8::Undefined();
913 v8::Handle<v8::Value> NodeList::length(v8::Local<v8::String>, const v8::AccessorInfo& args)
915 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
916 if (!r) return v8::Undefined();
917 QV8Engine *engine = V8ENGINE();
919 return v8::Integer::New(r->d->children.count());
922 v8::Handle<v8::Object> NodeList::prototype(QV8Engine *engine)
924 QDeclarativeXMLHttpRequestData *d = xhrdata(engine);
925 if (d->nodeListPrototype.IsEmpty()) {
926 v8::Local<v8::ObjectTemplate> ot = v8::ObjectTemplate::New();
927 ot->SetAccessor(v8::String::New("length"), length, 0, v8::External::Wrap(engine));
928 ot->SetIndexedPropertyHandler(indexed, 0, 0, 0, 0, v8::External::Wrap(engine));
929 d->nodeListPrototype = qPersistentNew<v8::Object>(ot->NewInstance());
930 engine->freezeObject(d->nodeListPrototype);
932 return d->nodeListPrototype;
935 v8::Handle<v8::Value> NodeList::create(QV8Engine *engine, NodeImpl *data)
937 QDeclarativeXMLHttpRequestData *d = xhrdata(engine);
938 v8::Local<v8::Object> instance = d->newNode();
939 instance->SetPrototype(NodeList::prototype(engine));
940 QDeclarativeDOMNodeResource *r = new QDeclarativeDOMNodeResource(engine);
943 instance->SetExternalResource(r);
947 v8::Handle<v8::Value> Document::documentElement(v8::Local<v8::String>, const v8::AccessorInfo& args)
949 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
950 if (!r || r->d->type != NodeImpl::Document) return v8::Undefined();
951 QV8Engine *engine = V8ENGINE();
953 return Node::create(engine, static_cast<DocumentImpl *>(r->d)->root);
956 v8::Handle<v8::Value> Document::xmlStandalone(v8::Local<v8::String>, const v8::AccessorInfo& args)
958 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
959 if (!r || r->d->type != NodeImpl::Document) return v8::Undefined();
960 QV8Engine *engine = V8ENGINE();
962 return v8::Boolean::New(static_cast<DocumentImpl *>(r->d)->isStandalone);
965 v8::Handle<v8::Value> Document::xmlVersion(v8::Local<v8::String>, const v8::AccessorInfo& args)
967 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
968 if (!r || r->d->type != NodeImpl::Document) return v8::Undefined();
969 QV8Engine *engine = V8ENGINE();
971 return engine->toString(static_cast<DocumentImpl *>(r->d)->version);
974 v8::Handle<v8::Value> Document::xmlEncoding(v8::Local<v8::String>, const v8::AccessorInfo& args)
976 QDeclarativeDOMNodeResource *r = v8_resource_cast<QDeclarativeDOMNodeResource>(args.This());
977 if (!r || r->d->type != NodeImpl::Document) return v8::Undefined();
978 QV8Engine *engine = V8ENGINE();
980 return engine->toString(static_cast<DocumentImpl *>(r->d)->encoding);
983 class QDeclarativeXMLHttpRequest : public QObject, public QV8ObjectResource
986 V8_RESOURCE_TYPE(XMLHttpRequestType)
988 enum State { Unsent = 0,
989 Opened = 1, HeadersReceived = 2,
990 Loading = 3, Done = 4 };
992 QDeclarativeXMLHttpRequest(QV8Engine *engine, QNetworkAccessManager *manager);
993 virtual ~QDeclarativeXMLHttpRequest();
995 bool sendFlag() const;
996 bool errorFlag() const;
997 quint32 readyState() const;
998 int replyStatus() const;
999 QString replyStatusText() const;
1001 v8::Handle<v8::Value> open(v8::Handle<v8::Object> me, const QString &, const QUrl &);
1002 v8::Handle<v8::Value> send(v8::Handle<v8::Object> me, const QByteArray &);
1003 v8::Handle<v8::Value> abort(v8::Handle<v8::Object> me);
1005 void addHeader(const QString &, const QString &);
1006 QString header(const QString &name);
1010 QString responseBody();
1011 const QByteArray & rawResponseBody() const;
1012 bool receivedXml() const;
1014 void downloadProgress(qint64);
1015 void error(QNetworkReply::NetworkError);
1019 void requestFromUrl(const QUrl &url);
1026 QByteArray m_responseEntityBody;
1028 int m_redirectCount;
1030 typedef QPair<QByteArray, QByteArray> HeaderPair;
1031 typedef QList<HeaderPair> HeadersList;
1032 HeadersList m_headersList;
1033 void fillHeadersList();
1037 QByteArray m_charset;
1038 QTextCodec *m_textCodec;
1039 #ifndef QT_NO_TEXTCODEC
1040 QTextCodec* findTextCodec() const;
1042 void readEncoding();
1044 v8::Handle<v8::Object> getMe() const;
1045 void setMe(v8::Handle<v8::Object> me);
1046 v8::Persistent<v8::Object> m_me;
1048 void dispatchCallback(v8::Handle<v8::Object> me);
1049 void printError(v8::Handle<v8::Message>);
1052 QString m_statusText;
1053 QNetworkRequest m_request;
1054 QDeclarativeGuard<QNetworkReply> m_network;
1055 void destroyNetwork();
1057 QNetworkAccessManager *m_nam;
1058 QNetworkAccessManager *networkAccessManager() { return m_nam; }
1061 QDeclarativeXMLHttpRequest::QDeclarativeXMLHttpRequest(QV8Engine *engine, QNetworkAccessManager *manager)
1062 : QV8ObjectResource(engine), m_state(Unsent), m_errorFlag(false), m_sendFlag(false),
1063 m_redirectCount(0), m_gotXml(false), m_textCodec(0), m_network(0), m_nam(manager)
1067 QDeclarativeXMLHttpRequest::~QDeclarativeXMLHttpRequest()
1072 bool QDeclarativeXMLHttpRequest::sendFlag() const
1077 bool QDeclarativeXMLHttpRequest::errorFlag() const
1082 quint32 QDeclarativeXMLHttpRequest::readyState() const
1087 int QDeclarativeXMLHttpRequest::replyStatus() const
1092 QString QDeclarativeXMLHttpRequest::replyStatusText() const
1094 return m_statusText;
1097 v8::Handle<v8::Value> QDeclarativeXMLHttpRequest::open(v8::Handle<v8::Object> me, const QString &method,
1102 m_errorFlag = false;
1103 m_responseEntityBody = QByteArray();
1107 dispatchCallback(me);
1108 return v8::Undefined();
1111 void QDeclarativeXMLHttpRequest::addHeader(const QString &name, const QString &value)
1113 QByteArray utfname = name.toUtf8();
1115 if (m_request.hasRawHeader(utfname)) {
1116 m_request.setRawHeader(utfname, m_request.rawHeader(utfname) + ',' + value.toUtf8());
1118 m_request.setRawHeader(utfname, value.toUtf8());
1122 QString QDeclarativeXMLHttpRequest::header(const QString &name)
1124 QByteArray utfname = name.toLower().toUtf8();
1126 foreach (const HeaderPair &header, m_headersList) {
1127 if (header.first == utfname)
1128 return QString::fromUtf8(header.second);
1133 QString QDeclarativeXMLHttpRequest::headers()
1137 foreach (const HeaderPair &header, m_headersList) {
1139 ret.append(QLatin1String("\r\n"));
1140 ret = ret % QString::fromUtf8(header.first) % QLatin1String(": ")
1141 % QString::fromUtf8(header.second);
1146 void QDeclarativeXMLHttpRequest::fillHeadersList()
1148 QList<QByteArray> headerList = m_network->rawHeaderList();
1150 m_headersList.clear();
1151 foreach (const QByteArray &header, headerList) {
1152 HeaderPair pair (header.toLower(), m_network->rawHeader(header));
1153 if (pair.first == "set-cookie" ||
1154 pair.first == "set-cookie2")
1157 m_headersList << pair;
1161 void QDeclarativeXMLHttpRequest::requestFromUrl(const QUrl &url)
1163 QNetworkRequest request = m_request;
1164 request.setUrl(url);
1165 if(m_method == QLatin1String("POST") ||
1166 m_method == QLatin1String("PUT")) {
1167 QVariant var = request.header(QNetworkRequest::ContentTypeHeader);
1168 if (var.isValid()) {
1169 QString str = var.toString();
1170 int charsetIdx = str.indexOf(QLatin1String("charset="));
1171 if (charsetIdx == -1) {
1172 // No charset - append
1173 if (!str.isEmpty()) str.append(QLatin1Char(';'));
1174 str.append(QLatin1String("charset=UTF-8"));
1178 int semiColon = str.indexOf(QLatin1Char(';'), charsetIdx);
1179 if (semiColon == -1) {
1180 n = str.length() - charsetIdx;
1182 n = semiColon - charsetIdx;
1185 str.replace(charsetIdx, n, QLatin1String("UTF-8"));
1187 request.setHeader(QNetworkRequest::ContentTypeHeader, str);
1189 request.setHeader(QNetworkRequest::ContentTypeHeader,
1190 QLatin1String("text/plain;charset=UTF-8"));
1195 qWarning().nospace() << "XMLHttpRequest: " << qPrintable(m_method) << " " << qPrintable(url.toString());
1196 if (!m_data.isEmpty()) {
1197 qWarning().nospace() << " "
1198 << qPrintable(QString::fromUtf8(m_data));
1202 if (m_method == QLatin1String("GET"))
1203 m_network = networkAccessManager()->get(request);
1204 else if (m_method == QLatin1String("HEAD"))
1205 m_network = networkAccessManager()->head(request);
1206 else if (m_method == QLatin1String("POST"))
1207 m_network = networkAccessManager()->post(request, m_data);
1208 else if (m_method == QLatin1String("PUT"))
1209 m_network = networkAccessManager()->put(request, m_data);
1210 else if (m_method == QLatin1String("DELETE"))
1211 m_network = networkAccessManager()->deleteResource(request);
1213 QObject::connect(m_network, SIGNAL(downloadProgress(qint64,qint64)),
1214 this, SLOT(downloadProgress(qint64)));
1215 QObject::connect(m_network, SIGNAL(error(QNetworkReply::NetworkError)),
1216 this, SLOT(error(QNetworkReply::NetworkError)));
1217 QObject::connect(m_network, SIGNAL(finished()),
1218 this, SLOT(finished()));
1221 v8::Handle<v8::Value> QDeclarativeXMLHttpRequest::send(v8::Handle<v8::Object> me, const QByteArray &data)
1223 m_errorFlag = false;
1225 m_redirectCount = 0;
1230 requestFromUrl(m_url);
1232 return v8::Undefined();
1235 v8::Handle<v8::Value> QDeclarativeXMLHttpRequest::abort(v8::Handle<v8::Object> me)
1238 m_responseEntityBody = QByteArray();
1240 m_request = QNetworkRequest();
1242 if (!(m_state == Unsent ||
1243 (m_state == Opened && !m_sendFlag) ||
1248 dispatchCallback(me);
1253 return v8::Undefined();
1256 v8::Handle<v8::Object> QDeclarativeXMLHttpRequest::getMe() const
1261 void QDeclarativeXMLHttpRequest::setMe(v8::Handle<v8::Object> me)
1263 qPersistentDispose(m_me);
1266 m_me = qPersistentNew<v8::Object>(me);
1269 void QDeclarativeXMLHttpRequest::downloadProgress(qint64 bytes)
1271 v8::HandleScope handle_scope;
1275 m_network->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
1277 QString::fromUtf8(m_network->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray());
1279 // ### We assume if this is called the headers are now available
1280 if (m_state < HeadersReceived) {
1281 m_state = HeadersReceived;
1284 dispatchCallback(m_me);
1285 if (tc.HasCaught()) printError(tc.Message());
1288 bool wasEmpty = m_responseEntityBody.isEmpty();
1289 m_responseEntityBody.append(m_network->readAll());
1290 if (wasEmpty && !m_responseEntityBody.isEmpty()) {
1293 dispatchCallback(m_me);
1294 if (tc.HasCaught()) printError(tc.Message());
1298 static const char *errorToString(QNetworkReply::NetworkError error)
1300 int idx = QNetworkReply::staticMetaObject.indexOfEnumerator("NetworkError");
1301 if (idx == -1) return "EnumLookupFailed";
1303 QMetaEnum e = QNetworkReply::staticMetaObject.enumerator(idx);
1305 const char *name = e.valueToKey(error);
1306 if (!name) return "EnumLookupFailed";
1310 void QDeclarativeXMLHttpRequest::error(QNetworkReply::NetworkError error)
1312 v8::HandleScope handle_scope;
1316 m_network->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
1318 QString::fromUtf8(m_network->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray());
1320 m_responseEntityBody = QByteArray();
1322 m_request = QNetworkRequest();
1327 qWarning().nospace() << "XMLHttpRequest: ERROR " << qPrintable(m_url.toString());
1328 qWarning().nospace() << " " << error << " " << errorToString(error) << " " << m_statusText;
1331 if (error == QNetworkReply::ContentAccessDenied ||
1332 error == QNetworkReply::ContentOperationNotPermittedError ||
1333 error == QNetworkReply::ContentNotFoundError ||
1334 error == QNetworkReply::AuthenticationRequiredError ||
1335 error == QNetworkReply::ContentReSendError) {
1338 dispatchCallback(m_me);
1339 if (tc.HasCaught()) printError(tc.Message());
1347 dispatchCallback(m_me);
1348 if (tc.HasCaught()) printError(tc.Message());
1351 #define XMLHTTPREQUEST_MAXIMUM_REDIRECT_RECURSION 15
1352 void QDeclarativeXMLHttpRequest::finished()
1354 v8::HandleScope handle_scope;
1357 if (m_redirectCount < XMLHTTPREQUEST_MAXIMUM_REDIRECT_RECURSION) {
1358 QVariant redirect = m_network->attribute(QNetworkRequest::RedirectionTargetAttribute);
1359 if (redirect.isValid()) {
1360 QUrl url = m_network->url().resolved(redirect.toUrl());
1362 requestFromUrl(url);
1368 m_network->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
1370 QString::fromUtf8(m_network->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray());
1372 if (m_state < HeadersReceived) {
1373 m_state = HeadersReceived;
1376 dispatchCallback(m_me);
1377 if (tc.HasCaught()) printError(tc.Message());
1379 m_responseEntityBody.append(m_network->readAll());
1383 qWarning().nospace() << "XMLHttpRequest: RESPONSE " << qPrintable(m_url.toString());
1384 if (!m_responseEntityBody.isEmpty()) {
1385 qWarning().nospace() << " "
1386 << qPrintable(QString::fromUtf8(m_responseEntityBody));
1393 if (m_state < Loading) {
1396 dispatchCallback(m_me);
1397 if (tc.HasCaught()) printError(tc.Message());
1402 dispatchCallback(m_me);
1403 if (tc.HasCaught()) printError(tc.Message());
1405 setMe(v8::Handle<v8::Object>());
1409 void QDeclarativeXMLHttpRequest::readEncoding()
1411 foreach (const HeaderPair &header, m_headersList) {
1412 if (header.first == "content-type") {
1413 int separatorIdx = header.second.indexOf(';');
1414 if (separatorIdx == -1) {
1415 m_mime == header.second;
1417 m_mime = header.second.mid(0, separatorIdx);
1418 int charsetIdx = header.second.indexOf("charset=");
1419 if (charsetIdx != -1) {
1421 separatorIdx = header.second.indexOf(';', charsetIdx);
1422 m_charset = header.second.mid(charsetIdx, separatorIdx >= 0 ? separatorIdx : header.second.length());
1429 if (m_mime.isEmpty() || m_mime == "text/xml" || m_mime == "application/xml" || m_mime.endsWith("+xml"))
1433 bool QDeclarativeXMLHttpRequest::receivedXml() const
1439 #ifndef QT_NO_TEXTCODEC
1440 QTextCodec* QDeclarativeXMLHttpRequest::findTextCodec() const
1442 QTextCodec *codec = 0;
1444 if (!m_charset.isEmpty())
1445 codec = QTextCodec::codecForName(m_charset);
1447 if (!codec && m_gotXml) {
1448 QXmlStreamReader reader(m_responseEntityBody);
1450 codec = QTextCodec::codecForName(reader.documentEncoding().toString().toUtf8());
1453 if (!codec && m_mime == "text/html")
1454 codec = QTextCodec::codecForHtml(m_responseEntityBody, 0);
1457 codec = QTextCodec::codecForUtfText(m_responseEntityBody, 0);
1460 codec = QTextCodec::codecForName("UTF-8");
1466 QString QDeclarativeXMLHttpRequest::responseBody()
1468 #ifndef QT_NO_TEXTCODEC
1470 m_textCodec = findTextCodec();
1472 return m_textCodec->toUnicode(m_responseEntityBody);
1475 return QString::fromUtf8(m_responseEntityBody);
1478 const QByteArray &QDeclarativeXMLHttpRequest::rawResponseBody() const
1480 return m_responseEntityBody;
1483 // Requires a TryCatch scope
1484 void QDeclarativeXMLHttpRequest::dispatchCallback(v8::Handle<v8::Object> me)
1486 v8::Local<v8::Value> callback = me->Get(v8::String::New("onreadystatechange"));
1487 if (callback->IsFunction()) {
1488 v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(callback);
1494 // Must have a handle scope
1495 void QDeclarativeXMLHttpRequest::printError(v8::Handle<v8::Message> message)
1497 v8::Context::Scope scope(engine->context());
1499 QDeclarativeError error;
1500 QDeclarativeExpressionPrivate::exceptionToError(message, error);
1501 QDeclarativeEnginePrivate::warning(QDeclarativeEnginePrivate::get(engine->engine()), error);
1504 void QDeclarativeXMLHttpRequest::destroyNetwork()
1507 m_network->disconnect();
1508 m_network->deleteLater();
1513 // XMLHttpRequest methods
1514 static v8::Handle<v8::Value> qmlxmlhttprequest_open(const v8::Arguments &args)
1516 QDeclarativeXMLHttpRequest *r = v8_resource_cast<QDeclarativeXMLHttpRequest>(args.This());
1518 V8THROW_REFERENCE("Not an XMLHttpRequest object");
1520 if (args.Length() < 2 || args.Length() > 5)
1521 V8THROW_DOM(SYNTAX_ERR, "Incorrect argument count");
1523 QV8Engine *engine = r->engine;
1525 // Argument 0 - Method
1526 QString method = engine->toString(args[0]).toUpper();
1527 if (method != QLatin1String("GET") &&
1528 method != QLatin1String("PUT") &&
1529 method != QLatin1String("HEAD") &&
1530 method != QLatin1String("POST") &&
1531 method != QLatin1String("DELETE"))
1532 V8THROW_DOM(SYNTAX_ERR, "Unsupported HTTP method type");
1535 QUrl url = QUrl::fromEncoded(engine->toString(args[1]).toUtf8());
1537 if (url.isRelative())
1538 url = engine->callingContext()->resolvedUrl(url);
1540 // Argument 2 - async (optional)
1541 if (args.Length() > 2 && !args[2]->BooleanValue())
1542 V8THROW_DOM(NOT_SUPPORTED_ERR, "Synchronous XMLHttpRequest calls are not supported");
1544 // Argument 3/4 - user/pass (optional)
1545 QString username, password;
1546 if (args.Length() > 3)
1547 username = engine->toString(args[3]);
1548 if (args.Length() > 4)
1549 password = engine->toString(args[4]);
1551 // Clear the fragment (if any)
1552 url.setFragment(QString());
1554 // Set username/password
1555 if (!username.isNull()) url.setUserName(username);
1556 if (!password.isNull()) url.setPassword(password);
1558 return r->open(args.This(), method, url);
1561 static v8::Handle<v8::Value> qmlxmlhttprequest_setRequestHeader(const v8::Arguments &args)
1563 QDeclarativeXMLHttpRequest *r = v8_resource_cast<QDeclarativeXMLHttpRequest>(args.This());
1565 V8THROW_REFERENCE("Not an XMLHttpRequest object");
1567 if (args.Length() != 2)
1568 V8THROW_DOM(SYNTAX_ERR, "Incorrect argument count");
1570 if (r->readyState() != QDeclarativeXMLHttpRequest::Opened || r->sendFlag())
1571 V8THROW_DOM(INVALID_STATE_ERR, "Invalid state");
1573 QV8Engine *engine = r->engine;
1575 QString name = engine->toString(args[0]);
1576 QString value = engine->toString(args[1]);
1578 // ### Check that name and value are well formed
1580 QString nameUpper = name.toUpper();
1581 if (nameUpper == QLatin1String("ACCEPT-CHARSET") ||
1582 nameUpper == QLatin1String("ACCEPT-ENCODING") ||
1583 nameUpper == QLatin1String("CONNECTION") ||
1584 nameUpper == QLatin1String("CONTENT-LENGTH") ||
1585 nameUpper == QLatin1String("COOKIE") ||
1586 nameUpper == QLatin1String("COOKIE2") ||
1587 nameUpper == QLatin1String("CONTENT-TRANSFER-ENCODING") ||
1588 nameUpper == QLatin1String("DATE") ||
1589 nameUpper == QLatin1String("EXPECT") ||
1590 nameUpper == QLatin1String("HOST") ||
1591 nameUpper == QLatin1String("KEEP-ALIVE") ||
1592 nameUpper == QLatin1String("REFERER") ||
1593 nameUpper == QLatin1String("TE") ||
1594 nameUpper == QLatin1String("TRAILER") ||
1595 nameUpper == QLatin1String("TRANSFER-ENCODING") ||
1596 nameUpper == QLatin1String("UPGRADE") ||
1597 nameUpper == QLatin1String("USER-AGENT") ||
1598 nameUpper == QLatin1String("VIA") ||
1599 nameUpper.startsWith(QLatin1String("PROXY-")) ||
1600 nameUpper.startsWith(QLatin1String("SEC-")))
1601 return v8::Undefined();
1603 r->addHeader(nameUpper, value);
1605 return v8::Undefined();
1608 static v8::Handle<v8::Value> qmlxmlhttprequest_send(const v8::Arguments &args)
1610 QDeclarativeXMLHttpRequest *r = v8_resource_cast<QDeclarativeXMLHttpRequest>(args.This());
1612 V8THROW_REFERENCE("Not an XMLHttpRequest object");
1614 QV8Engine *engine = r->engine;
1616 if (r->readyState() != QDeclarativeXMLHttpRequest::Opened ||
1618 V8THROW_DOM(INVALID_STATE_ERR, "Invalid state");
1621 if (args.Length() > 0)
1622 data = engine->toString(args[0]).toUtf8();
1624 return r->send(args.This(), data);
1627 static v8::Handle<v8::Value> qmlxmlhttprequest_abort(const v8::Arguments &args)
1629 QDeclarativeXMLHttpRequest *r = v8_resource_cast<QDeclarativeXMLHttpRequest>(args.This());
1631 V8THROW_REFERENCE("Not an XMLHttpRequest object");
1633 return r->abort(args.This());
1636 static v8::Handle<v8::Value> qmlxmlhttprequest_getResponseHeader(const v8::Arguments &args)
1638 QDeclarativeXMLHttpRequest *r = v8_resource_cast<QDeclarativeXMLHttpRequest>(args.This());
1640 V8THROW_REFERENCE("Not an XMLHttpRequest object");
1642 QV8Engine *engine = r->engine;
1644 if (args.Length() != 1)
1645 V8THROW_DOM(SYNTAX_ERR, "Incorrect argument count");
1647 if (r->readyState() != QDeclarativeXMLHttpRequest::Loading &&
1648 r->readyState() != QDeclarativeXMLHttpRequest::Done &&
1649 r->readyState() != QDeclarativeXMLHttpRequest::HeadersReceived)
1650 V8THROW_DOM(INVALID_STATE_ERR, "Invalid state");
1652 return engine->toString(r->header(engine->toString(args[0])));
1655 static v8::Handle<v8::Value> qmlxmlhttprequest_getAllResponseHeaders(const v8::Arguments &args)
1657 QDeclarativeXMLHttpRequest *r = v8_resource_cast<QDeclarativeXMLHttpRequest>(args.This());
1659 V8THROW_REFERENCE("Not an XMLHttpRequest object");
1661 QV8Engine *engine = r->engine;
1663 if (args.Length() != 0)
1664 V8THROW_DOM(SYNTAX_ERR, "Incorrect argument count");
1666 if (r->readyState() != QDeclarativeXMLHttpRequest::Loading &&
1667 r->readyState() != QDeclarativeXMLHttpRequest::Done &&
1668 r->readyState() != QDeclarativeXMLHttpRequest::HeadersReceived)
1669 V8THROW_DOM(INVALID_STATE_ERR, "Invalid state");
1671 return engine->toString(r->headers());
1674 // XMLHttpRequest properties
1675 static v8::Handle<v8::Value> qmlxmlhttprequest_readyState(v8::Local<v8::String> property,
1676 const v8::AccessorInfo& info)
1678 QDeclarativeXMLHttpRequest *r = v8_resource_cast<QDeclarativeXMLHttpRequest>(info.This());
1680 V8THROW_REFERENCE("Not an XMLHttpRequest object");
1682 return v8::Integer::NewFromUnsigned(r->readyState());
1685 static v8::Handle<v8::Value> qmlxmlhttprequest_status(v8::Local<v8::String> property,
1686 const v8::AccessorInfo& info)
1688 QDeclarativeXMLHttpRequest *r = v8_resource_cast<QDeclarativeXMLHttpRequest>(info.This());
1690 V8THROW_REFERENCE("Not an XMLHttpRequest object");
1692 if (r->readyState() == QDeclarativeXMLHttpRequest::Unsent ||
1693 r->readyState() == QDeclarativeXMLHttpRequest::Opened)
1694 V8THROW_DOM(INVALID_STATE_ERR, "Invalid state");
1697 return v8::Integer::New(0);
1699 return v8::Integer::New(r->replyStatus());
1702 static v8::Handle<v8::Value> qmlxmlhttprequest_statusText(v8::Local<v8::String> property,
1703 const v8::AccessorInfo& info)
1705 QDeclarativeXMLHttpRequest *r = v8_resource_cast<QDeclarativeXMLHttpRequest>(info.This());
1707 V8THROW_REFERENCE("Not an XMLHttpRequest object");
1709 QV8Engine *engine = r->engine;
1711 if (r->readyState() == QDeclarativeXMLHttpRequest::Unsent ||
1712 r->readyState() == QDeclarativeXMLHttpRequest::Opened)
1713 V8THROW_DOM(INVALID_STATE_ERR, "Invalid state");
1716 return engine->toString(QString());
1718 return engine->toString(r->replyStatusText());
1721 static v8::Handle<v8::Value> qmlxmlhttprequest_responseText(v8::Local<v8::String> property,
1722 const v8::AccessorInfo& info)
1724 QDeclarativeXMLHttpRequest *r = v8_resource_cast<QDeclarativeXMLHttpRequest>(info.This());
1726 V8THROW_REFERENCE("Not an XMLHttpRequest object");
1728 QV8Engine *engine = r->engine;
1730 if (r->readyState() != QDeclarativeXMLHttpRequest::Loading &&
1731 r->readyState() != QDeclarativeXMLHttpRequest::Done)
1732 return engine->toString(QString());
1734 return engine->toString(r->responseBody());
1737 static v8::Handle<v8::Value> qmlxmlhttprequest_responseXML(v8::Local<v8::String> property,
1738 const v8::AccessorInfo& info)
1740 QDeclarativeXMLHttpRequest *r = v8_resource_cast<QDeclarativeXMLHttpRequest>(info.This());
1742 V8THROW_REFERENCE("Not an XMLHttpRequest object");
1744 if (!r->receivedXml() ||
1745 (r->readyState() != QDeclarativeXMLHttpRequest::Loading &&
1746 r->readyState() != QDeclarativeXMLHttpRequest::Done)) {
1749 return Document::load(r->engine, r->rawResponseBody());
1753 static v8::Handle<v8::Value> qmlxmlhttprequest_new(const v8::Arguments &args)
1755 if (args.IsConstructCall()) {
1756 QV8Engine *engine = V8ENGINE();
1757 QDeclarativeEnginePrivate *ep = QDeclarativeEnginePrivate::get(engine->engine());
1759 QDeclarativeXMLHttpRequest *r = new QDeclarativeXMLHttpRequest(engine, engine->networkAccessManager());
1760 args.This()->SetExternalResource(r);
1764 return v8::Undefined();
1768 #define NEWFUNCTION(function) v8::FunctionTemplate::New(function)->GetFunction()
1770 void qt_rem_qmlxmlhttprequest(QV8Engine *engine, void *d)
1772 QDeclarativeXMLHttpRequestData *data = (QDeclarativeXMLHttpRequestData *)d;
1776 void *qt_add_qmlxmlhttprequest(QV8Engine *engine)
1778 v8::PropertyAttribute attributes = (v8::PropertyAttribute)(v8::ReadOnly | v8::DontEnum | v8::DontDelete);
1781 v8::Local<v8::FunctionTemplate> xmlhttprequest = v8::FunctionTemplate::New(qmlxmlhttprequest_new,
1782 v8::External::Wrap(engine));
1783 xmlhttprequest->InstanceTemplate()->SetHasExternalResource(true);
1786 xmlhttprequest->PrototypeTemplate()->Set(v8::String::New("open"), NEWFUNCTION(qmlxmlhttprequest_open), attributes);
1787 xmlhttprequest->PrototypeTemplate()->Set(v8::String::New("setRequestHeader"), NEWFUNCTION(qmlxmlhttprequest_setRequestHeader), attributes);
1788 xmlhttprequest->PrototypeTemplate()->Set(v8::String::New("send"), NEWFUNCTION(qmlxmlhttprequest_send), attributes);
1789 xmlhttprequest->PrototypeTemplate()->Set(v8::String::New("abort"), NEWFUNCTION(qmlxmlhttprequest_abort), attributes);
1790 xmlhttprequest->PrototypeTemplate()->Set(v8::String::New("getResponseHeader"), NEWFUNCTION(qmlxmlhttprequest_getResponseHeader), attributes);
1791 xmlhttprequest->PrototypeTemplate()->Set(v8::String::New("getAllResponseHeaders"), NEWFUNCTION(qmlxmlhttprequest_getAllResponseHeaders), attributes);
1793 // Read-only properties
1794 xmlhttprequest->PrototypeTemplate()->SetAccessor(v8::String::New("readyState"), qmlxmlhttprequest_readyState, 0, v8::Handle<v8::Value>(), v8::DEFAULT, attributes);
1795 xmlhttprequest->PrototypeTemplate()->SetAccessor(v8::String::New("status"),qmlxmlhttprequest_status, 0, v8::Handle<v8::Value>(), v8::DEFAULT, attributes);
1796 xmlhttprequest->PrototypeTemplate()->SetAccessor(v8::String::New("statusText"),qmlxmlhttprequest_statusText, 0, v8::Handle<v8::Value>(), v8::DEFAULT, attributes);
1797 xmlhttprequest->PrototypeTemplate()->SetAccessor(v8::String::New("responseText"),qmlxmlhttprequest_responseText, 0, v8::Handle<v8::Value>(), v8::DEFAULT, attributes);
1798 xmlhttprequest->PrototypeTemplate()->SetAccessor(v8::String::New("responseXML"),qmlxmlhttprequest_responseXML, 0, v8::Handle<v8::Value>(), v8::DEFAULT, attributes);
1801 xmlhttprequest->PrototypeTemplate()->Set(v8::String::New("UNSENT"), v8::Integer::New(0), attributes);
1802 xmlhttprequest->PrototypeTemplate()->Set(v8::String::New("OPENED"), v8::Integer::New(1), attributes);
1803 xmlhttprequest->PrototypeTemplate()->Set(v8::String::New("HEADERS_RECEIVED"), v8::Integer::New(2), attributes);
1804 xmlhttprequest->PrototypeTemplate()->Set(v8::String::New("LOADING"), v8::Integer::New(3), attributes);
1805 xmlhttprequest->PrototypeTemplate()->Set(v8::String::New("DONE"), v8::Integer::New(4), attributes);
1808 xmlhttprequest->Set(v8::String::New("UNSENT"), v8::Integer::New(0), attributes);
1809 xmlhttprequest->Set(v8::String::New("OPENED"), v8::Integer::New(1), attributes);
1810 xmlhttprequest->Set(v8::String::New("HEADERS_RECEIVED"), v8::Integer::New(2), attributes);
1811 xmlhttprequest->Set(v8::String::New("LOADING"), v8::Integer::New(3), attributes);
1812 xmlhttprequest->Set(v8::String::New("DONE"), v8::Integer::New(4), attributes);
1813 engine->global()->Set(v8::String::New("XMLHttpRequest"), xmlhttprequest->GetFunction());
1816 v8::Local<v8::Object> domexception = v8::Object::New();
1817 domexception->Set(v8::String::New("INDEX_SIZE_ERR"), v8::Integer::New(INDEX_SIZE_ERR), attributes);
1818 domexception->Set(v8::String::New("DOMSTRING_SIZE_ERR"), v8::Integer::New(DOMSTRING_SIZE_ERR), attributes);
1819 domexception->Set(v8::String::New("HIERARCHY_REQUEST_ERR"), v8::Integer::New(HIERARCHY_REQUEST_ERR), attributes);
1820 domexception->Set(v8::String::New("WRONG_DOCUMENT_ERR"), v8::Integer::New(WRONG_DOCUMENT_ERR), attributes);
1821 domexception->Set(v8::String::New("INVALID_CHARACTER_ERR"), v8::Integer::New(INVALID_CHARACTER_ERR), attributes);
1822 domexception->Set(v8::String::New("NO_DATA_ALLOWED_ERR"), v8::Integer::New(NO_DATA_ALLOWED_ERR), attributes);
1823 domexception->Set(v8::String::New("NO_MODIFICATION_ALLOWED_ERR"), v8::Integer::New(NO_MODIFICATION_ALLOWED_ERR), attributes);
1824 domexception->Set(v8::String::New("NOT_FOUND_ERR"), v8::Integer::New(NOT_FOUND_ERR), attributes);
1825 domexception->Set(v8::String::New("NOT_SUPPORTED_ERR"), v8::Integer::New(NOT_SUPPORTED_ERR), attributes);
1826 domexception->Set(v8::String::New("INUSE_ATTRIBUTE_ERR"), v8::Integer::New(INUSE_ATTRIBUTE_ERR), attributes);
1827 domexception->Set(v8::String::New("INVALID_STATE_ERR"), v8::Integer::New(INVALID_STATE_ERR), attributes);
1828 domexception->Set(v8::String::New("SYNTAX_ERR"), v8::Integer::New(SYNTAX_ERR), attributes);
1829 domexception->Set(v8::String::New("INVALID_MODIFICATION_ERR"), v8::Integer::New(INVALID_MODIFICATION_ERR), attributes);
1830 domexception->Set(v8::String::New("NAMESPACE_ERR"), v8::Integer::New(NAMESPACE_ERR), attributes);
1831 domexception->Set(v8::String::New("INVALID_ACCESS_ERR"), v8::Integer::New(INVALID_ACCESS_ERR), attributes);
1832 domexception->Set(v8::String::New("VALIDATION_ERR"), v8::Integer::New(VALIDATION_ERR), attributes);
1833 domexception->Set(v8::String::New("TYPE_MISMATCH_ERR"), v8::Integer::New(TYPE_MISMATCH_ERR), attributes);
1834 engine->global()->Set(v8::String::New("DOMException"), domexception);
1836 QDeclarativeXMLHttpRequestData *data = new QDeclarativeXMLHttpRequestData;
1842 #endif // QT_NO_XMLSTREAMREADER
1844 #include <qdeclarativexmlhttprequest.moc>