Files
palemoon27/dom/base/FileReader.cpp
T
roytam1 2e02aab9a7 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1198458: Webrtc updated to branch 43; pull made 2015-09-29 09:00AM PDT rs=jesup (c45a789c99)
- Bug 1159489: WebRTC bitrate limits for video depend on input resolution and framerate r=pkerr (e3691a247c)
- Bug 1132318: merge SelectSendFrameRate with SelectSendResolution r=bwc (bcc232994c)
- Bug 1182289: Clean up dispatches in WebrtcGmpVideoEncoder/Decoder. r=jesup, a=abillings (b5e2030b07)
- Bug 1167306: Fix preprocessor goof that disabled the load manager and some preference handling. r=jesup (0cc0dee688)
- Bug 1198458: Rollup of changes previously applied to media/webrtc/trunk/webrtc and fixes to those rs=jesup r=froyd,jib,bwc,jesup,gcp,sotaro,pkerr,pehrsons (fe384d5e63)
- Bug 1198458 Unbreak build on BSDs by fixing non-POSIX thread includes/usage. r=jesup (4ad8e88c17)
- Bug 1198458: Fix typo in merges in OMX rs=bustage,kwierso on a CLOSED TREE (211b3b1a3f)
- Bug 1226146: fix sndio audio_device backend after webrtc 43 landing in bug 1198458 r=jesup NPOTB (2b10ba3e86)
- Bug 1231106 - Make BSDs fall-through to ASSERT as well. r=jesup (775d4fedae)
- Bug 1231109 - Drop FreeBSD checks for unsupported versions. r=jld r=jesup (3cd55166fd)
- Bug 1161079: Fix VideoCodecStats to allow for collecting encoder and decoder stats r=jib (1f98af8939)
- add limits to fix gcc12 compile (d78098980f)
- Bug 1193495 - Part 1: Test case. r=mt (add2ded009)
- Bug 1193495 - Part 2: Maintain clones of supported codecs for each level, and do necessary checking to prevent payload-type clashes. r=mt (d45a24dba7)
- Bug 1191301 - Re-enable the use of media.navigator.video.use_tmmbr pref. r=bwc (d2723821d4)
- Bug 1094447 - Use UDP/TLS/RTP/SAVPF for audio/video m-lines. r=drno (e8e1dafd0a)
- Bug 1173599 - a=imageattr support. r=mt (612fc343d7)
- Bug 1173601 - Add a=simulcast support. r=mt (7c5303bacb)
- Bug 1203246 - Factor track negotiation stuff out of JsepSessionImpl, and other simplification. r=mt (b71c809b78)
- Bug 1212907 - a=rid support. r=mt (7479ab6984)
- Bug 1212908 - Update a=simulcast to match new grammar in 03 draft. r=mt (e205d3b0dd)
- Bug 1192390 - Part 1: Lay architectural groundwork for simulcast negotiation. r=mt r=jesup (e75dda3139)
- Bug 1223160 - added SDP parser file reader. r=bwc (6752195791)
- Bug 1192390 - Part 2: Simulcast and RID negotiation. r=mt (51b151ef52)
- fix some warnings stuff (fed8f513a8)
- Bug 1161317: Fix bug where sendonly video RTCP would be treated as outgoing RTP r=jesup (e24371fbe0)
- Bug 1226347: Import cherry-pick of AEC changes from 43->48 (delay-agnostic AEC). r=pkerr (d3a074f4d8)
- Bug 1226347 - Part 2: Allow control of AEC via prefs. r=rjesup (58f142005b)
- Bug 1228788 - Force QT device release to happen on the main thread. r=jesup (885e9d1236)
- Bug 1162218 - Make worker idle thread timeouts more strict, r=baku. (a7d2106987)
- No bug. Remove a stray debugging printf of mine. r=me. (77b84cda62)
- minor (22564a666e)
- Bug 1224237 - Remove the !baseURL check from ServiceWorkerContainer::Register;r=bkelly (8b13c4dc49)
- Bug 1196157 - Marks left by performance marks should print the domain of the application and not the complete URL. r=baku (d133708d8d)
- Bug 1211970 - "Muted errors in workers are not correctly reported to the console". r=bz (42c15275f4)
- Bug 1208559 - Tests. r=bholley (e16a30caa5)
-  Bug 1045891 - Tests for child-src r=ckerschb (90aa832cd0)
- Bug 1223647: CSP erroneously inherited into dedicated workers. r=ckerschb (6fd8d9bfc9)
- Bug 1218433 - Use AsyncOpen2 in dom/workers/ScriptLoader.cpp - part 1, r=sicking (a7e9187e52)
- Bug 1218433 - Use AsyncOpen2 in dom/workers/ScriptLoader.cpp - part 3 - WPT, r=sicking, r=Ms2ger (e5e3c69f6a)
- Bug 1218433 - Use AsyncOpen2 in dom/workers/ScriptLoader.cpp - part 2 - WPT, r=sicking, r=Ms2ger (1dd2d871ec)
- Bug 1211967 - Fix how we report errors when loading a worker from a data url, r=bz (8517368daa)
- nsRefPtr - RefPtr (34bb404530)
- Bug 1231055 - Fix tags usage in PluginProvider. r=dtownsend (870b0e71eb)
- bug 1228792 - remove use of array comprehensions r=mossop (3e31f18e83)
- bug 1228792 - use standard version of catch r=mossop (f306557ca2)
- Bug 1228009. Geolocation code needs to handle failures on its ErrorResults. r=smaug (8778a9e264)
- Bug 1228707. Add a away to call Web IDL callbacks while ignoring any errors from them, and use it in a few places. r=smaug (a414e0d711)
- Bug 1201692. Add a fast path to ExplicitChildIterator::Seek for the common case of seeking an actual DOM child of the parent node. r=wchen (01234ad43a)
- Bug 1202186 - use nsISensitiveInfoHidden for console methods, r=baku (888b4506ad)
- Bug 1223774 - Console API should check if the outer window exists, r=smaug (e0d7f408dc)
- Bug 1200551 - Handle multiple %c formatters without a string between them by using only the last one for styling;r=baku,r=past (463550117a)
- Bug 1213719 - Back out bug 1170314 for duplicate functionality. r=smaug (ae74e0ad52)
- Bug 1154076 followup: Mark ConsoleRunnable::Run() as override. rs=ehsan (337181faab)
- Bug 1127703 - "Support iteration on FormData" r=bz (4ddd461e99)
- Bug 1230509 - BlobImplFile should return false in IsDateUnknown and IsSizeUnknown, r=bz (1079bfe2ab)
- Bug 1198095 - FileReader should dispatch an error if the blob changes size in the meantime the read is executed, r=bz (263993a172)
- Bug 1231094 - patch 1 - nsDOMFileReader to mozilla::dom::FileReader, r=sicking (aa8c3ff373)
- Bug 1231094 - patch 2 - Get rid of FileIOObject, r=sicking (44af1e17dd)
- Bug 1231100 - Get rid of nsIDOMFileReader - patch 1, r=sicking (c909d9d793)
- Bug 1231100 - Get rid of nsIDOMFileReader - patch 2, r=sicking (4d3da1c566)
- Bug 1161183: Don't show the add-on version in the list view. r=dao (002d8f6fb1)
- Bug 1229519: Fix toolkit/modules to pass eslint checks. r=mak (8bbd9c8fe0)
2023-04-06 15:48:27 +08:00

