source: webkit/trunk/Source/WebCore/fileapi/FileReader.cpp

Last change on this file was 284075, checked in by [email protected], 4 years ago

Use std::variant instead of WTF::Variant
https://bugs.webkit.org/show_bug.cgi?id=231629

Patch by Alex Christensen <[email protected]> on 2021-10-12
Reviewed by Chris Dumez.

Source/JavaScriptCore:

  • bytecode/StructureStubClearingWatchpoint.h:
  • dfg/DFGSpeculativeJIT.cpp:

(JSC::DFG::SpeculativeJIT::compileCallDOM):

  • jit/AssemblyHelpers.cpp:

(JSC::AssemblyHelpers::branchIfValue):

  • jit/AssemblyHelpers.h:

(JSC::AssemblyHelpers::branchIfTruthy):
(JSC::AssemblyHelpers::branchIfFalsey):

  • jit/SnippetReg.h:
  • jsc.cpp:
  • parser/Lexer.h:
  • parser/VariableEnvironment.h:
  • runtime/BytecodeCacheError.h:
  • runtime/CachePayload.cpp:

(JSC::CachePayload::CachePayload):

  • runtime/CachePayload.h:
  • runtime/CacheUpdate.h:
  • runtime/ISO8601.cpp:

(JSC::ISO8601::parseTimeZoneBracketedAnnotation):

  • runtime/ISO8601.h:
  • wasm/WasmLLIntGenerator.cpp:

Source/WebCore:

  • Modules/async-clipboard/ClipboardItemBindingsDataSource.h:
  • Modules/cache/DOMCacheEngine.h:
  • Modules/fetch/FetchBody.h:
  • Modules/fetch/FetchBodyOwner.h:
  • Modules/fetch/FetchHeaders.h:
  • Modules/fetch/FetchRequest.h:
  • Modules/fetch/FetchResponse.h:
  • Modules/indexeddb/IDBCursor.h:
  • Modules/indexeddb/IDBDatabase.h:
  • Modules/indexeddb/IDBKey.h:
  • Modules/indexeddb/IDBKeyData.h:
  • Modules/indexeddb/IDBKeyPath.h:
  • Modules/indexeddb/IDBRequest.h:
  • Modules/mediacontrols/MediaControlsHost.cpp:

(WebCore::MediaControlsHost::showMediaControlsContextMenu):

  • Modules/mediacontrols/MediaControlsHost.h:
  • Modules/mediastream/MediaDevices.cpp:

(WebCore::createMediaConstraints):

  • Modules/mediastream/MediaDevices.h:
  • Modules/mediastream/MediaTrackConstraints.h:
  • Modules/mediastream/RTCIceServer.h:
  • Modules/mediastream/RTCPeerConnection.h:
  • Modules/mediastream/RTCRtpTransform.h:
  • Modules/mediastream/libwebrtc/LibWebRTCDataChannelHandler.h:
  • Modules/mediastream/libwebrtc/LibWebRTCRtpSenderBackend.h:
  • Modules/paymentrequest/PaymentMethodChangeEvent.h:
  • Modules/paymentrequest/PaymentRequest.h:
  • Modules/push-api/PushEventInit.h:
  • Modules/push-api/PushSubscriptionOptionsInit.h:
  • Modules/speech/SpeechRecognitionUpdate.h:
  • Modules/webaudio/AudioContextOptions.h:
  • Modules/webaudio/AudioNode.h:
  • Modules/webxr/WebXRWebGLLayer.h:
  • accessibility/AXObjectCache.h:
  • accessibility/AccessibilityObjectInterface.h:
  • accessibility/isolatedtree/AXIsolatedTree.h:
  • animation/EffectTiming.h:
  • animation/KeyframeEffect.cpp:

(WebCore::KeyframeEffect::create):

  • animation/KeyframeEffect.h:
  • animation/OptionalEffectTiming.h:
  • bindings/IDLTypes.h:
  • bindings/js/BufferSource.h:
  • bindings/js/JSValueInWrappedObject.h:
  • crypto/CryptoAlgorithm.h:
  • crypto/CryptoKey.h:
  • crypto/SubtleCrypto.h:
  • crypto/parameters/CryptoAlgorithmEcdsaParams.h:
  • crypto/parameters/CryptoAlgorithmHkdfParams.h:
  • crypto/parameters/CryptoAlgorithmHmacKeyParams.h:
  • crypto/parameters/CryptoAlgorithmPbkdf2Params.h:
  • crypto/parameters/CryptoAlgorithmRsaHashedImportParams.h:
  • crypto/parameters/CryptoAlgorithmRsaHashedKeyGenParams.h:
  • css/CSSCustomPropertyValue.h:
  • css/DOMMatrix.cpp:

(WebCore::DOMMatrix::create):

  • css/DOMMatrix.h:
  • css/DOMMatrixReadOnly.cpp:

(WebCore::DOMMatrixReadOnly::create):

  • css/DOMMatrixReadOnly.h:
  • css/FontFace.h:
  • css/StyleRule.h:
  • css/parser/CSSPropertyParserHelpers.h:
  • css/typedom/CSSNumericValue.h:
  • css/typedom/CSSUnparsedValue.h:
  • dom/Document.h:
  • dom/DocumentMarker.h:
  • dom/Element.cpp:

(WebCore::Element::scrollIntoView):
(WebCore::Element::animate):

  • dom/Element.h:
  • dom/EventTarget.h:
  • dom/MessageEvent.h:
  • dom/Node.h:
  • editing/AlternativeTextController.h:
  • editing/TextCheckingHelper.cpp:

(WebCore::TextCheckingHelper::findFirstMisspelledWordOrUngrammaticalPhrase const):

  • editing/TextCheckingHelper.h:
  • editing/TextManipulationController.h:
  • fileapi/Blob.h:
  • fileapi/FileReader.cpp:

(WebCore::FileReader::result const):

  • fileapi/FileReader.h:
  • fileapi/NetworkSendQueue.h:
  • html/DOMFormData.h:
  • html/HTMLAllCollection.cpp:

(WebCore::HTMLAllCollection::namedOrIndexedItemOrItems const):
(WebCore::HTMLAllCollection::namedItemOrItems const):

  • html/HTMLAllCollection.h:
  • html/HTMLDocument.cpp:

(WebCore::HTMLDocument::namedItem):

  • html/HTMLDocument.h:
  • html/HTMLFormControlsCollection.cpp:

(WebCore::HTMLFormControlsCollection::namedItemOrItems const):

  • html/HTMLFormControlsCollection.h:
  • html/HTMLFormElement.cpp:

(WebCore::HTMLFormElement::namedItem):

  • html/HTMLFormElement.h:
  • html/HTMLMediaElement.h:
  • html/HTMLOptionsCollection.h:
  • html/HTMLSelectElement.h:
  • html/ImageBitmap.h:
  • html/OffscreenCanvas.h:
  • html/URLSearchParams.cpp:

(WebCore::URLSearchParams::create):

  • html/URLSearchParams.h:
  • html/canvas/CanvasRenderingContext2DBase.h:
  • html/canvas/CanvasStyle.h:
  • html/canvas/WebGL2RenderingContext.h:
  • html/canvas/WebGLAny.h:
  • html/canvas/WebGLMultiDraw.h:
  • html/canvas/WebGLRenderingContextBase.h:
  • html/track/TrackEvent.h:
  • html/track/VTTCue.h:
  • inspector/InspectorCanvas.h:
  • inspector/InspectorShaderProgram.h:
  • layout/integration/InlineIteratorBox.h:
  • layout/integration/InlineIteratorLine.h:
  • page/DiagnosticLoggingClient.h:
  • page/IntersectionObserver.h:
  • page/Page.h:
  • page/Performance.h:
  • page/PerformanceMeasureOptions.h:
  • page/PerformanceUserTiming.cpp:

(WebCore::PerformanceUserTiming::convertMarkToTimestamp const):

  • page/PerformanceUserTiming.h:
  • page/scrolling/ScrollingCoordinator.h:
  • platform/PasteboardCustomData.cpp:

(WebCore::copyPlatformData):
(WebCore::PasteboardCustomData::forEachPlatformStringOrBuffer const):

  • platform/PasteboardCustomData.h:
  • platform/SharedBuffer.h:
  • platform/audio/AudioStreamDescription.h:
  • platform/encryptedmedia/CDMProxy.h:
  • platform/graphics/DecodingOptions.h:
  • platform/graphics/FontCascadeDescription.h:
  • platform/graphics/Gradient.h:
  • platform/graphics/InlinePathData.h:
  • platform/graphics/cocoa/SourceBufferParser.h:
  • platform/graphics/cocoa/SourceBufferParserWebM.h:
  • platform/graphics/displaylists/DisplayListResourceHeap.h:
  • platform/mediastream/mac/DisplayCaptureSourceMac.h:
  • platform/mock/MockMediaDevice.h:
  • platform/network/DNS.h:
  • platform/network/FormData.h:
  • platform/sql/SQLValue.h:
  • platform/xr/PlatformXR.h:
  • rendering/RenderBlockFlow.h:
  • testing/TypeConversions.h:
  • workers/SharedWorker.cpp:

(WebCore::SharedWorker::SharedWorker):

  • workers/SharedWorker.h:
  • workers/service/ExtendableMessageEvent.h:
  • workers/service/ServiceWorkerTypes.h:
  • xml/XMLHttpRequest.h:

Source/WebKit:

  • NetworkProcess/NetworkLoadChecker.h:
  • NetworkProcess/cache/NetworkCacheData.h:
  • Platform/IPC/ArgumentCoders.h:

(IPC::VariantCoder::encode):
(IPC::VariantCoder::decode):

  • Platform/IPC/Attachment.h:
  • Platform/IPC/MessageReceiveQueueMap.h:
  • Shared/SessionState.h:
  • Shared/WebCoreArgumentCoders.h:
  • Shared/WebPreferencesStore.h:
  • Shared/mac/MediaFormatReader/MediaSampleCursor.h:
  • UIProcess/API/APIWebAuthenticationPanel.h:
  • UIProcess/API/C/WKMockMediaDevice.cpp:

(WKAddMockMediaDevice):

  • UIProcess/API/Cocoa/WKWebView.mm:

(-[WKWebView _showSafeBrowsingWarning:completionHandler:]):
(-[WKWebView _showSafeBrowsingWarningWithURL:title:warning:detailsWithLinks:completionHandler:]):

  • UIProcess/API/Cocoa/WKWebViewInternal.h:
  • UIProcess/API/Cocoa/_WKWebAuthenticationPanel.mm:

(-[_WKWebAuthenticationPanel makeCredentialWithChallenge:origin:options:completionHandler:]):
(-[_WKWebAuthenticationPanel getAssertionWithChallenge:origin:options:completionHandler:]):

  • UIProcess/Automation/SimulatedInputDispatcher.h:
  • UIProcess/Automation/WebAutomationSession.cpp:

(WebKit::WebAutomationSession::simulateKeyboardInteraction):

  • UIProcess/Automation/WebAutomationSession.h:
  • UIProcess/Automation/ios/WebAutomationSessionIOS.mm:

(WebKit::WebAutomationSession::platformSimulateKeyboardInteraction):

  • UIProcess/Automation/mac/WebAutomationSessionMac.mm:

(WebKit::WebAutomationSession::platformSimulateKeyboardInteraction):

  • UIProcess/Cocoa/SOAuthorization/SubFrameSOAuthorizationSession.h:
  • UIProcess/Cocoa/WKSafeBrowsingWarning.h:
  • UIProcess/Cocoa/WKSafeBrowsingWarning.mm:

(-[WKSafeBrowsingWarning initWithFrame:safeBrowsingWarning:completionHandler:]):

  • UIProcess/Cocoa/WebViewImpl.h:
  • UIProcess/Cocoa/WebViewImpl.mm:

(WebKit::WebViewImpl::showSafeBrowsingWarning):

  • UIProcess/PageClient.h:

(WebKit::PageClient::showSafeBrowsingWarning):

  • UIProcess/ProcessThrottler.h:
  • UIProcess/WebAuthentication/Authenticator.h:
  • UIProcess/WebAuthentication/AuthenticatorManager.cpp:

(WebKit::WebCore::getRpId):
(WebKit::WebCore::getUserName):

  • UIProcess/WebAuthentication/AuthenticatorManager.h:
  • UIProcess/WebAuthentication/WebAuthenticationRequestData.cpp:

(WebKit::getClientDataType):
(WebKit::getUserVerificationRequirement):

  • UIProcess/WebAuthentication/WebAuthenticationRequestData.h:
  • UIProcess/WebAuthentication/WebAuthenticatorCoordinatorProxy.cpp:

(WebKit::WebAuthenticatorCoordinatorProxy::handleRequest):

  • UIProcess/WebPageProxy.cpp:

(WebKit::WebPageProxy::receivedPolicyDecision):

  • UIProcess/WebPageProxy.h:
  • UIProcess/ios/PageClientImplIOS.h:
  • UIProcess/ios/PageClientImplIOS.mm:

(WebKit::PageClientImpl::showSafeBrowsingWarning):

  • UIProcess/mac/PageClientImplMac.h:
  • UIProcess/mac/PageClientImplMac.mm:

(WebKit::PageClientImpl::showSafeBrowsingWarning):

  • WebAuthnProcess/WebAuthnConnectionToWebProcess.cpp:

(WebKit::WebAuthnConnectionToWebProcess::handleRequest):

  • WebProcess/GPU/graphics/ImageBufferBackendHandle.h:
  • WebProcess/Storage/WebServiceWorkerFetchTaskClient.h:
  • WebProcess/WebPage/RemoteLayerTree/PlatformCAAnimationRemote.h:

Source/WebKitLegacy/mac:

  • DOM/DOMHTMLSelectElement.mm:

(-[DOMHTMLSelectElement add:before:]):

Source/WTF:

  • wtf/LikelyDenseUnsignedIntegerSet.h:
  • wtf/SmallSet.h:
  • wtf/text/TextBreakIterator.cpp:

(WTF::mapModeToBackingIterator):

  • wtf/text/TextBreakIterator.h:
  • wtf/text/cocoa/TextBreakIteratorInternalICUCocoa.cpp:

(WTF::mapModeToBackingIterator):

  • Property svn:eol-style set to native