648 lines
17 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "FileReader.h"
#include "nsContentCID.h"
#include "nsContentUtils.h"
#include "nsDOMClassInfoID.h"
#include "nsError.h"
#include "nsIFile.h"
#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsXPCOM.h"
#include "nsIDOMEventListener.h"
#include "nsJSEnvironment.h"
#include "nsCycleCollectionParticipant.h"
#include "mozilla/Base64.h"
#include "mozilla/dom/EncodingUtils.h"
#include "mozilla/dom/File.h"
#include "mozilla/dom/FileReaderBinding.h"
#include "mozilla/dom/ProgressEvent.h"
#include "xpcpublic.h"
#include "nsDOMJSUtils.h"
#include "jsfriendapi.h"
#include "nsITransport.h"
#include "nsIStreamTransportService.h"
namespace mozilla {
namespace dom {
#define ABORT_STR "abort"
#define LOAD_STR "load"
#define LOADSTART_STR "loadstart"
#define LOADEND_STR "loadend"
#define ERROR_STR "error"
#define PROGRESS_STR "progress"
const uint64_t kUnknownSize = uint64_t(-1);
static NS_DEFINE_CID(kStreamTransportServiceCID, NS_STREAMTRANSPORTSERVICE_CID);
NS_IMPL_CYCLE_COLLECTION_CLASS(FileReader)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(FileReader,
DOMEventTargetHelper)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBlob)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mProgressNotifier)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mError)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(FileReader,
DOMEventTargetHelper)
tmp->mResultArrayBuffer = nullptr;
NS_IMPL_CYCLE_COLLECTION_UNLINK(mBlob)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mProgressNotifier)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mError)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(FileReader,
DOMEventTargetHelper)
NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mResultArrayBuffer)
NS_IMPL_CYCLE_COLLECTION_TRACE_END
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(FileReader)
NS_INTERFACE_MAP_ENTRY(nsITimerCallback)
NS_INTERFACE_MAP_ENTRY(nsIInputStreamCallback)
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
NS_IMPL_ADDREF_INHERITED(FileReader, DOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(FileReader, DOMEventTargetHelper)
void
FileReader::RootResultArrayBuffer()
{
mozilla::HoldJSObjects(this);
}
//FileReader constructors/initializers
FileReader::FileReader(nsPIDOMWindow* aWindow)
: DOMEventTargetHelper(aWindow)
, mFileData(nullptr)
, mDataLen(0)
, mDataFormat(FILE_AS_BINARY)
, mResultArrayBuffer(nullptr)
, mProgressEventWasDelayed(false)
, mTimerIsActive(false)
, mReadyState(EMPTY)
, mTotal(0)
, mTransferred(0)
{
SetDOMStringToNull(mResult);
}
FileReader::~FileReader()
{
FreeFileData();
mResultArrayBuffer = nullptr;
DropJSObjects(this);
}
/* static */ already_AddRefed<FileReader>
FileReader::Constructor(const GlobalObject& aGlobal, ErrorResult& aRv)
{
// The owner can be null when this object is used by chrome code.
nsCOMPtr<nsPIDOMWindow> owner = do_QueryInterface(aGlobal.GetAsSupports());
RefPtr<FileReader> fileReader = new FileReader(owner);
if (!owner && nsContentUtils::IsCallerChrome()) {
// Instead of grabbing some random global from the context stack,
// let's use the default one (junk scope) for now.
// We should move away from this Init...
fileReader->BindToOwner(xpc::NativeGlobal(xpc::PrivilegedJunkScope()));
}
return fileReader.forget();
}
// nsIInterfaceRequestor
NS_IMETHODIMP
FileReader::GetInterface(const nsIID & aIID, void **aResult)
{
return QueryInterface(aIID, aResult);
}
void
FileReader::GetResult(JSContext* aCx,
JS::MutableHandle<JS::Value> aResult,
ErrorResult& aRv)
{
JS::Rooted<JS::Value> result(aCx);
if (mDataFormat == FILE_AS_ARRAYBUFFER) {
if (mReadyState == DONE && mResultArrayBuffer) {
result.setObject(*mResultArrayBuffer);
} else {
result.setNull();
}
if (!JS_WrapValue(aCx, &result)) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
aResult.set(result);
return;
}
nsString tmpResult = mResult;
if (!xpc::StringToJsval(aCx, tmpResult, aResult)) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
}
static NS_IMETHODIMP
ReadFuncBinaryString(nsIInputStream* in,
void* closure,
const char* fromRawSegment,
uint32_t toOffset,
uint32_t count,
uint32_t *writeCount)
{
char16_t* dest = static_cast<char16_t*>(closure) + toOffset;
char16_t* end = dest + count;
const unsigned char* source = (const unsigned char*)fromRawSegment;
while (dest != end) {
*dest = *source;
++dest;
++source;
}
*writeCount = count;
return NS_OK;
}
nsresult
FileReader::DoOnLoadEnd(nsresult aStatus,
nsAString& aSuccessEvent,
nsAString& aTerminationEvent)
{
// Make sure we drop all the objects that could hold files open now.
nsCOMPtr<nsIAsyncInputStream> stream;
mAsyncStream.swap(stream);
RefPtr<Blob> blob;
mBlob.swap(blob);
// Clear out the data if necessary
if (NS_FAILED(aStatus)) {
FreeFileData();
return NS_OK;
}
// In case we read a different number of bytes, we can assume that the
// underlying storage has changed. We should not continue.
if (mDataLen != mTotal) {
DispatchError(NS_ERROR_FAILURE, aTerminationEvent);
FreeFileData();
return NS_ERROR_FAILURE;
}
aSuccessEvent = NS_LITERAL_STRING(LOAD_STR);
aTerminationEvent = NS_LITERAL_STRING(LOADEND_STR);
nsresult rv = NS_OK;
switch (mDataFormat) {
case FILE_AS_ARRAYBUFFER: {
AutoJSAPI jsapi;
if (NS_WARN_IF(!jsapi.Init(DOMEventTargetHelper::GetParentObject()))) {
FreeFileData();
return NS_ERROR_FAILURE;
}
RootResultArrayBuffer();
mResultArrayBuffer = JS_NewArrayBufferWithContents(jsapi.cx(), mDataLen, mFileData);
if (!mResultArrayBuffer) {
JS_ClearPendingException(jsapi.cx());
rv = NS_ERROR_OUT_OF_MEMORY;
} else {
mFileData = nullptr; // Transfer ownership
}
break;
}
case FILE_AS_BINARY:
break; //Already accumulated mResult
case FILE_AS_TEXT:
if (!mFileData) {
if (mDataLen) {
rv = NS_ERROR_OUT_OF_MEMORY;
break;
}
rv = GetAsText(blob, mCharset, "", mDataLen, mResult);
break;
}
rv = GetAsText(blob, mCharset, mFileData, mDataLen, mResult);
break;
case FILE_AS_DATAURL:
rv = GetAsDataURL(blob, mFileData, mDataLen, mResult);
break;
}
mResult.SetIsVoid(false);
FreeFileData();
return rv;
}
nsresult
FileReader::DoReadData(nsIAsyncInputStream* aStream, uint64_t aCount)
{
MOZ_ASSERT(aStream);
if (mDataFormat == FILE_AS_BINARY) {
//Continuously update our binary string as data comes in
uint32_t oldLen = mResult.Length();
NS_ASSERTION(mResult.Length() == mDataLen, "unexpected mResult length");
if (uint64_t(oldLen) + aCount > UINT32_MAX)
return NS_ERROR_OUT_OF_MEMORY;
char16_t *buf = nullptr;
mResult.GetMutableData(&buf, oldLen + aCount, fallible);
NS_ENSURE_TRUE(buf, NS_ERROR_OUT_OF_MEMORY);
uint32_t bytesRead = 0;
aStream->ReadSegments(ReadFuncBinaryString, buf + oldLen, aCount,
&bytesRead);
NS_ASSERTION(bytesRead == aCount, "failed to read data");
}
else {
//Update memory buffer to reflect the contents of the file
if (mDataLen + aCount > UINT32_MAX) {
// PR_Realloc doesn't support over 4GB memory size even if 64-bit OS
return NS_ERROR_OUT_OF_MEMORY;
}
if (mDataFormat != FILE_AS_ARRAYBUFFER) {
mFileData = (char *) moz_realloc(mFileData, mDataLen + aCount);
NS_ENSURE_TRUE(mFileData, NS_ERROR_OUT_OF_MEMORY);
}
uint32_t bytesRead = 0;
aStream->Read(mFileData + mDataLen, aCount, &bytesRead);
NS_ASSERTION(bytesRead == aCount, "failed to read data");
}
mDataLen += aCount;
return NS_OK;
}
// Helper methods
void
FileReader::ReadFileContent(Blob& aBlob,
const nsAString &aCharset,
eDataFormat aDataFormat,
ErrorResult& aRv)
{
//Implicit abort to clear any other activity going on
ErrorResult error;
Abort(error);
error.SuppressException();
mError = nullptr;
SetDOMStringToNull(mResult);
mTransferred = 0;
mTotal = 0;
mReadyState = EMPTY;
FreeFileData();
mBlob = &aBlob;
mDataFormat = aDataFormat;
CopyUTF16toUTF8(aCharset, mCharset);
nsresult rv;
nsCOMPtr<nsIStreamTransportService> sts =
do_GetService(kStreamTransportServiceCID, &rv);
if (NS_WARN_IF(NS_FAILED(rv))) {
aRv.Throw(rv);
return;
}
nsCOMPtr<nsIInputStream> stream;
mBlob->GetInternalStream(getter_AddRefs(stream), aRv);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
nsCOMPtr<nsITransport> transport;
aRv = sts->CreateInputTransport(stream,
/* aStartOffset */ 0,
/* aReadLimit */ -1,
/* aCloseWhenDone */ true,
getter_AddRefs(transport));
if (NS_WARN_IF(aRv.Failed())) {
return;
}
nsCOMPtr<nsIInputStream> wrapper;
aRv = transport->OpenInputStream(/* aFlags */ 0,
/* aSegmentSize */ 0,
/* aSegmentCount */ 0,
getter_AddRefs(wrapper));
if (NS_WARN_IF(aRv.Failed())) {
return;
}
MOZ_ASSERT(!mAsyncStream);
mAsyncStream = do_QueryInterface(wrapper);
MOZ_ASSERT(mAsyncStream);
mTotal = mBlob->GetSize(aRv);
if (NS_WARN_IF(aRv.Failed())) {
return;
}
aRv = mAsyncStream->AsyncWait(this,
/* aFlags*/ 0,
/* aRequestedCount */ 0,
NS_GetCurrentThread());
if (NS_WARN_IF(aRv.Failed())) {
return;
}
//FileReader should be in loading state here
mReadyState = LOADING;
DispatchProgressEvent(NS_LITERAL_STRING(LOADSTART_STR));
if (mDataFormat == FILE_AS_ARRAYBUFFER) {
mFileData = js_pod_malloc<char>(mTotal);
if (!mFileData) {
NS_WARNING("Preallocation failed for ReadFileData");
aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
}
}
}
nsresult
FileReader::GetAsText(Blob *aBlob,
const nsACString &aCharset,
const char *aFileData,
uint32_t aDataLen,
nsAString& aResult)
{
// The BOM sniffing is baked into the "decode" part of the Encoding
// Standard, which the File API references.
nsAutoCString encoding;
if (!nsContentUtils::CheckForBOM(
reinterpret_cast<const unsigned char *>(aFileData),
aDataLen,
encoding)) {
// BOM sniffing failed. Try the API argument.
if (!EncodingUtils::FindEncodingForLabel(aCharset,
encoding)) {
// API argument failed. Try the type property of the blob.
nsAutoString type16;
aBlob->GetType(type16);
NS_ConvertUTF16toUTF8 type(type16);
nsAutoCString specifiedCharset;
bool haveCharset;
int32_t charsetStart, charsetEnd;
NS_ExtractCharsetFromContentType(type,
specifiedCharset,
&haveCharset,
&charsetStart,
&charsetEnd);
if (!EncodingUtils::FindEncodingForLabel(specifiedCharset, encoding)) {
// Type property failed. Use UTF-8.
encoding.AssignLiteral("UTF-8");
}
}
}
nsDependentCSubstring data(aFileData, aDataLen);
return nsContentUtils::ConvertStringFromEncoding(encoding, data, aResult);
}
nsresult
FileReader::GetAsDataURL(Blob *aBlob,
const char *aFileData,
uint32_t aDataLen,
nsAString& aResult)
{
aResult.AssignLiteral("data:");
nsAutoString contentType;
aBlob->GetType(contentType);
if (!contentType.IsEmpty()) {
aResult.Append(contentType);
} else {
aResult.AppendLiteral("application/octet-stream");
}
aResult.AppendLiteral(";base64,");
nsCString encodedData;
nsresult rv = Base64Encode(Substring(aFileData, aDataLen), encodedData);
NS_ENSURE_SUCCESS(rv, rv);
if (!AppendASCIItoUTF16(encodedData, aResult, fallible)) {
return NS_ERROR_OUT_OF_MEMORY;
}
return NS_OK;
}
/* virtual */ JSObject*
FileReader::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
{
return FileReaderBinding::Wrap(aCx, this, aGivenProto);
}
void
FileReader::StartProgressEventTimer()
{
if (!mProgressNotifier) {
mProgressNotifier = do_CreateInstance(NS_TIMER_CONTRACTID);
}
if (mProgressNotifier) {
mProgressEventWasDelayed = false;
mTimerIsActive = true;
mProgressNotifier->Cancel();
mProgressNotifier->InitWithCallback(this, NS_PROGRESS_EVENT_INTERVAL,
nsITimer::TYPE_ONE_SHOT);
}
}
void
FileReader::ClearProgressEventTimer()
{
mProgressEventWasDelayed = false;
mTimerIsActive = false;
if (mProgressNotifier) {
mProgressNotifier->Cancel();
}
}
void
FileReader::DispatchError(nsresult rv, nsAString& finalEvent)
{
// Set the status attribute, and dispatch the error event
switch (rv) {
case NS_ERROR_FILE_NOT_FOUND:
mError = new DOMError(GetOwner(), NS_LITERAL_STRING("NotFoundError"));
break;
case NS_ERROR_FILE_ACCESS_DENIED:
mError = new DOMError(GetOwner(), NS_LITERAL_STRING("SecurityError"));
break;
default:
mError = new DOMError(GetOwner(), NS_LITERAL_STRING("NotReadableError"));
break;
}
// Dispatch error event to signify load failure
DispatchProgressEvent(NS_LITERAL_STRING(ERROR_STR));
DispatchProgressEvent(finalEvent);
}
nsresult
FileReader::DispatchProgressEvent(const nsAString& aType)
{
ProgressEventInit init;
init.mBubbles = false;
init.mCancelable = false;
init.mLoaded = mTransferred;
if (mTotal != kUnknownSize) {
init.mLengthComputable = true;
init.mTotal = mTotal;
} else {
init.mLengthComputable = false;
init.mTotal = 0;
}
RefPtr<ProgressEvent> event =
ProgressEvent::Constructor(this, aType, init);
event->SetTrusted(true);
return DispatchDOMEvent(nullptr, event, nullptr, nullptr);
}
// nsITimerCallback
NS_IMETHODIMP
FileReader::Notify(nsITimer* aTimer)
{
nsresult rv;
mTimerIsActive = false;
if (mProgressEventWasDelayed) {
rv = DispatchProgressEvent(NS_LITERAL_STRING("progress"));
NS_ENSURE_SUCCESS(rv, rv);
StartProgressEventTimer();
}
return NS_OK;
}
// InputStreamCallback
NS_IMETHODIMP
FileReader::OnInputStreamReady(nsIAsyncInputStream* aStream)
{
if (mReadyState != LOADING || aStream != mAsyncStream) {
return NS_OK;
}
uint64_t aCount;
nsresult rv = aStream->Available(&aCount);
if (NS_SUCCEEDED(rv) && aCount) {
rv = DoReadData(aStream, aCount);
}
if (NS_SUCCEEDED(rv)) {
rv = aStream->AsyncWait(this,
/* aFlags*/ 0,
/* aRequestedCount */ 0,
NS_GetCurrentThread());
}
if (NS_FAILED(rv) || !aCount) {
if (rv == NS_BASE_STREAM_CLOSED) {
rv = NS_OK;
}
return OnLoadEnd(rv);
}
mTransferred += aCount;
//Notify the timer is the appropriate timeframe has passed
if (mTimerIsActive) {
mProgressEventWasDelayed = true;
} else {
rv = DispatchProgressEvent(NS_LITERAL_STRING(PROGRESS_STR));
NS_ENSURE_SUCCESS(rv, rv);
StartProgressEventTimer();
}
return NS_OK;
}
nsresult
FileReader::OnLoadEnd(nsresult aStatus)
{
// Cancel the progress event timer
ClearProgressEventTimer();
// FileReader must be in DONE stage after an operation
mReadyState = DONE;
nsAutoString successEvent, termEvent;
nsresult rv = DoOnLoadEnd(aStatus, successEvent, termEvent);
NS_ENSURE_SUCCESS(rv, rv);
// Set the status field as appropriate
if (NS_FAILED(aStatus)) {
DispatchError(aStatus, termEvent);
return NS_OK;
}
// Dispatch event to signify end of a successful operation
DispatchProgressEvent(successEvent);
DispatchProgressEvent(termEvent);
return NS_OK;
}
void
FileReader::Abort(ErrorResult& aRv)
{
if (mReadyState != LOADING) {
// XXX The spec doesn't say this
aRv.Throw(NS_ERROR_DOM_FILE_ABORT_ERR);
return;
}
ClearProgressEventTimer();
mReadyState = DONE;
// XXX The spec doesn't say this
mError = new DOMError(GetOwner(), NS_LITERAL_STRING("AbortError"));
// Revert status and result attributes
SetDOMStringToNull(mResult);
mResultArrayBuffer = nullptr;
mAsyncStream = nullptr;
mBlob = nullptr;
//Clean up memory buffer
FreeFileData();
// Dispatch the events
DispatchProgressEvent(NS_LITERAL_STRING(ABORT_STR));
DispatchProgressEvent(NS_LITERAL_STRING(LOADEND_STR));
}
} // dom namespace
} // mozilla namespace