File size: 7.4 KB
Line 
1/*
2 * Copyright (C) 2010 Google Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31#include "config.h"
32#include "FileReader.h"
33
34#include "DOMException.h"
35#include "EventLoop.h"
36#include "EventNames.h"
37#include "Exception.h"
38#include "ExceptionCode.h"
39#include "File.h"
40#include "Logging.h"
41#include "ProgressEvent.h"
42#include "ScriptExecutionContext.h"
43#include <JavaScriptCore/ArrayBuffer.h>
44#include <wtf/IsoMallocInlines.h>
45#include <wtf/text/CString.h>
46
47namespace WebCore {
48
49WTF_MAKE_ISO_ALLOCATED_IMPL(FileReader);
50
51// Fire the progress event at least every 50ms.
52static const auto progressNotificationInterval = 50_ms;
53
54Ref<FileReader> FileReader::create(ScriptExecutionContext& context)
55{
56 auto fileReader = adoptRef(*new FileReader(context));
57 fileReader->suspendIfNeeded();
58 return fileReader;
59}
60
61FileReader::FileReader(ScriptExecutionContext& context)
62 : ActiveDOMObject(&context)
63{
64}
65
66FileReader::~FileReader()
67{
68 if (m_loader)
69 m_loader->cancel();
70}
71
72const char* FileReader::activeDOMObjectName() const
73{
74 return "FileReader";
75}
76
77void FileReader::stop()
78{
79 m_pendingTasks.clear();
80 if (m_loader) {
81 m_loader->cancel();
82 m_loader = nullptr;
83 }
84 m_state = DONE;
85}
86
87bool FileReader::virtualHasPendingActivity() const
88{
89 return m_state == LOADING;
90}
91
92ExceptionOr<void> FileReader::readAsArrayBuffer(Blob& blob)
93{
94 LOG(FileAPI, "FileReader: reading as array buffer: %s %s\n", blob.url().string().utf8().data(), is<File>(blob) ? downcast<File>(blob).path().utf8().data() : "");
95
96 return readInternal(blob, FileReaderLoader::ReadAsArrayBuffer);
97}
98
99ExceptionOr<void> FileReader::readAsBinaryString(Blob& blob)
100{
101 LOG(FileAPI, "FileReader: reading as binary: %s %s\n", blob.url().string().utf8().data(), is<File>(blob) ? downcast<File>(blob).path().utf8().data() : "");
102
103 return readInternal(blob, FileReaderLoader::ReadAsBinaryString);
104}
105
106ExceptionOr<void> FileReader::readAsText(Blob& blob, const String& encoding)
107{
108 LOG(FileAPI, "FileReader: reading as text: %s %s\n", blob.url().string().utf8().data(), is<File>(blob) ? downcast<File>(blob).path().utf8().data() : "");
109
110 m_encoding = encoding;
111 return readInternal(blob, FileReaderLoader::ReadAsText);
112}
113
114ExceptionOr<void> FileReader::readAsDataURL(Blob& blob)
115{
116 LOG(FileAPI, "FileReader: reading as data URL: %s %s\n", blob.url().string().utf8().data(), is<File>(blob) ? downcast<File>(blob).path().utf8().data() : "");
117
118 return readInternal(blob, FileReaderLoader::ReadAsDataURL);
119}
120
121ExceptionOr<void> FileReader::readInternal(Blob& blob, FileReaderLoader::ReadType type)
122{
123 // If multiple concurrent read methods are called on the same FileReader, InvalidStateError should be thrown when the state is LOADING.
124 if (m_state == LOADING)
125 return Exception { InvalidStateError };
126
127 m_blob = &blob;
128 m_readType = type;
129 m_state = LOADING;
130 m_error = nullptr;
131
132 m_loader = makeUnique<FileReaderLoader>(m_readType, static_cast<FileReaderLoaderClient*>(this));
133 m_loader->setEncoding(m_encoding);
134 m_loader->setDataType(m_blob->type());
135 m_loader->start(scriptExecutionContext(), blob);
136
137 return { };
138}
139
140void FileReader::abort()
141{
142 LOG(FileAPI, "FileReader: aborting\n");
143 if (m_state != LOADING || m_finishedLoading)
144 return;
145
146 m_pendingTasks.clear();
147 stop();
148 m_error = DOMException::create(Exception { AbortError });
149
150 Ref protectedThis { *this };
151 fireEvent(eventNames().abortEvent);
152 fireEvent(eventNames().loadendEvent);
153}
154
155void FileReader::didStartLoading()
156{
157 enqueueTask([this] {
158 fireEvent(eventNames().loadstartEvent);
159 });
160}
161
162void FileReader::didReceiveData()
163{
164 enqueueTask([this] {
165 auto now = MonotonicTime::now();
166 if (std::isnan(m_lastProgressNotificationTime)) {
167 m_lastProgressNotificationTime = now;
168 return;
169 }
170 if (now - m_lastProgressNotificationTime > progressNotificationInterval) {
171 fireEvent(eventNames().progressEvent);
172 m_lastProgressNotificationTime = now;
173 }
174 });
175}
176
177void FileReader::didFinishLoading()
178{
179 enqueueTask([this] {
180 if (m_state == DONE)
181 return;
182 m_finishedLoading = true;
183 fireEvent(eventNames().progressEvent);
184 if (m_state == DONE)
185 return;
186 m_state = DONE;
187 fireEvent(eventNames().loadEvent);
188 fireEvent(eventNames().loadendEvent);
189 });
190}
191
192void FileReader::didFail(ExceptionCode errorCode)
193{
194 enqueueTask([this, errorCode] {
195 if (m_state == DONE)
196 return;
197 m_state = DONE;
198
199 m_error = DOMException::create(Exception { errorCode });
200
201 fireEvent(eventNames().errorEvent);
202 fireEvent(eventNames().loadendEvent);
203 });
204}
205
206void FileReader::fireEvent(const AtomString& type)
207{
208 ASSERT(isAllowedToRunScript());
209 dispatchEvent(ProgressEvent::create(type, true, m_loader ? m_loader->bytesLoaded() : 0, m_loader ? m_loader->totalBytes() : 0));
210}
211
212std::optional<std::variant<String, RefPtr<JSC::ArrayBuffer>>> FileReader::result() const
213{
214 if (!m_loader || m_error || m_state != DONE)
215 return std::nullopt;
216 if (m_readType == FileReaderLoader::ReadAsArrayBuffer) {
217 auto result = m_loader->arrayBufferResult();
218 if (!result)
219 return std::nullopt;
220 return { result };
221 }
222 String result = m_loader->stringResult();
223 if (result.isNull())
224 return std::nullopt;
225 return { WTFMove(result) };
226}
227
228void FileReader::enqueueTask(Function<void()>&& task)
229{
230 if (!scriptExecutionContext())
231 return;
232
233 static uint64_t taskIdentifierSeed = 0;
234 uint64_t taskIdentifier = ++taskIdentifierSeed;
235 m_pendingTasks.add(taskIdentifier, WTFMove(task));
236 queueTaskKeepingObjectAlive(*this, TaskSource::FileReading, [this, pendingActivity = makePendingActivity(*this), taskIdentifier] {
237 auto task = m_pendingTasks.take(taskIdentifier);
238 if (task && !isContextStopped())
239 task();
240 });
241}
242
243} // namespace WebCore
Note: See TracBrowser for help on using the repository browser.